How to overload Lua string subscript operator?

Tag: string , lua , operator-overloading Author: Floating79 Date: 2011-03-31

This:

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

and this:

debug.getmetatable("").__index = _proc_lua_read

does not work.

Best Answer

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