Lua Table Optimisation
Table optimisation avoids creating a new table on every loop pass. A scratch table is a table a loop reuses for temporary results.
Count tables made inside a loop
A helper makes each fresh table and counts it. Three passes make three tables.
local made = 0
local function newTable() made = made + 1 return {} end
local total = 0
for i = 1, 3 do
local t = newTable()
t[1] = i
total = total + t[1]
end
print(made)
print(total)Reuse one table across passes
The helper runs once, before the loop. The same table serves all three passes, and the total is unchanged.
local made = 0
local function newTable() made = made + 1 return {} end
local t = newTable()
local total = 0
for i = 1, 3 do
t[1] = i
total = total + t[1]
end
print(made)
print(total)Overwrite every slot you reuse
A reused slot keeps its old value until it is overwritten. The second slot here still keeps its old value.
local t = {10, 20}
t[1] = 5
print(t[1], t[2])Example
local made = 0
local function newTable() made = made + 1 return {} end
local scratch = newTable()
local total = 0
for i = 1, 4 do
scratch[1] = i
scratch[2] = i * i
total = total + scratch[1] + scratch[2]
end
print(made)
print(total)
print(scratch[1], scratch[2])Key points
- Creation counter: a variable that grows by one each time a new table is made.
- Reuse: using the same table again instead of making a fresh one.
- Make a scratch table once, before the loop, and overwrite its slots inside the loop.
- A reused table keeps only the latest result, so older results are lost unless copied elsewhere.
- Keep a scratch table separate from results the program must keep.
In this example, one scratch table is made before the loop. Each pass overwrites both slots and adds them to the total. The final prints show one table made, the total, and only the last pass in the scratch table.
Note
a table made inside a loop is fine when each pass must keep its own result.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A loop needs only the current pair of numbers on each pass. Which approach makes the fewest tables?