Skip to content
1 / 5
Lesson 01 of 05

Table Library Deep Dive

Master every table function for powerful array and dictionary manipulation.

The table library provides essential functions for data manipulation.

Insertion:

  • table.insert(t, value) — append to end
  • table.insert(t, pos, value) — insert at position (shifts others)

Removal:

  • table.remove(t) — remove and return last element
  • table.remove(t, pos) — remove at position (shifts others)

Sorting:

  • table.sort(t) — sorts ascending using <
  • table.sort(t, comp) — custom comparator: comp(a, b) returns true if a should come before b

Joining:

  • table.concat(t, sep, i, j) — joins array elements into a string

Packing/Unpacking:

  • table.pack(...) — packs varargs into table with .n count
  • table.unpack(t, i, j) — unpacks table into multiple values

Advanced:

  • table.move(src, f, e, t, dest) — efficiently copies elements between tables
  • table.create(n, val) — pre-allocate array (performance boost)
  • table.find(t, value) — find index of value in array
luau
1-- Insert and remove
2local queue = {"first", "second", "third"}
3table.insert(queue, "fourth") -- append
4table.insert(queue, 2, "inserted") -- at position 2
5local removed = table.remove(queue, 1) -- remove first
6print(removed) -- "first"
7
8-- Sort with comparator
9local players = {
10 {name = "Alex", score = 150},
11 {name = "Sam", score = 300},
12 {name = "Jordan", score = 75},
13}
14
15table.sort(players, function(a, b)
16 return a.score > b.score -- descending by score
17end)
18
19for i, p in ipairs(players) do
20 print(i, p.name, p.score)
21end
22-- 1 Sam 300
23-- 2 Alex 150
24-- 3 Jordan 75
25
26-- Concat
27local fruits = {"apple", "banana", "cherry"}
28print(table.concat(fruits, ", ")) -- "apple, banana, cherry"
29
30-- Pre-allocate for performance
31local bigArray = table.create(1000, 0) -- 1000 zeros
32
33-- Find value
34local items = {"sword", "shield", "potion"}
35local idx = table.find(items, "shield") -- 2
READY · 35 lines