lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Wed, Nov 24, 2010 at 10:10 AM, James Rhodes
<jrhodes@roket-enterprises.com> wrote:
> With regards to your last note about accessing characters through s[i], you
> can actually already do this by setting the metatable for all strings; like
> so:
> mt = {}
> mt["__index"] = function(str, i)
>     if (type(i) == "number") then
>         return string.sub(str, i, i)
>     else
>         return string[i]
>     end
> end
> debug.setmetatable("", mt)

This is a bit of a tangent but you can actually do this without
needing to use the debug library - the standard getmetatable() does
work on strings (in a standard Lua setup) so you could do:

 getmetatable("").__index = function(str, i)
   -- (... code ...)
 end

-Duncan