Lua - handling concatenation of List
We use .. operator to concatenate elements in Lua. We can use __concat() metamethod to implement concatenation of list items with any string using .. operator. We can define how to concatenate elements of the list.
Syntax
__concat(table, value)
where
table represents the current table whose behavior is to be modified.
value to be used while concatenation.
Example - Concatenation of List without __concat() implementation
.. operator works with numbers and strings. In case of list, it will throw error as shown below−
main.lua
-- list with non-contigous indexes
local list = {"Welcome", "To", "Tutorialspoint"}
-- concatenate list using space string
local concatenatedString = list.." "
print(concatenatedString)
Output
When we run the above code, we will get the following output−
lua: main.lua:5: attempt to concatenate a table value (local 'list') stack traceback: main.lua:5: in main chunk [C]: in ?
As list is a table, we cannot directly concatenate list items with string using .. operator.
Example - Solution to concatenate list with String
We can implement __concat(table, value) metamethod to concatenate table with string−
main.lua
-- list of strings
local list = {"Welcome", "To", "Tutorialspoint"}
-- create a metatable for concatenation
local metatableConcat = {
__concat = function(list, value)
return table.concat(list, value)
end
}
setmetatable(list,metatableConcat )
-- concatenate list using space
local concatenatedString = list.." "
-- print the concatenated string
print(concatenatedString)
Output
When the above code is built and executed, it produces the following result −
Welcome To Tutorialspoint
Explanation
local list = {"Welcome", "To", "Tutorialspoint"} is used to create a list of strings.
local metatableConcat is used to create a meta table with __concat() method.
__concat = function(list, value) is the implementation of metamethod __concat(table, value) method.
return table.concat(list, value)concatenates entries of the list using the value as separator.
When list.." " is called then __concat metamethod is called and a concatenated string is returned.