"Local" functions

This is sort of a follow-up to this question: Local variables in a global scope

Most commonly when browsing others’ code, variables are defined with ‘local’ in front of them and functions are not. However, would it be better to define all functions as local as well, for the same reasons that variables should be defined as local (such as being faster)?

That should be your answer. Sometimes you would need a global function:

local function One()
    Three()
end

local function Two()
    Three()
    One()
end

function Three()
    One()
end

Try rearranging that but with only local functions, you can’t.

1 Like

Remember that Lua has no concept of “local functions” or “global” functions.

All functions in Lua are anonymous, which means they have no names.

This code:

function foo()

end

Is syntactic sugar (a nicer way to write something) for

foo = function()

end

As you can see, it is just a variable declaration. The global variable foo points to a function.

And this code

local function foo()

end

Is syntactic sugar for

local foo
foo = function()

end

If you wonder why it is not

local foo = function()

end

it is because then you couldn’t make recursive calls.

At the end, functions are first-class and there is nothing special about them. Always use local variables.

2 Likes

You can just add local Three to the first line. I’m not sure if this is what OP has seen or if it’s different, but either way you can forward declare and still get the benefits of a local function.

local Three

function Three()

end

This is still a local function.

The question of “do you need a global” is probably “no” close to 100% of the time in Roblox Lua, but in vanilla Lua they play a bigger part.

2 Likes

You could’ve asked this question in that thread itself and an answer was also provided a few times in that thread itself. Functions are still values like any other, so yes, place local before them.

Most times you see this disjointed pattern of all variables except functions being local will come from novice developers who don’t know that the relationship of function values and other values is still the same and thus you can put local before a function (and should).

Only case that you wouldn’t put a local before a function, obviously, is if you’re putting it in a table as a member directly, because that’s not a valid declaration then.