#t calls __len(t, t)?

73 views
Skip to first unread message

Rett Berg

unread,
Nov 21, 2025, 10:12:48 AM (6 days ago) Nov 21
to lu...@googlegroups.com
I'm very confused by this:

$ lua -v
Lua 5.4.8  Copyright (C) 1994-2025 Lua.org, PUC-Rio

$ lua
> t = setmetatable({}, {__len=function(...) print(...) end})
table: 0x556e5dc1ad50
> #t
table: 0x556e5dc1ad50   table: 0x556e5dc1ad50
nil

It seems like #t is passing t twice?

Luiz Henrique de Figueiredo

unread,
Nov 21, 2025, 11:06:24 AM (6 days ago) Nov 21
to lu...@googlegroups.com
> It seems like #t is passing t twice?

Yes. For treating binary and unary metamethods uniformly.
Arithmetic negation works the same way:

t = setmetatable({}, {__unm=function(...) print(...) end})
print(-t)

Roberto Ierusalimschy

unread,
Nov 24, 2025, 8:08:51 AM (3 days ago) Nov 24
to lu...@googlegroups.com
https://www.lua.org/manual/5.4/manual.html#2.4

[...]
For the unary operators (negation, length, and bitwise NOT), the
metamethod is computed and called with a dummy second operand, equal
to the first one. This extra operand is only to simplify Lua's
internals (by making these operators behave like a binary operation)
and may be removed in future versions. For most uses this extra
operand is irrelevant.

-- Roberto

Sainan

unread,
Nov 24, 2025, 8:15:41 AM (3 days ago) Nov 24
to lu...@googlegroups.com
May I suggest a patch?

> luaV_objlen
-luaT_callTMres(L, tm, rb, rb, ra);
+luaT_callTMres(L, tm, rb, 0, ra);

> luaV_execute
-Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));
+Protect(luaT_trybinTM(L, rb, 0, ra, TM_UNM));
...
-Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT));
+Protect(luaT_trybinTM(L, rb, 0, ra, TM_BNOT));

> luaT_callTMres
-setobj2s(L, func + 2, p2); /* 2nd argument */
-L->top.p += 3;
+L->top.p += 2;
+if (p2) {
+ setobj2s(L, func + 2, p2); /* 2nd argument */
+ L->top.p += 1;
+}

-- Sainan

Rett Berg

unread,
Nov 24, 2025, 8:31:25 AM (3 days ago) Nov 24
to lu...@googlegroups.com
Thanks everyone, glad to know it was a known behavior and may be removed.

--
You received this message because you are subscribed to a topic in the Google Groups "lua-l" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/lua-l/FoKgdN7DMic/unsubscribe.
To unsubscribe from this group and all its topics, send an email to lua-l+un...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/lua-l/tXcMNZ4GEwvcw32abvdzyDgaD1aq4kdph7T6aCbatZoecloX-AkbQvnfgz_LBM9F2GQPp4gOeTosK-u2gPSMAlpfqcZrIfsA_RmNqkzEqMM%3D%40calamity.inc.
Reply all
Reply to author
Forward
0 new messages