local is a very important keyword in Lua, and you should be using it for every single variable you define, unless you want it to be global (available everywhere and to anything). When you define a variable or a function, you can use the local keyword so it is only available in the scope you are using it in - inside the function you are working on, inside an if statement, inside the program, etc…
For example:
-- This function starts with the keyword local, meaning it is only available in this program
-- This means that once the program ends, other programs that may run after it cannot use this function
local function testFunction()
print("test")
end
-- Since this function does not have local after it, other programs that run after this one are able to modify this function and call it.
function testFunction2()
print("test 2")
end
-- Likewise with variables:
-- Is not available to everything
local var1 = "hello"
-- Is available to everything
var2 = "hai"
Apart from this, local variables are only available in the current scope. This means that if you create a local variable inside a function, you cannot use that variable outside of it. Likewise with if, while, for, else, elseif, etc… statements.
Example:
local var1 = "hello!"
local function hello()
local a = "hai" -- We cannot use this variable outside of this function!
b = "hello 2" -- Since this one does not have the local keyword, we can use this variable outside of this function, but only after we call the function!
end
hello()
if a == nil then -- Returns true, because the variable a is local, and cannot be used outside the function hello.
print("a is nil")
end
if b == nil then -- Returns false, because b is global, and can be used outside the hello function.
print("b is nil")
end
-- It is the same with all other block statements (if, else, elseif, while, do, for, etc...). Declare a local variable inside it, and you cannot use it outside.