I am trying to create my own length method for strings in Lua.
You cannot do this from Lua.
You will need to change the source of Lua, in particular the virtual machine (lvm.c), and change its processing of the OP_LEN operation OP_LEN . In Lua 5.2, you will need to modify luaV_objlen to check the metamethod before getting the actual string 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 it looks like the operator is overloading abuse, for example, overloading + by division, or something like that.
source share