Opening a file

When writing to a file or reading from a file, that file needs to be opened first. Lua provides the io.open function to open files. On success, the io.open function will return a file handle. On failure, it will return nil:

file = io.open("my_file.txt"); -- Opens existing file in read only mode

The preceding line of code will open a file in read-only mode. What if you want to write to a file? The io.open function takes an optional second argument, which is a string. This optional second argument controls the mode in which the file will be opened. Valid values are as follows:

  • "r": Read-only mode will let you read the file, but not write to it. This is the default mode for opening the file. If the file does not exist, nil is returned.
  • "w": Write mode will create a new file if the specified file name does not exist. If the specified file name exists, it will be overwritten! Allows writing to the file only.
  • "a": Append mode opens an existing file, or creates a new one. If the file already exists, its contents remain unchanged and we write data to the end of the file. Allows writing to the file only.
  • "r+": Read and write mode for an existing file. This mode will open an existing file and allow us to read from and write to it. If the file already exists, its contents will be overwritten! If the file does not exist, the function returns nil.
  • "w+": The same as "w", except this mode allows us to read from the file as well.
  • "a+": The same as "a", except this mode allows us to read from the file as well.

If you want to open an existing file for reading and writing, call io.open, like so:

file = io.open("my_file.txt", "r+"); -- Opens existing file in read/write mode

The file handle returned by io.open is a Lua object. as such, the colon operator will be used to call methods on this object. The methods of the file handle can read, write, and close the file.

..................Content has been hidden....................

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