✓ Accepted answer
They limit the scope of a variable.
x = 5
function apple()
x = x + 5
print(x)
end
function alternateUniverseApple()
local x = x + 5
print(x)
end
function banana()
print(x)
end
If we do this, we get 10 and 10:
apple()
banana()
If we do this instead, we get 10 and 5:
alternateUniverseApple()
banana()
This is because the local version of x ceases to exist once you get outside of the scope. I believe that in Lua, scope extends to the edges of a function, but I might be wrong on that front.
Edit
As link has pointed out, what I've said about scope is incorrect.
In Lua, scope is to do with "blocks", rather than functions.
Consider the following:
function testFunction()
local x = 5
print(x)
if x == 5 then
local x = x + 5
print(x)
end
print(x)
end
You get out 5, 10, 5, rather than the 5, 10, 10 you'd expect if scoping was to the edge of functions
Further information here
End edit
Why do you want this? Two good reasons:
It allows the garbage collector to clean up variables you aren't using any more once they go out of scope, meaning your script uses less memory
It means that you can reuse a variable name in one place without changing it in another
The idea of scope can be a little weird at first, so you probably want to have a little play around with it.
4 comments
That's right, variables are tied to the blocks they are declared in, not to functions. Non-local variables, called global variables, should not be used because they make your code messy.
Have edited code regarding scope - however, disagree regarding global variables. There are two very good reasons to use them:
(1) Lua doesn't support constants, and global variables are far clearer than "magic numbers"
(2) If the flow of your code requires you to pass many variables around frequently at each step, it's often more readable to just use global variables rather than passing around 5 arguments to 5 different layers of your program.