How can i save variables in other lua file?

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
JoLetus
Prole
Posts: 1
Joined: Mon Feb 01, 2021 12:34 pm

How can i save variables in other lua file?

Post by JoLetus »

I am trying to make a game and it would be ideal that who ever is using it does not have to start again when he closes the game. i have the variables on other file and the game loads them when ever you open the game but i currently cant save new progress to the wariables with out them being reset when game is closed.
User avatar
pgimeno
Party member
Posts: 3641
Joined: Sun Oct 18, 2015 2:58 pm

Re: How can i save variables in other lua file?

Post by pgimeno »

Best is to have the whole game state in a single table, instead of separate variables, and use a serialization/de-serialization library. See for example how the new_or_load_game function in Thrust II Reloaded: https://notabug.org/pgimeno/Thrust-II-r ... e.lua#L235

You can make shortcuts to some tables to avoid cluttering the code, see e.g. https://notabug.org/pgimeno/Thrust-II-r ... e.lua#L287, but that won't work for variables that aren't tables or Löve objects.

I use a JSON library to save the table, but any serialization library should work.

If you absolutely want to have all state spread into multiple variables, you can still make a table with these variables and serialize it, and at the time of loading, de-serialize it and use it to fill in the variables. That's more prone to mistakes in case you add or remove variables, though. It's easy to forget to update both the loading and the saving code. That's why I recommend using a table throughout the program.
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Google [Bot] and 4 guests