Search code examples
lua

Trouble with metamethods


i wanted to rewrite this code

local tb = {}


local meta = {}

function tb.new(b)
local super = {}
super.b = b

setmetatable(super,meta)

return super
end

function tb.add(s1,s2)

return s1.b+s2.b

end

meta.__concat = tb.add

f= tb.new(3)
t= tb.new(4)

print(f..t)

in tb = setmetable({},(metamethod) style and i came up with this


 local tb = setmetatable({},{__concat = function(a,b)

return a+b
end
})

function ins(a)

tb.a = a

return tb.a

end

print(ins(2)..ins(3))

i want to know why its not working , i admit i got no idea what im doing and how many words does this post need ;-;


Solution

  • print(ins(2)..ins(3))
    

    resolves to

    print( 2 .. 3)
    

    which resolves to

    print("2" .. "3")
    

    which resolves to

    print("23")
    

    which outputs 23

    Both numbers are implicitly converted to their string representation, then they are concatenated to a single string "23"

    From the Lua 5.4 Reference Manual: 3.4.6 Concatenation:

    The string concatenation operator in Lua is denoted by two dots ('..'). If both operands are strings or numbers, then the numbers are converted to strings in a non-specified format (see §3.4.3). Otherwise, the __concat metamethod is called (see §2.4).

    Your first snippet concatenates two tables while your second snippet concatenates two numbers. So in the second case the __concat metamethod is never invoked.

    Just use print(ins(2) + ins(3)) if you want to add those two numbers. I don't see why you should replace simple arithmetic operators. That just adds unnecessary confusion.

    You would have to concatenate tb with something to invoke your __concat, not its fields.