gpt4 book ai didi

Lua 自定义数字串联

转载 作者:行者123 更新时间:2023-12-05 00:05:41 24 4
gpt4 key购买 nike

我一直在学习 Lua 中的元表,我想像在 Ruby 中一样实现范围运算符,所以我使用了这个模型

debug.setmetatable(1, {
__concat = function(a, b)
if a > b then
error(table.concat({
"attempt to create a range of values with a",
"minimum larger than the maximum"
}, " "))
elseif a == b then
return a
else
return unpack((function(nStart,nEnd)
local nTable = {}
for it = nStart,nEnd do
table.insert(nTable, it)
end
return nTable
end)(a, b))
end
end
})

print(6 .. 6)

但似乎它继续使用默认行为。有什么办法可以让它发挥作用吗?我知道我可以创建一个函数来模拟行为并使用 range(n,n2) 或类似方法调用它,但这违背了目的。谢谢。

最佳答案

请查看 section 3.4.5 Lua 5.2 手册。

The string concatenation operator in Lua is denoted by two dots ('..'). If both operands are strings or numbers, then they are converted to strings according to the rules mentioned in §3.4.2. Otherwise, the __concat metamethod is called (see §2.4).



如果您想更改此行为,请查看 lvm.c ,特别是 luaV_concat 功能。

关于Lua 自定义数字串联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20152511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com