Lua String Optimisation
String optimisation builds a long string with table.concat, not with .. in a loop. The .. operator joins two strings into a fresh string.
Count joins in a .. loop
Each pass joins one more letter onto the string. Four passes run four joins.
local joins = 0
local s = ""
for i = 1, 4 do
s = s .. "a"
joins = joins + 1
end
print(joins)
print(s)Join pieces once with table.concat
Pieces are collected in a table first. One join call then links them with a separator.
local parts = {}
for i = 1, 4 do parts[i] = "b" end
local s = table.concat(parts, "-")
print(#parts)
print(s)Both routes reach the same string
The .. loop and the table.concat route build the same digits. The check prints true.
local a = ""
for i = 1, 3 do a = a .. i end
local parts = {}
for i = 1, 3 do parts[i] = tostring(i) end
local b = table.concat(parts)
print(a == b)
print(b)Example
local parts = {}
for i = 1, 3 do parts[i] = "item-" .. i end
local line = table.concat(parts, " ")
print(line)
print(#parts)Key points
- Concatenation: joining strings into one longer string.
- The .. operator builds a fresh string each time it runs.
- table.concat: a function that joins a list of pieces in one call.
- Collect pieces in a table during the loop, then join them once after the loop.
- Use .. for a few joins, and table.concat for many joins in a loop.
In this example, the loop collects one piece per pass in a table. table.concat then joins the pieces with spaces. The prints show the joined line and the piece count.
Note
the joined result is the same either way, only the joining work changes.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A loop must build a long string from hundreds of pieces. Which approach is best?