read and write data
The io library in Lua language is used to maintain your data inside persistent structure like your memory disk or in other similar places.
This tutorial will cover only read-only mode which is the default mode for opening files, if the file exist it returns the file handle otherwise nil is returned, and the write mode which can let you create a file and write over it if the file does not exist otherwise this file will be overwritten.
So, create a new file called test.lua inside a folder, open up your text editor and type in:
local file = io.open("filename.txt") --io.open("filename.txt", "r") should work the same way print(file) -- It will prints out nil, because there is no filename.txt
To check if the file exist open up your terminal, go inside your folder and type lua test.lua
To create this file, the mode needs to be changed to write mode.
For writing data you have to call the write method which lets you pass arguments inside the file you want to create.
Let's see how it works:
local number = 7 local string = "seven" local boolean = tostring(number == boolean) local file = io.open("filename.tx", "w") file:write(number .. "\n") file:write(string .. "\n") file:write(boolean .. "\n") io.close(file)
At the end of all remember to close the file handle.
Now you have a filename.txt inside your folder with all these previously stated data.
How to reading data from an existing file?
For reading arguments inside a file, lines() method is required.
It can retrieve every line by using a loop.
The following code demonstrates how to print out all this lines:
-- Open again your previous "filename.txt" in "read-only" mode local file = io.open("filename.txt", "r") for line in file:lines() do print(line) end -- Remember to close it io.close(file)
On the console you will see:
If you want to see this code in action watch this video: