lua-users home
lua-l archive

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


On Wed, Nov 24, 2010 at 9:24 PM, Duncan Cross <duncan.cross@gmail.com> wrote:
On Wed, Nov 24, 2010 at 10:10 AM, James Rhodes
> 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

I did try using setmetatable on strings, but I didn't think of just changing the __index value from the result of getmetatable() :P  That is definitely a better solution than using debug.setmetatable.

Regards, James.