The most straightforward way to concatenate (or combine) strings in Lua is to use the dedicated string concatenation operator, which is two periods (..
).
Numbers are coerced to strings. For fine-grained control over number formatting, use string.format, which behaves mostly like C’s printf.
Trying to concatenate other types, like nil or a table, will result in an error.
Note that Lua doesn’t have syntactic sugar for augmented assignment. The following is invalid syntax.
Strings in Lua are immutable, so the concatenation result (message
in this example) is a brand new string.
table.concat
If you need to perform many concatenation operations, using the concatenation operator can be slow because Lua has to keep reallocating memory to create new strings.
As a result, it can be much faster to use table.concat.
Here’s a benchmark comparsion (using hyperfine) from running the ..
example as slow.lua
and running the table.concat
example as fast.lua
.
The difference probably doesn’t matter in most cases, but it’s a good optimization to be aware of.
table.concat
can also be easier to use because it can take a separator argument to add between elements.
It can also take start and end indexes. Keep in mind that Lua arrays start with index 1.
Direct Approach
Depending on your use case, you might be able to save some memory usage over table.concat
by generating the result directly.
Originally published at https://www.dannyguo.com on December 28, 2020.