Page 1 of 1

metatables, __len

Posted: Mon Feb 15, 2016 3:38 pm
by Operarus
When i write it, im get 0, but i want to get 100, please help;

Code: Select all

q = {};
setmetatable(q, {
  __len = function(self)
    return 100;
  end
});
error(#q);

Re: metatables, __len

Posted: Mon Feb 15, 2016 3:44 pm
by zorg
worksforme, both with "error(#q)" and "return #q". (on the online lua demo page)
maybe someone else can figure out your issue, it could be some version difference thing, like __len not existing before lua 5.2 or something.

Re: metatables, __len

Posted: Mon Feb 15, 2016 4:01 pm
by kikito
I confirm that __len works in some versions of Lua and not in others. In vanilla it works in Lua >= 5.2.

I have just tried it in LuaJIT 2.0.3 and it does not work.

A good way to know if it is supported is by checking the expression type(_G.rawlen). If it's nil, then __len is not supported. If it's 'function', then __len is probably supported.

Re: metatables, __len

Posted: Mon Feb 15, 2016 4:25 pm
by zorg
Looks like it, and some other 5.2 stuff depends on whether luaJIT was compiled with the -DLUAJIT_ENABLE_LUA52COMPAT flag or not; probably not the case with löve then.

Re: metatables, __len

Posted: Mon Feb 15, 2016 5:14 pm
by slime
Correct, the precompiled LuaJIT bundled with love in OS X and Windows isn't compiled with that flag, since it would prevent games whose code relies on some Lua 5.1-specific features from working properly.

(The flag only exists in the first place because the features it enables can break compatibility with code written for Lua 5.1).