如何在 Lua 中更改表的长度运算符( #
),手册建议分配 __len
在元表中运行,然后将该元表分配给我想要覆盖的表,但这不能按预期工作?我没有选择在 C 端覆盖它。
turtles = {1,2,3}
setmetatable(turtles, {__len = function(mytable) return 5 end})
print(#turtles)
--returns 3, should return 5
最佳答案
您必须使用 Lua 5.1。 __len
从 Lua 5.2 开始支持表上的元方法。
在 Lua 5.1 reference manual , 如果操作数是表,则直接返回原始表长度。
"len": the # operation.
function len_event (op) if type(op) == "string" then return strlen(op) -- primitive string length elseif type(op) == "table" then return #op -- primitive table length else local h = metatable(op).__len if h then -- call the handler with the operand return (h(op)) else -- no handler available: default behavior error(···) end end end
在 Lua 5.2 reference manual , 如果操作数是表,检查
__len
是否元方法可用。"len": the # operation.
function len_event (op) if type(op) == "string" then return strlen(op) -- primitive string length else local h = metatable(op).__len if h then return (h(op)) -- call handler with the operand elseif type(op) == "table" then return #op -- primitive table length else -- no handler available: error error(···) end end end
关于Lua 表长度函数覆盖不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25716851/