Is there an alternative syntax for
Account = {}
function Account:new (o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
where new could be put directly into the table constructor for Account, and where the function gains an implicit self variable?
Or must one use a self parameter (or equivalent), and do it the following way?
Account = {
new = function (self, o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
}
No syntactic sugar is available for function definitions within table constructors. This includes function name (args) body end for name = function (args) body end, and by extension the colon syntax.
You must use an explicit first function parameter (it does not need to be named self, but that is good practice).
As you have noted, this will work, as colon syntax for function calls is a separate form of syntactic sugar.
A call v:name(args) is syntactic sugar for v.name(v,args), except that v is evaluated only once.
Lua 5.4:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With