lua-users home
lua-l archive

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


On Sat, Feb 14, 2009 at 2:02 PM, Peter Hickman <peterhi@ntlworld.com> wrote:
> I have some code that I want to use to add an invert method to tables.
>
> table.invert = function (t)
>        local i = {}
>        for k in pairs(t) do
>                i[t[k]] = true
>        end
>        return i
> end
>
> When I call it as "table.invert(a)" it works fine, but it errors when I call
> it as "a:invert()"
>
> lua: invert.lua:15: attempt to call method 'invert' (a nil value)
>
> My understanding was that a:invert() was just sugar on table.invert(a), what
> am I doing wrong?
>

a:invert(var) is sugar for a.invert(a, var)

Since "invert" isn't a field in a, it won't work. You can set a
metatable however: setmetatable(a, { __index = table }) which will
make it work as you wish, fetching table.invert when a.invert is nil.
Just beware that if you set a.invert yourself, or a.insert, etc. it
will use that instead of table.invert, table.insert, etc.

Matthew.