It's not just about speed. Or, i should say, it's more about avoiding littering the "global environment" than any minuscule speed gains you might get.
Let me give you a horrible analogy first: Let's say i want to buy groceries in the store. It's both faster and more concise if i take a list of the stuff i need with me, instead of calling back home each time i enter a new aisle (or worse, for each item the shop might sell).
Digressing from that, here's some other answers:
In Lua, a file is a block too, so that's another scope, the file scope.
When you use local x in your main.lua's file scope, for example, it means that those are only visible from within that file. (Sometimes you want to put your locals there, instead of inside a function block, since you might want the variable to be local AND to be used in more than one function in said file; see my example below for what i mean by this.
Going back to my bad analogy, here's how you'd access one file's stuff from another:
Code: Select all
-- a.lua
local t = {}
-- fill up t with stuff
return t
-- main.lua (as example)
local foo -- this could be inside love.load as well ,but this way, whatever foo will be later will be accessible by any function that's in this file, instead of just love.load.
function love.load()
foo = require 'a' -- returns the table we return from a.lua you can return a variable, or anything really.
end
The table "t" in a.lua exists only inside there, but we require it in main.lua since we want to use it there as well.
In the end, it's about being
explicit about access across files, instead of using globals
implicitly. And being implicit could lead you to modifying variables you used elsewhere, because you can't easily see what you defined (and used) where. The way i wrote it, you can exactly see what you use where, so you minimize these kinds of errors.