Why can't we use the function definition sugar syntax in tables?

So

function x()

end

is syntactic sugar for

x = function()

end

So how come we can’t do this in a table?

local t =
{
    function x()
        -- what is the point if we can't use it here??
    end
}

Shouldn’t it evaluate to this?

{
    x = function()

    end
}
2 Likes

x = whatever in a table definition is itself another form of ["x"] = whatever. The definitions look similar inside a table and outside, but they are technically different. So, I guess for the same reason you can’t do function ["x"](); you just can’t.

3 Likes

It may be worth looking at the syntax of lua
https://www.lua.org/manual/5.1/manual.html#8

function x()

end

Is a statement
It’s the function funcname funcbody in stat
Now in the constructor for tables

tableconstructor ::= `{´ [fieldlist] `}´
fieldlist ::= field {fieldsep field} [fieldsep]
field ::= `[´ exp `]´ `=´ exp | Name `=´ exp | exp
fieldsep ::= `,´ | `;´

Table constructors work with expressions, not statements.
function x()end isn’t valid for field.
x = function()end is valid for field because it’s in the form Name `=´ exp

x = function() end is also a statement. There has to be something else going on. If not then oh well

Yes, both

function x()end

and

x = function()end

Are both valid statements.
The latter satisfies the varlist ‘=’ explist part of stat, while the former satisfies the function funcname funcbody part of stat.

A field is different from a statement.

Every field in a table constructor must follow the form of
‘[’ exp ‘]’ ‘=’ exp or Name ‘=’ exp or exp

x = function()end works both as a field, and a statement.
function x()end works as a statement, and not as a field.

Another example of something which can be used multiple places is a function call, it can be a statement, or an expression.

2 Likes