Being able to simply load Lua tables is a powerful mechanism. If you format save data as a valid Lua file, it can be loaded back as a module. Using this feature of Lua, you can avoid having to write code that parses a text file.
Let's explore this concept by first saving some data to disk. The following function saves a simple object containing a level, health, and number of lives to a file named save.lua:
function Save(level, health, lives)
file = io.open("save.lua", "w")
file:write("return { ")
file:write(" level = ", level, ",", " ")
file:write(" health = ", health, ",", " ")
file:write(" lives = ", lives, " ")
file:write("}")
file:close()
end
Save(20, 10, 2)
Because save.lua is a module, you can load the save data with a single call to require, like so:
gameData = require("save")
print("Loaded:")
print(" level: " .. gameData.level)
print(" health: " .. gameData.health)
print(" lives: " .. gameData.lives)