Lua table length function not working

How to change the length operator ( # ) for a table in Lua, the manual suggests assigning the __len function in the metathe, and then assigning this metatetable table that I want to override, but that doesn’t mean t works as expected? I have no way to override this on C side.

 turtles = {1,2,3} setmetatable(turtles, {__len = function(mytable) return 5 end}) print(#turtles) --returns 3, should return 5 
+5
source share
1 answer

You must use Lua 5.1. The __len __len in tables is supported since Lua 5.2.

In the Lua 5.1 reference manual , if the operand is a table, directly return the length of the primitive table.

"len": 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 

In the Lua 5.2 reference manual , if the operand is a table, check if the __len __len .

"len": 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 
+6
source

Source: https://habr.com/ru/post/1202036/


All Articles