【问题标题】:Lua table length function override not workingLua表长度函数覆盖不起作用
【发布时间】:2014-11-01 05:39:08
【问题描述】:

如何更改 Lua 中表的长度运算符 (#),手册建议在元表中分配 __len 函数,然后将该元表分配给我要覆盖的表,但这并没有没有按预期工作?我没有在 C 端覆盖它的选项。

turtles = {1,2,3}
setmetatable(turtles, {__len = function(mytable) return 5 end})

print(#turtles)
--returns 3, should return 5

【问题讨论】:

标签: lua lua-table metatable


【解决方案1】:

您必须使用 Lua 5.1。自 Lua 5.2 起支持表上的 __len 元方法。

Lua 5.1 reference manual中,如果操作数是表,直接返回原始表长度。

“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 reference manual中,如果操作数是表,检查__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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    相关资源
    最近更新 更多