Trying to concatenate other types, like nil or a table, will result in an error.
Strings in Lua are immutable, so the concatenation result (
message in this example) is a brand new string.
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.
Here’s a benchmark comparsion (using hyperfine) from running the
.. example as
slow.lua and running the
table.concat example as
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.
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.