Lua File I/O

The Lua I/O library is used for reading and processing files. It is divided into simple mode (same as C) and complete mode.

  • Simple model has a current input file and a current output file, and provides operations related to these files.
  • Complete model uses external file handles for implementation. In an object-oriented form, it defines all file operations as methods of the file handle.

Simple mode is more suitable for some simple file operations. But when performing some advanced file operations, simple mode seems inadequate. For example, for operations such as reading multiple files at the same time, complete mode is more suitable.

The file open operation statement is as follows:

file = io.open (filename [, mode])

The values of mode are:

ModeDescription
rOpen the file in read-only mode; the file must exist.
wOpen a write-only file. If the file exists, its length is cleared to 0, that is, its content will disappear. If the file does not exist, create it.
aOpen a write-only file in append mode. If the file does not exist, it will be created. If the file exists, written data will be appended to the end of the file, that is, the original content of the file will be preserved. (EOF marker preserved)
r+ Open the file for reading and writing; the file must exist.
w+ Open a file for reading and writing. If the file exists, its length is cleared to zero, that is, its content will disappear. If the file does not exist, create it.
a+ Similar to a, but this file is readable and writable.
b Binary mode. If the file is a binary file, you can add b.
+ The + sign indicates that the file can be both read and written.

Simple Mode

Simple mode uses standard I/O or uses a current input file and a current output file.

The following is the code of the file.lua file. The file being operated on is test.lua (if it does not exist, you need to create it). The code is as follows:

Example

-- Open the file in read-only mode
file = io.open("test.lua", "r")

-- Set the default input file to test.lua
io.input(file)

-- Output the first line of the file
print(io.read())

-- Close the opened file
io.close(file)

-- Open a write-only file in append mode
file = io.open("test.lua", "a")

-- Set the default output file to test.lua
io.output(file)

-- Add a Lua comment to the last line of the file
io.write("-- test.lua end-of-file comment")

-- Close the opened file
io.close(file)

After executing the above code, you will find that it outputs the first line information of the test.lua file and adds a Lua comment to the last line of the file. For example, my output here is:

-- test.lua 文件

In the above example, we used the io."x" method. In io.read(), we did not pass a parameter. The parameter can be one of the following in the table:

ModeDescription
"*n"Read a number and return it. Example: file.read("*n")
"*a"Read the entire file from the current position. Example: file.read("*a")
"*l" (default)Read the next line; return nil at EOF. Example: file.read("*l")
numberReturn a string of the specified number of characters, or return nil at EOF. Example: file.read(5)

Other io methods include:

  • io.tmpfile():Return a temporary file handle. The file is opened in update mode and is automatically deleted when the program ends.

  • io.type(file):Check whether obj is a usable file handle.

  • io.flush():Write all buffered data to the file.

  • io.lines(optional file name):Return an iterator function. Each call will get a line from the file. At EOF, it returns nil, but does not close the file.


Complete Mode

Usually we need to process multiple files at the same time. We need to use file:function_name instead of io.function_name methods. The following example demonstrates how to process the same file at the same time:

Example

-- Open the file in read-only mode
file = io.open("test.lua", "r")

-- Output the first line of the file
print(file:read())

-- Close the opened file
file:close()

-- Open a write-only file in append mode
file = io.open("test.lua", "a")

-- Add a Lua comment to the last line of the file
file:write("--test")

-- Close the opened file
file:close()

After executing the above code, you will find that it outputs the first line information of the test.lua file and adds a Lua comment to the last line of the file. For example, my output here is:

-- test.lua 文件

The parameters of read are the same as in simple mode.

Other methods:

  • file:seek(optional whence, optional offset):Set and get the current file position. On success, return the final file position (in bytes); on failure, return nil plus an error message. The whence parameter can be:

    • "set": start from the beginning of the file
    • "cur": start from the current position [default]
    • "end": start from the end of the file
    • offset: default is 0
    Without parameters, file:seek() returns the current position; file:seek("set") positions to the beginning of the file; file:seek("end") positions to the end of the file and returns the file size.
  • file:flush():Write all buffered data to the file.

  • io.lines(optional file name):Open the specified file filename in read mode and return an iterator function. Each call will get a line from the file. When reaching EOF, it returns nil and automatically closes the file.
    When called without parameters, io.lines() <=> io.input():lines(); it reads the content of the default input device, but does not close the file at the end, for example:

    for line in io.lines("main.lua") do
    
      print(line)
    
      end
    

The following example uses the seek method to position to the 25th position from the end of the file, and uses the *a parameter of the read method, that is, reads the entire file from the current position (the 25th position from the end).

Example

-- Open the file in read-only mode
file = io.open("test.lua", "r")

file:seek("end",-25)
print(file:read("*a"))

-- Close the opened file
file:close()

My output here is:

st.lua 文件末尾--test
Other Extensions