Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua/print table error : ( attempt to concatenate a table value)

Tags:

lua

I got a simple code like:

table = {}
print(table.."hello")

then got a error like the title. I know i need to use tostring(table) to fix it . Why table or other types can't convert to string to concatenate a String automatically except number type ?

print(table) is available But print(table.."hello") is not .

Does lua have some rules?

Thanks you.

like image 483
littlecode Avatar asked Nov 27 '25 18:11

littlecode


1 Answers

Why table or other types can't convert to string to concatenate a String automatically except number type?

This is a deliberate choice made by the Lua language designers. Strings and numbers are coerced: Every operation that expects a string will also accept a number and tostring it; every operation that expects a number will also accept a string and tonumber it.

Coercion is an operation applied to strings. Numbers will be tostringed. Any other type won't. For other primitive types like bools and nils this is somewhat questionable, since they can be converted to string without issue. For tables it's reasonable though since they are a reference type.

Unlike other languages which make such decisions for you, Lua is highly metaprogrammable: You can simply override the decision! In this case, metatables are the solution, specifically the __concat metamethod which gets called if concatenation (..) is applied to two values of which one has the metamethod (and is neither a string or number):

table = setmetatable({}, {
    __concat = function(left, right)
        if type(left) == "string" then
            return left .. tostring(right)
        end
        return tostring(left) .. tostring(right)
    end
})
print(table .. "hello") -- hellotable: 0x563eb139bea0

You could even extend this to primitive types (nils, booleans), some other reference types (functions, coroutines) using debug.setmetatable, but I'd advise against this.

like image 126
LMD Avatar answered Nov 30 '25 14:11

LMD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!