I understand the difference between the scope of local and global variables, but I am confused about the difference and effects of declaring a variable OUTSIDE of Lua functions (or LOVE2D core callback functions). Consider these three code snippets:
declare function as global, outside of all functions
var = 30 function f1() -- end function f2() print(var) end f1() f2()declare function as local, outside of all functions
local var = 30 function f1() -- end function f2() print(var) end f1() f2()
- declare function as global, inside of a function
function f1() var = 30 end function f2() print(var) end f1() f2()
All three of these have the same result. I know that all global variables are stored in the global environment table (accessible via _G), and that official Lua documentation discourages the use of global variables:
It is good programming style to use local variables whenever possible. Local variables help you avoid cluttering the global environment with unnecessary names. Moreover, the access to local variables is faster than to global ones. (from https://www.lua.org/pil/4.2.html)
So, what is the difference between these three and which is the best one to use?
I am specifically looking at LOVE2D, although their core callback functions act like normal functions. I guess my question is, if I want to declare a Player (table), where should I put Player = {} (either at the top of main.lua or inside love.load) and if I should declare it 'local' (if at the top of main.lua)?