Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Lua表格长度函数覆盖不起作用_Lua_Lua Table_Metatable - Fatal编程技术网

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

Lua表格长度函数覆盖不起作用,lua,lua-table,metatable,Lua,Lua Table,Metatable,如何更改Lua中表的长度运算符(#),手册建议在元表中指定u len函数,然后将该元表指定给我要覆盖的表,但这并没有按预期工作?我没有在C端覆盖此选项的选项 turtles = {1,2,3} setmetatable(turtles, {__len = function(mytable) return 5 end}) print(#turtles) --returns 3, should return 5 您必须使用Lua5.1。自Lua5.2以来,表上的\uuu len元方法就得到了支持

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

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

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

您必须使用Lua5.1。自Lua5.2以来,表上的
\uuu len
元方法就得到了支持

在中,如果操作数是表,则直接返回基元表长度

“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
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
在中,如果操作数是表,请检查
\u len
元方法是否可用

“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
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

@LarryBattle的可能重复不是真正的重复,这里的操作数不是字符串,而是表。您的代码在中运行良好。