Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

What's the difference between a local function and a regular function?

Asked by 6 years ago

Even though this may be a stupid question, what's the difference? I never learned what the difference was.

For example:

01local function printMessage(msg)
02      print(msg)
03end
04 
05printMessage('hi')
06 
07------------------------------------------------
08 
09function printMessage(msg)
10      print(msg)
11end
12 
13printMessage('hi')

They do the same exact thing..

1 answer

Log in to vote
2
Answered by
Avigant 2374 Moderation Voter Community Moderator
6 years ago

I'll quote my answer from this earlier question.

There is no such thing as a local function, actually. You are merely assigning variables that reference functions.

It's important to remember that functions are first-class values, and that all functions in Lua are anonymous (nameless). This code:

1function name()
2 
3end

Is really sugar syntax (a nicer way of writing something else) for this:

1name = function()
2 
3end

And that this code:

1local function name()
2 
3end

Is really sugar syntax for this:

1local name
2name = function()
3 
4end

You might ask why it's not sugar syntax for this instead:

1local name = function()
2 
3end

And the reason would be that you wouldn't be able to make recursive calls in the function if that were the case.

Again, functions are just like any other values in Lua. You can store them in variables, pass them to other functions, and so on, they're not special at all.

Ad

Answer this question