Menu
Coddy logo textTech

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 element

table.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 icon

Challenge

Easy

Create a typed array queue: {string} initialized with "save" and "load". Then:

  1. append "quit" with table.insert
  2. insert "help" at position 1
  3. remove the last command with table.remove, storing the returned value

Finally print, each on its own line:

  1. the removed command
  2. how many commands remain
  3. the first command in the queue
  4. 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To Luau