order that love loads files

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
randy0428
Citizen
Posts: 51
Joined: Sun Jul 31, 2016 10:19 am

order that love loads files

Post by randy0428 »

I am confused about how love loads.

I’m trying to use a global variable, “timesAllowed”. I tried initializing it in main.lua in two ways, neither of which seemed to work as I expected. That is, when I tried to use this variable in another file, I got an error that the variable has a nil value. Note: The program is well developed and was working fine till I tried to add this.

First, I tried putting “timesAllowed = 5” (without the quotes) as the first line in the love.load() function in main.lua. That didn’t work, so I tried putting it BEFORE the love.load() function, immediately after the require statements. This also didn’t work.

This caused me to wonder about the order that love loads things, so I tried a few experiments. The one that surprised me seemed to indicate that files other than main.lua were loaded before main.lua. In the first line of several files I put a print statement with the name of the file. Ex: print(“splash”) as the first line in splash.lua. I did this with the files data.lua, main.lua (print statement after the require statements), play.lua, splash.lua, and useLimit.lua.

When I ran the file I got the print results in the order below:
splash
play
data
useLimit
main

Why would main be run LAST? How can I create a global variable?

Thanks.
hamberge
Prole
Posts: 25
Joined: Wed Aug 16, 2017 2:55 pm

Re: order that love loads files

Post by hamberge »

You should put your global variable before the require statements. The way to think about it is that require just runs the script in the file you require. Thus if the variable is declared before you run the script, the script will be able to access it. You are getting an error because your require is running the script before the global variable is available.

This would also explain the results of your experiments above.

It's not like C header files or whatever. It also means your other files can return things and you can do crazy things like assign return values from required files into variables in the middle of main or any other file.

Another thing to note is that if a file returns a table and you require that file in multiple other files, the require will return a reference to the exact same table, not a copy.
randy0428
Citizen
Posts: 51
Joined: Sun Jul 31, 2016 10:19 am

Resolved: order that love loads files

Post by randy0428 »

Thanks for the explanation, hamberge.
That solved the mystery and the problem.
Post Reply

Who is online

Users browsing this forum: No registered users and 106 guests