问题描述
我正在尝试对Lua中的字符串实施我自己的长度方法.我已经成功重写了len()方法的字符串,但是我不知道如何为#运算符执行此操作.
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'
如果我打电话:
print(abc:len())
它输出:
abc
3
但是
print(#abc)
仅输出"3",这意味着它调用了原始长度函数,而不是我的.有没有办法让#调用我的length函数?
Outputs only '3' and that means it called original length function instead of mine. Is there a way to make # call my length function?
推荐答案
您不能在Lua上做到这一点.
You can't do this from Lua.
您需要修改Lua源,特别是虚拟机(lvm.c),并更改其对操作码OP_LEN
的处理.在Lua 5.2中,您需要更改luaV_objlen
来检查元方法,然后才能获取字符串的实际长度:
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.
这篇关于Lua覆盖#的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!