Variables
In Lua variables can be in two major scopes: global and local (let's skip table variables for now for clarity). To define a variable in the local scope you simply:
local my_variable = 5
By "local scope" we usually mean something like "the block this code is in". For instance: a local variable inside a function block would be available only inside that function. Or: a local variable at the top-level of the file is only available in that particular file.
You usually assign a value right away, but sometimes you may want to simply state that "I want my_variable
to be in the local scope, but I don't know what it is just yet":
local my_variable
Then, assuming that you are in the same scope as before you can assign a value to it:
local my_variable
-- Some things happen, but we are in the same scope...
my_variable = 5
This will assign the value 5
to the my_variable
in the local scope.
In case we wouldn't have the local my_variable
first, then this statement would assign the value 5
to a global my_variable
. Don't worry, this can be confusing at start. I recommend to simply play around with this idea by writing some functions, loops, and declaring, defining, then changing variables inside of them, with and without the local
. This way you should be able to build up your intuition about the scopes more easily than reading raw descriptions.
You can also check out chapters in Programming in Lua: 4.1 - Assignment and the following 4.2 - Local Variables and Blocks.
Functions
As for functions, they are treated exactly the same way as any other value:
function my_func ()
end
Is a shorthand for assigning a "function as value" to variable my_func
:
my_func = function () end
Now, we can declare my_func
as a local variable just like we did before with my_variable
. This would mean that the variable holding the function is only available in that particular local scope. The definition you wrote:
local function my_func () end
Is exactly that - a shorthand to define a function in local scope which expands to:
local my_func
my_func = function () end
For more technical descriptions you can check out Lua's reference manual: