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

Local in front of functions?

Asked by 9 years ago

Explanation of why there is sometimes local in front of functions?

3 answers

Log in to vote
3
Answered by
2eggnog 981 Moderation Voter
9 years ago

In Lua, it turns out that local functions and variables can be accessed faster than global variables/functions. Normally this doesn't matter, but if a function needs to be called extremely often, the performance increase adds up.

Ad
Log in to vote
3
Answered by 9 years ago

Apart from faster performance, as explained elsewhere, local functions can also be neater for organisation purposes.

Using local means it cannot be used outside of it's scope. Here's an example that will help understanding better.

function f1()
    local function f3()
        print(1)
    end
    f3()
end

function f2()
    local function f3()
        print(2)
    end
    f3()
end

f1()
f2()

As you can see f1 and f2 are called. In both f1 and f2 we call a function called f3. However, when we call f3 whilst in the function f1 it will print 1, if we call f3 whilst in the function f2 it will print 2. This can be useful for organisation as you can have two different functions with the same name, as long as they are in different scopes.

Log in to vote
1
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

To add to the other answers, because Lua's functions are "first-class values with proper lexical scoping" (read: pure effing magic) they are, effectively, variables. The reason you put the name after the keyword function is because it's more easily read that way, so they added it in as syntactic sugar.

name = function()
end

--Is the exact same as

function name()
end

Because they can be considered as any other type of variable, you can apply the local keyword to them, with either of the (syntactically correct) above definitions. The effect is the same, and the same scope rules apply.

Also, like the others said, local variables of any kind are accessed slightly faster than global ones (not to be confused with variables in _G or shared).

Answer this question