Is there even a benefit to this - is there a difference between a function that's local to the entire script and one that's not local?
The benefit of using locals is twofold:
First, locals are usually faster, as they simply use registers in Lua's virtual machine whereas globals are entries in the global table (which is effectively a hash map). Calling a global function requires first indexing the hash map.
Second, locals help improve code quality, as they are only visible in their local scope (say, a file, or even within an if-branch, a loop or the like). Putting everything in the global scope is known as "global pollution" and frowned upon. It also slows down global access as it bloats the global table. Note that Lua allows changing the environment using _ENV
(or setfenv
in older versions), so you can sometimes save yourself both the local keyword and forward declarations by doing so without polluting the global environment. Usually you shouldn't change environments though.
Globals are often used to expose interfaces as pointed out by Nicol Bolas. You can alternatively use return my_api_table
at the end of your files for this; the API table can then be "imported" using local my_api_table = require(relative_path)
.
Is that because the code comes after the place it is launched it in the code, and at the point Launcher executes it doesn't exist yet?
Yes. You can fix this using a "forward local declaration" of GetLevel
:
local UseLevel = true
local Limit = 0
local GetLevel -- "forward declaration" for Launcher
local function Launcher()
print("trying to launch GetLevel now")
GetLevel()
end
-- This is the same as GetLevel = function() ... end and thus does not set a global variable
-- but instead assigns to the previously declared local variable GetLevel
function GetLevel()
print("GetLevel was launched")
if UseLevel then
Limit = 4
else
Limit = 5
end
end
Simply putting the Launcher
function below GetLevel
also works:
local UseLevel = true
local Limit = 0
local function GetLevel()
print("GetLevel was launched")
if UseLevel then
Limit = 4
else
Limit = 5
end
end
local function Launcher()
print("trying to launch GetLevel now")
GetLevel()
end