Adding and Reading Elements
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 14 of 80.
You already grow and shrink Lua tables with table.insert and table.remove: both work exactly the same on typed arrays. The difference is that Luau now checks what you insert: pushing a string into a {number} array is flagged while you type, not discovered by a confused player at runtime.
local queue: {string} = {"save", "load"}
table.insert(queue, "quit") -- append at the end
table.insert(queue, 1, "help") -- insert at position 1, shifting the rest
local last = table.remove(queue) -- removes AND returns the last elementtable.remove(t) takes the last element out and hands it back to you; table.remove(t, 1) removes the first one and shifts everything down. Because the array is typed {string}, Luau knows the returned value is a string.
Reading is just as forgiving as plain Lua: an index that holds nothing, queue[0], queue[-1], or anything past #queue, quietly evaluates to nil. No error is raised, so check for nil before using a value you're not sure exists.
Challenge
EasyGrow and shrink a typed list of moves.
- Declare
local moves: {string} = {"jump", "run"}. - Append
"duck"withtable.insert, then insert"crawl"at position 1. - Store
table.remove(moves)inlocal removed, then printremoved,#moves,moves[1]andmoves[10].
Press Run Code: the output shows duck, 3, crawl and nil.
Try it yourself
-- 1) declare moves: {string} with "jump" and "run"
-- 2) append "duck", insert "crawl" at position 1
-- 3) remove the last move, then print the four values
All lessons in Introduction To Luau
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and MapsPractice on your own: Online Luau compiler