Lua表长度函数覆盖无效



如何在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。自Lua 5.2以来,支持表上的__len元方法。

在Lua 5.1参考手册中,如果操作数是表,则直接返回基元表长度。

"len":#操作。

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参考手册中,如果操作数是一个表,请检查__len元方法是否可用。

"len":#操作。

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

最新更新