Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function definition in Lua

Tags:

lua

Is there any difference between

local splitPathFileExtension = function (res)
end

and

function splitPathFileExtension(res)
end

? I understand in the first case this function is anonymous but this is the only difference?

like image 443
Vyacheslav Avatar asked Jun 08 '26 07:06

Vyacheslav


2 Answers

They are almost exactly the same thing (other than the fact that you've specified the first function as local and not the second one.)

See the manual on function definitions:

The statement

    function f () body end

corresponds to

    f = function () body end

The statement

    function t.a.b.c.f () body end

translates to

    t.a.b.c.f = function () body end

The statement

    local function f () body end

translates to

    local f; f = function () body end

not to

    local f = function () body end

(This only makes a difference when the body of the function contains references to f.)

like image 75
Lynn Avatar answered Jun 10 '26 19:06

Lynn


All functions are anonymous, they don't have names. A function definition is in fact an assignment statement that creates a value of type function and assigns it to a variable.

The second code is syntactic sugar that's equivalent to:

splitPathFileExtension = function (res) end

So, other than the first is local while the second is global, there's no difference between the two ways of function definition.

like image 25
Yu Hao Avatar answered Jun 10 '26 19:06

Yu Hao