2

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?

2 Answers 2

5

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Should be: "you've specified the first variable as local". Functions are values, so they don't have a scope category.
4

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.

1 Comment

Note: You have to take the de-sugaring exactly as stated. A variable is global only when it's not local. For example, taking the two assignment statements from the question together in sequence, the local variable splitPathFileExtension is assigned twice.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.