Menu
CoddyTech

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

challenge icon

Challenge

Easy

Grow and shrink a typed list of moves.

  1. Declare local moves: {string} = {"jump", "run"}.
  2. Append "duck" with table.insert, then insert "crawl" at position 1.
  3. Store table.remove(moves) in local removed, then print removed, #moves, moves[1] and moves[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

Practice on your own: Online Luau compiler