lua-users home
lua-l archive

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


Reuben Thomas wrote:
> To allow string methods to continue to work, you can't just override  
> __index. After some thought, I came up with this:
> 
> -- @func __index: Give strings a subscription operator
> --   @param s: string
> --   @param n: index
> -- @returns
> --   @param s_: string.sub (s, n, n)
> local oldmeta = getmetatable("").__index
> getmetatable("").__index =
>    function (s, n)
>      if type (n) == "number" then
>        return sub (s, n, n)
>      else
>        return oldmeta[n]
>      end
>    end
> 
> What are the downsides?

If oldmeta is a function you have to call it with normal function call
syntax rather than table indexing.

local oldmeta = getmetatable("").__index
getmetatable("").__index =
   function (s, n)
     if type (n) == "number" then
       return sub (s, n, n)
     elseif type(oldmeta)=="function" then
       return oldmeta(s, n)
     else
       return oldmeta[n]
     end
   end