How to prevent a C Stack Overflow

I have been testing with metatables and I got a new error when using __concat.

local mt = setmetatable({"Hello", {
__concat = function(t1, t2)
return t1..t2
end
})

print(mt.." World!")

It is recursive since t1 of the concat metamethos returns a table which invokes the concat method again and again.

To solve it one way is to make t1 not a table in order to avoid the __concat and instead to extract the strings out of it like so:


local mt = setmetatable({"Hello", {
__concat = function(t1, t2)
return t1[1]..t2
end
})

print(mt.." World!")

You can use a for loop if you have multiple strings in the table and want to concat them all together if that’s what you want.