问题
I'm trying to imlement my own length method for strings in Lua. I have successfully overriden len() method for string, but I have no idea how to do this for # operator.
orig_len = string.len
function my_len(s)
print(s)
return orig_len(s)
end
string.len = my_len
abc = 'abc'
If I call:
print(abc:len())
It outputs:
abc
3
But
print(#abc)
Outputs only '3' and that means it called original length function instead of mine. Is there a way to make # call my length function?
回答1:
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.
回答2:
You cannot override the #
operator for strings in Lua, not even with metatables: the __len
metamethod does not apply to strings.
In fact, there is really no notion of overriding any operators in Lua. Lua metamethods are fallbacks: they are used when Lua cannot proceed on its own. Thus, arithmetic metamethods do not apply to numbers and the length metamethod does not apply to strings.
The situation is different for tables because they are meant to implement objects in Lua.
来源:https://stackoverflow.com/questions/23085204/lua-override-for-strings