Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Lua function using the colon syntactic sugar be defined inside a table?

Tags:

syntax

lua

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
}
like image 401
DrDreadful Avatar asked Jun 15 '26 13:06

DrDreadful


1 Answers

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:

  • §3.4.9 - Table Constructors
  • §3.4.10 – Function Calls
  • §3.4.11 - Function Definitions
like image 187
Oka Avatar answered Jun 18 '26 20:06

Oka