Game Development Reference
In-Depth Information
file:write( … )
This function writes to the file each of the arguments passed to the function. The arguments must be
either strings or numbers. To write other values, you might have to convert them to string format.
file = io.open("myfile.txt","w")
file:write("Writing to a file")
file:close()
Note The pure implementation of Lua lacks the functions and commands required for file system access.
This is generally available as an external library that can be added. It is called Lua File System (LFS) .
As of this writing, you can integrate it with all frameworks (the amount of effort this takes, however,
depends on the framework.)
onus is on you to save and load the data to help provide continuity and seamless game play to the
player.
Let's look at how we would do that when dealing with stuff like life, health, score, level, and so forth.
Saving a Variable
In many games, you generally get only about three lives. So, consider the following code:
local lives = 3
print("You have " .. lives .. " lives left")
There are many ways of dealing with this. One good way would be to save the data as soon as you
change it—something like an autosave option. So, let's write out lives variable to the storage so
that it persists.
function writeToFileSingle(value, filename)
local hfile = io.open(filename,"w")
if hfile==nil then return end -- Did not get a handle on the file
hfile:write(value)
hfile:close()
end
In the preceding code, we declare a function called writeToFileSingle that takes two parameters:
value and filename . The function opens a file, writes the data to the file, and then closes the file.
 
Search WWH ::




Custom Search