Skip to main content
Version: 8.2411.x.x RR

String

As in Java, strings in Lua are immutable. So whenever you concatenate strings, the Lua interpreter will reallocate the buffer for the new string and copy everything in the new buffer. If you have a lot of them, this can end up in a memory waste but, moreover, it will have performance drawbacks as it has then to allocate/copy/free a lot of memory, which is expensive.

Bad Pattern

myString = myString .. something
myString = mString .. "today its raining"
...
myString = myString .. "that's all"

This leads to a lot of allocate/copy/free.

Good Pattern

Using a table to collect the strings and concatenating it in the end is much more performant and leads to much fewer allocate/copy/free cycles.

myString = { }
table.insert(myString, something)
table.insert(myString, "today it's raining")
...
table.insert(myString, "that's all")
result = table.concat(myString)

There is as well a possibility to generate a list of comma-separated words from this table like that

result = table.concat(myString, ",")

Of course, any other string may be used for separating the collected strings.