Lua覆盖#的字符串

编程入门 行业动态 更新时间:2024-10-26 00:28:14
本文介绍了Lua覆盖#的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试对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中对字符串使用自己的长度方法.

I'm trying to imlement my own length method for strings in Lua.

您不能在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覆盖#的字符串

本文发布于:2023-08-01 08:50:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1266997.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   Lua

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!