lua-users home
lua-l archive

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

On Thu, Jan 13, 2011 at 6:12 PM, Michal Kottman <> wrote:
On Thu, 2011-01-13 at 17:08 +0800, Tang Daogang wrote:
> 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))
>           end
>         end
> I need to obviously call the function createShortcut? That doesn't fit
> my needs.

You need to call it when creating a table. You can make it 'nicer' (IMO)
if you use a simple shortcut-type name, like 'T'. I often use this in my

function T(t)
 return setmetatable(t or {}, {__index=table})

Then, instead of using the {} literal to create a key, thanks to syntax
sugar provided by Lua, you only have to add one letter: T{}. Then you
can do stuff like:

t = T{} -- or T()
t2 = T{1, 2, 3, some_key=some_value}
print(t:concat(', '))

It keeps code clean (no global modifications to all tables), without
much visual clutter, and also communicates the intent - "here, I want to
use an 'enhanced' table, not a raw Lua table".

Great way! I like it. Thank you!