Search code examples
lua

LUA: how do you save someones progress?


lets say you have a script like this

print("you've been here for the first time.")
print("you're here for second or more time")

how would you make it so once a person runs the script once, instead of repeating the whole script it just goes to the second print right away?


Solution

  • You basically need to:

    • Save the state of the program when the program ends
    • Restore the state of the program when the program starts

    There are several ways to store the state, the simplest way would be to create a file and store the state inside. One could also use the Windows Registry, a database, a remote server, etc.

    A simple example:

    function FileExists (Filename)
      local File = io.open(Filename, "r")
      if File then
        File:close()
      end
      return File
    end
    
    function CreateFile (Filename)
      local File = io.open(Filename, "w")
      if File then
        File:close()
      end
    end
    
    ProgramStateFile = "program-state.txt"
    
    if not FileExists(ProgramStateFile) then
      print("you've been here for the first time.")
    else
      print("you're here for second or more time")
    end
    
    CreateFile(ProgramStateFile)
    

    In this example, the state is only the existence of the state file. Obviously, you can extend this example by writing additional information inside the file.

    function ReadState (Filename)
      local File = io.open(Filename, "r")
      local State
      if File then
        State = File:read("a")
        File:close()
      end
      return State
    end
    
    function WriteState (Filename, State)
      local File = io.open(Filename, "w")
      if File then
        File:write(State)
        File:close()
      end
    end
    
    ProgramStateFile = "program-state.txt"
    
    if ReadState(ProgramStateFile) ~= "PROGRAM-FINISHED" then
      print("you've been here for the first time.")
    else
      print("you're here for second or more time")
    end
    
    WriteState(ProgramStateFile, "PROGRAM-FINISHED")
    

    Finally, please note that there are many formats already existing to store the states: INI file, XML, JSON, etc. For Lua, you could also use a serialization library in order to store a Lua table directly inside a file. I would personally recommend the binser library.