如何重载Lua字符串下标运算符? [英] How to overload Lua string subscript operator?

查看:515
本文介绍了如何重载Lua字符串下标运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此:

debug.getmetatable("").__index = function (s, i) return s:sub(i, i) end

和这个:

debug.getmetatable("").__index = _proc_lua_read

不起作用.

推荐答案

尝试

debug.getmetatable("").__index = function (s, i) return string.sub(s,i,i) end

请注意,通过以这种方式为字符串重新定义__index,您将失去在字符串上调用方法的能力:请注意代码如何不调用s:sub.有关避免这种情况的更好解决方案,请参见 http://lua- users.org/lists/lua-l/2007-11/msg00619.html .或改为设置__call:

Note that by redefining __index for strings in that way, you lose the ability to call methods on strings: note how the code does not call s:sub. For a better solution that avoids that, see http://lua-users.org/lists/lua-l/2007-11/msg00619.html . Or set __call instead:

getmetatable("").__call = string.sub

这篇关于如何重载Lua字符串下标运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆