Writing data

Writing data to a file is done with the write function of the file handle. This function will write whatever arguments are passed to it into the file. The following code creates a data.txt file, if one does not exist, or replaces the contents of the existing file:

file = io.open("data.txt", "w")
file:write("foo")
file:write("bar")

After running the previous code, a data.txt file would contain the foobar string. Looking at the code, it's reasonable to expect "foo" and "bar" to be on separate lines. By default, the write function does not add any newline characters. You have to add line breaks manually, like so:

file = io.open("data.txt", "w")
file:write("foo", " ")
-- file:write("foo ") -- would also work
file:write("bar")

The write function will take any data type as an argument,and will take any number of arguments. The following code demonstrates different ways of concatenating strings being written to a file. The file being written is something you might see being saved as data for a game:

-- Create function to save character data
function SaveCharacterData(name, power, team)
file = io.open("data.txt", "w")
file:write("name " .. name .. " ") -- We can concatenate with ..
file:write("attack ", power, " ") -- or use a comma seperated list
file:write("team " .. team, " ") -- we can even mix & match!
end

-- Call the function
SaveCharacterData("gwen", 20, "blue")
..................Content has been hidden....................

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