我一直在学习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)或类似的方式调用它,但这违背了初衷。谢谢。
tostring()
效果接近拼接的基础工作。Lua源代码有相当不错的注释,但这并不是小菜一碟的。第一步应该是消除自动转换为字符串,第二步应该是扩大使用__concat
。 - RBerteigrange(6, 6)
这样的东西吧?或者试试r [[6..6]]
? :P - greatwolf