No you don't have to assign require-calls to local variables, but you should do so.
When you call require, then the code in the required file is executed. If this code defines a global variable, then it will also exist in your normal program.
However, in most cases, it is bad practice to define global variable in external code files. That way different libraries could get coupled or break each other.
-- something.lua
return { moo = 'yo' }
-- main.lua
local a = require 'something'
a.moo = "test" -- change the moo in the table to 'test'
local b = require 'something'
print(b.moo) -- prints test instead of yo
I bumped into this issue feature when I tried to reset an object to the default values by just re-requiring it.
So it is good to know if you need to require the same file multiple times for whatever the reason, it only creates one instance.
-- something.lua
return { moo = 'yo' }
-- main.lua
local a = require 'something'
a.moo = "test" -- change the moo in the table to 'test'
local b = require 'something'
print(b.moo) -- prints test instead of yo
I bumped into this issue feature when I tried to reset an object to the default values by just re-requiring it.
So it is good to know if you need to require the same file multiple times for whatever the reason, it only creates one instance.
Both correct, except for that you don't need to return anything (but usually want).
That's still not quite right. What you'll want to do is localize the player inside player.lua then return it at the end as though it were a function on its own.
Kingdaro wrote:That's still not quite right. What you'll want to do is localize the player inside player.lua then return it at the end as though it were a function on its own.
-- main.lua
local player = require 'player'
player[1].x = 100
I'll try that, when I was away I had an idea that requiring lua files with data without setting it to a local variable may not be bad however setting something like bump.lua or libraries using a local variable I totally see the point.
Would you explain the benefit of assigning the returned table to a local variable?
Is this in order to become ordered while making architecture preventing crashes, conflicts?
It's to try and prevent hidden dependencies. Suppose your modules all assign to global variable, then you have no idea what modules are loaded when looking at a specific module. So if module A depends on module B, but doesn't require it, and module C requires module B, then it works out if module C just happens to be loaded before module A. But suppose module C is no longer needed, or it is changed to not need module B, or it is decided for some reason module A needs to be loaded before module C, then it all breaks. That's why it's better to make your dependencies explicit, and assign all modules to local variables.