Search code examples
luasyntax

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


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
}

Solution

  • 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: