I can see what you are both saying but I came from code like this:
string.fred = function (s)
return s..s
end
a = "xxx"
print(a)
b = a:fred()
print(b)
Which does work. It has added a method to the string object and an
instance of a string has picked up the method. I thought that it
would also
work for tables also
On 14 Feb 2009, at 14:08, Duncan Cross wrote:
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() is actually sugar for a.invert(a), which will only be
equivalent to table.invert(a) if you have a metatable set on 'a'
which looks
up the 'table' library when __index is called.
The situation is different with strings because all string values
share a
common metatable, while tables each individually have their own
metatable,
which by default is nil. Therefore tables will never inherit any
methods as
soon as they are created, something has to be done to provide them.