I'm trying to imlement my own length method for strings in Lua.
You can't do this from Lua.
You'd need to modify the Lua source, specifically the virtual machine (lvm.c) and change its handling of the opcode OP_LEN
. In Lua 5.2 you'd need to change luaV_objlen
to check the metamethod before getting the string's actual length:
case LUA_TSTRING: {
tm = luaT_gettmbyobj(L, rb, TM_LEN); // <--- add this line
if (!ttisnil(tm)) // <--- add this line
break; // <--- add this line
setnvalue(ra, cast_num(tsvalue(rb)->len));
return;
}
But this seems like operator overloading abuse, like overloading +
to mean division or something.