Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Love2D: what is the difference between creating variables inside love.load instead of at the top of the main.lua file?

Tags:

lua

love2d

If you look at the docs for love.load it says

This function is called exactly once at the beginning of the game.

and nothing else really. Also it has one parameter, which are command line args.

So if you don't use the args, what is the difference between:

x = 5

-- rest of code

and

function love.load()
  x = 5
end

-- rest of code

The biggest benefit to avoiding love.load is that you can make x local instead of global. Are there any benefits to using love.load?

like image 530
m0meni Avatar asked Oct 17 '16 18:10

m0meni


3 Answers

I don't think there is any difference for simple values (like what you show in your examples), but a more complex code that uses love.graphics or other components needs to be executed from love.load as it guarantees that the engine is properly setup and initialized by that time.

like image 188
Paul Kulchenko Avatar answered Nov 19 '22 21:11

Paul Kulchenko


Just like you stated yourself, love.load() only runs once at the beginning and therefore is perfect to initialise variables. Everything set outside of that function might be loaded more often.

Try creating a conf.lua file and activate the console. Then print() something outside the love.load() and you'll see.

-- conf.lua
function love.conf(t)
  t.console = true
end

-- main.lua
print("Hello World!")
function love.load()
end

For me it always printed "Hello World!" two times when starting the game.

Just like Paul Kulchenko stated, it might not make any difference with simple values, but you'll never know... ;)

like image 42
nehegeb Avatar answered Nov 19 '22 20:11

nehegeb


After the main.lua has been run, Love calls love.run, which holds the main game loop. One of the first things love.run does, is call love.load(...) where ... holds the command line arguments for your game, which you may find useful.

This means, that love.load runs after all your main.lua code, but before love.draw, love.update, and similar begin to be called.

What value this has, is mostly up to yourself.

like image 23
ATaco Avatar answered Nov 19 '22 22:11

ATaco