[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: How to make table object has the shortcut ability as string
- From: Michal Kottman <k0mpjut0r@...>
- Date: Thu, 13 Jan 2011 11:12:53 +0100
On Thu, 2011-01-13 at 17:08 +0800, Tang Daogang wrote:
>
> On Thu, Jan 13, 2011 at 4:57 PM, Axel Kittenberger <axkibe@gmail.com>
> 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
code:
function T(t)
return setmetatable(t or {}, {__index=table})
end
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}
t:insert('Hello')
t:insert('world!')
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".