File Reading and Writing in Lua is often used in game configurations, such as the audio switch on the client.
Lua official API documentation: click here
The I/O Library provides four main functions for file operations: Io. open (), Io. Read (), Io. Write, and Io. Close ().
Io. Open (file path, open mode): open a file in the specified way. If the file is opened successfully, a file handle is returned. If the file fails to be opened, nil and error description are returned.
You can enter the following six open methods:
"R": Read mode (Default);
"W": Write mode;
"A": additional mode;
"R +": update mode. All previous data is retained;
"W +": update mode. All previous data is erased;
"A +": adds the update mode. The previous data is saved and the writing is only allowed at the end of the file.
Io. Read: reads a file in the specified method, returns the string or number, or nil.
There are five methods to read data:
"* N": reads a number. The unique return value is a number rather than a string;
"* A": reads all the following content from the current position. If it is at the end of the file, an empty string is returned;
"L": reads the content of the next line, excluding line breaks. Nil is returned at the end of the file,Default read mode;
"L": reads the content of the next line, including line breaks (if any). Nil is returned at the end of the file.
Number: reads the string of the specified number of bytes and returns nil at the end of the file. If the number is 0, an empty string is directly returned if the number is not read.
Io. Write ()
Write the value of each parameter to the file. The parameter must be a string or number. If the file is written successfully, nil and error description are returned if the file fails to be written.
No parameter.
Io. Close ()
Close the opened file without any parameters.
Instance:
-- Read the specified file function GetFile (file_name) Local F = assert (Io. open (file_name, 'R') Local string = F: Read ("* All") F: Close () return stringend
-- String write function writefile (file_name, string) Local F = assert (Io. Open (file_name, 'w') F: Write (string) F: Close () End