Is there any advantage to declaring a function as
Yes. They are faster to access, and you avoid polluting the global* namespace. Here is some info about the global environment from PIL.
For simple programs, honestly, it probably doesn’t matter what you do. As your programs get more complex, though, you will start to realize the benefits of well-defined scope.
Because so far I’ve only seen disadvantages : without
local , the function can be located anywhere in the code and when declared
local , the function must always be above the line that calls it.
This is false. The following fails:
printHello() -- attempt to call global 'printHello' (a nil value)
You may be referring to something like this:
This works because when you declare something without
local, you are actually putting it in a table that is shared for the entire script*. The
printHello() call triggers a lookup in that global* table.
However, that’s not a unique thing to globals, it’s more of a side-effect of the way lua is evaluated (at runtime). This works too, but makes printHello a local function:
function printHello() -- same as printHello = function()
You still need the forward declaration at the top, since you’re not storing the variable in the global* table, but you can put the definition wherever you want.
*: in non-roblox Lua, every non-local variable is put in _G and shared among all modules in the program – not true for ROBLOX. In ROBLOX Lua, each script has its own “global” table that other scripts cannot access.