As I understand it, there are multiple ways to define a member function to a table in Lua. For example, the following two appear to be equivalent:
-- method a)
local table1 = {x = 1, y = 2}
function table1:myfunc()
return self.x + self.y
end
-- method b)
local table2 = {
x = 1,
y = 2,
myfunc = function(self)
return self.x + self.y
end,
}
Having previously used Python, my instinct would be to use method b) to keep things more neatly grouped together. However reading through examples it seems that people generally use method a) by convention. I can't find any objective reason for why it should be superior though.
Indeed, it appears that on the contrary there are reasons to at least forward-declare the function variable when you initialise the table, like so:
local table3 = {x = 1, y = 2, myfunc}
function table3:myfunc()
return self.x + self.y
end
This way Lua knows about the existence of the member from the beginning and can set up the hashes correctly, whereas increasing the number of members to an existing table may require a rehash (although I can't imagine this ever actually becoming a noticable performance problem unless maybe you do this for a huge number of small tables). For sources compare: https://www.lua.org/gems/sample.pdf
So is there any reason for not defining member functions directly during the definition of the table itself? Or is it just the fact that some syntactic sugar (the function name()
syntax and the colon) is not available then?
table3
example doesn't do what you think it does. The table constructor{}
will copy the values to be inserted, reading the variablemyfunc
and storing it under index[3]
. It will not create themyfunc
entry to be filled later. If you wanted to create that entry, then writemyfunc = true
, to assign something that is notnil
. But frankly, you won't see any speedup here, just will waste more time writing unneeded text. Also note that it's more maintainable if you store all the method functions in separate table, and set it as metatable to all objects of the same type. – Vlada
allows you to access variabletable1
as upvalue from inside your functions. Methodb
doesn't allow this. – Egor Skriptunofftable.member
is equivalent totable["member"]
in Lua, I guesstable3 = {1 = 1, y=2, "myfunc"}
would also do the trick, right? – Abunself
achieve the same thing? – Abun