lua-users home
lua-l archive

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

On Thu, Jan 13, 2011 at 4:57 PM, Axel Kittenberger <> wrote:
-- this one preserves an existing metatable.__index unless it has a
naming conflict with table.x
function createShortcut(t)
  local mt = getmetatable(t) or {}
  local oi = mt.__index
  mt.__index = function(k)
     return table[k] or (oi and oi(k))

I understand this code today, that's powered. Thank you very much.

@steve there is no witchcraft in doing metatables. The idea doing them
in a language is one of the very highlights to Lua. Just read the
manual in a quiet hour. Maybe it are the double underscores that
freighten people which in other languages alert "dirty compiler
specifc extension, or using libc internal not ment to be for you!"
well here they don't and are normal part of the language, I don't
100%ly understand why they are there.

On Thu, Jan 13, 2011 at 9:48 AM, Matthew Wild <> wrote:
> On 13 January 2011 05:49, Tang Daogang <> wrote:
>> But a new problem comes - if the table 'a' has already a metatable which is
>> not 'table', how to reach this shortcut format?
> If the metatable it has doesn't have an __index then:
> getmetatable(t).__index = table
> If it has an __index and it's a function then that needs to return
> table[k]. Otherwise if it's a table (sorry for the early-morning
> brain-hurt):
> setmetatable(getmetatable(t).__index, { __index = table })  ;--)
> But seriously, this is why tables don't have a metatable by default -
> in case you need to store string keys that are the same as the method
> names in table.*. So if you're likely to have keys that conflict with
> these methods then make your table store its data in a another table
> inside itself instead and have methods for getting/setting.
> I feel like the above paragraph could probably be condensed into a
> single comprehensible sentence, but it's nearly 9AM and I haven't
> slept...
> Regards,
> Matthew