Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

table.insert does not call the __len metamethod #578

Open
wmoors opened this issue Apr 25, 2020 · 3 comments
Open

table.insert does not call the __len metamethod #578

wmoors opened this issue Apr 25, 2020 · 3 comments

Comments

@wmoors
Copy link

wmoors commented Apr 25, 2020

mt = {__len = function(t) print('__len called') return rawlen(t) end}
t = setmetatable({},mt)

table.insert(t, 1)

The provided snippet will show __len called when ran in lua 5.2.
luajit does not, which caused me quite a headache. :)

I built LuaJIT 2.1.0-beta3 with -DLUAJIT_ENABLE_LUA52COMPAT

@wmoors
Copy link
Author

wmoors commented Apr 25, 2020

for completeness...

print(#t)

will print __len called both in lua5.2 and luajit 2.1.0-beta3

@MikePall
Copy link
Member

To be compatible with Lua 5.2 this needs changes in both the interpreter and the JIT compiler.

Alternatively, table.insert could be implemented in internal bytecode, just like table.remove. The difficult part is an efficient check for the number of arguments. A fixarg Lua function cannot differentiate f(t,x) from f(t,x,nil), but a vararg function would be very inefficient. Tricky.

There's a performance impact, too.

@Biep
Copy link

Biep commented Sep 26, 2022

The bug in Lua has been described here. It seems trivial to correct, if one has access to the code.

I too have spent many hours chasing this bug, believing it was mine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants