MadByte wrote:I guess if I already load them local on top of the i.e game.lua this way doesn't make much sense anymore?
Code: Select all
local world = require'src.world'
local player = require'src.player'
local game = {}
local World
local Player
function game:enter()
World = world.new()
Player = player.new(200, 200)
World:add( Player )
end
What about put the requires into the init function of a gamestate, is there any advantage on doing that ?
I mean they are now already local & shouldn't pollute the global namespace anymore.
The way the require function works is that it'll only load the file once, and whatever is returned from that file is reused every other time you try to require it. So, if you move the requires into the game:enter function, it'll pretty much behave the same without a performance impact. If anything, it'd probably make your game startup faster, but take slightly longer the first time it switches to a new gamestate.
A side note though, Lua's rules on scoping are slightly different then what you're thinking. When you write
local, you've created a bound scoped variable, not a global variable. By putting the results of require calls into a local variable, it's only available to the file where you did so, or if you do it in the game:enter function, it'll only be available there. If you need it available everywhere, then consider making it global, which means you'd either require it main.lua and put it in a global variable, i.e. no local keyword, or don't use the local keyword in the file where you defined the module. Again, if it's your own gamespecific code, then it's fine, it's your global state. If you're writing libraries for others, then the global state isn't yours so don't do it that way.
MadByte wrote:
And one other question, what do you think about loading all entities and objects with a world class by looping through them everytime as I
currently do? This might be a bit heavy on the performance but it seems to be much more comfortable to organize things like that.
Or is there any similar way to archive this which does look better in the performance aspect.
I'm not sure what you're getting at here. If you're talking about writing code like this:
player = require('src.player').new(), that might get very messy.