Executing files

The require function only loads a file one time. When dealing with modules, this feature is a great way to avoid loading duplicate code. But, when trying to load data, the require function will not re-load data. Loading the same Lua file multiple times can be done using the dofile function. Both dofile and require load a file and execute the code within, but with two major differences:

  • dofile: will re-load a given file every time it is called
  • dofile: does not search package.path; instead, it loads the file name given assuming the path provided is relative to the current file path

Let's modify the previous code sample to save some data, load it, save some new data, and then re-load the data. The code needs to change to this:

Save(20, 10, 2)
gameData = dofile("save.lua")
print("Loaded:")
print(" level: " .. gameData.level)
print(" health: " .. gameData.health)
print(" lives: " .. gameData.lives)

Save(10, 10, 5)
gameData = dofile("save.lua")
print("Loaded:")
print(" level: " .. gameData.level)
print(" health: " .. gameData.health)
print(" lives: " .. gameData.lives)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.99.152