元方法的问题
Trouble with metamethods
我想重写这段代码
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)
采用 tb = setmetable({},(metamethod)
风格,我想到了这个
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))
我想知道为什么它不起作用,我承认我不知道我在做什么以及这个 post 需要多少字 ;-;
如果我没理解错的话,你想要这个。
function tb(b)
return setmetatable({b = b},{__concat = function(s1,s2)
return s1.b + s2.b
end})
end
print(tb(3)..tb(4))
print(ins(2)..ins(3))
解析为
print( 2 .. 3)
解析为
print("2" .. "3")
解析为
print("23")
输出23
两个数字都隐式转换为它们的字符串表示形式,然后将它们连接成一个字符串 "23"
来自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).
您的第一个代码段连接了两个表格,而您的第二个代码段连接了两个数字。所以在第二种情况下,__concat
元方法永远不会被调用。
如果您想将这两个数字相加,只需使用 print(ins(2) + ins(3))
。我不明白为什么要替换简单的算术运算符。那只会增加不必要的混乱。
您必须将 tb
与某些内容连接起来才能调用您的 __concat
,而不是它的字段。
我想重写这段代码
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)
采用 tb = setmetable({},(metamethod)
风格,我想到了这个
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))
我想知道为什么它不起作用,我承认我不知道我在做什么以及这个 post 需要多少字 ;-;
如果我没理解错的话,你想要这个。
function tb(b)
return setmetatable({b = b},{__concat = function(s1,s2)
return s1.b + s2.b
end})
end
print(tb(3)..tb(4))
print(ins(2)..ins(3))
解析为
print( 2 .. 3)
解析为
print("2" .. "3")
解析为
print("23")
输出23
两个数字都隐式转换为它们的字符串表示形式,然后将它们连接成一个字符串 "23"
来自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).
您的第一个代码段连接了两个表格,而您的第二个代码段连接了两个数字。所以在第二种情况下,__concat
元方法永远不会被调用。
如果您想将这两个数字相加,只需使用 print(ins(2) + ins(3))
。我不明白为什么要替换简单的算术运算符。那只会增加不必要的混乱。
您必须将 tb
与某些内容连接起来才能调用您的 __concat
,而不是它的字段。