How to overload Lua string subscript operator?

无人久伴 提交于 2019-12-12 13:06:47

问题


This:

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

and this:

debug.getmetatable("").__index = _proc_lua_read

does not work.


回答1:


Try

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

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


来源:https://stackoverflow.com/questions/5685920/how-to-overload-lua-string-subscript-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!