Adding and Reading Elements
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 14 of 73.
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.
One more tool for your belt: table.freeze(t) makes a table read-only at runtime — any later attempt to modify it raises an error. It's Luau's answer for constant data (configuration, fixed level lists) that must never change after creation.
Challenge
EasyCreate a typed array queue: {string} initialized with "save" and "load". Then:
- append
"quit"withtable.insert - insert
"help"at position 1 - remove the last command with
table.remove, storing the returned value
Finally print, each on its own line:
- the removed command
- how many commands remain
- the first command in the queue
queue[10]— a slot that holds nothing
Try it yourself
-- Write code here
-- 1) declare queue: {string} with "save" and "load"
-- 2) append "quit", insert "help" at position 1
-- 3) remove the last command, then print the four values
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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 ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe '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 TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps