Answered by
6 years ago Edited 6 years ago
They limit the scope of a variable.
08 | function alternateUniverseApple() |
If we do this, we get 10 and 10:
If we do this instead, we get 10 and 5:
1 | alternateUniverseApple() |
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:
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.