Lua 表长度函数覆盖不起作用

标签 lua lua-table metatable

如何在 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/

相关文章:

merge - 如何合并两个表并覆盖两个表中的元素?

Lua CLI 安装 - 如何让终端命令 'lua' 在 OSX 上运行?

lua 小数点在 -0.1 到 0.1 之间(不包括)

lua - 如何使用 Lua 读取 16 位 png?

c# - LuaInterface:如何访问多维lua表?

c++ - 路亚 "attempt to index a nil value"

lua - __add 在自定义 Vector3 类中不起作用

c++ - 使用 C API 覆盖 Lua 中的赋值运算符

arrays - Lua如何从表中获取数据

lua - Love2d 和径向重力