DEV Community


Posted on • Updated on

Using files in LuaRT

LuaRT is a comprehensive Windows framework to develop in Lua with a specific runtime library. In the Lua standard library, input / output functionalities are gathered within the io module. In LuaRT, they are grouped together within the sys module, and more particularly the File object.

Using the File object in LuaRT

The manipulation of files in LuaRT is facilitated by the use of File objects: creation of files, opening, closing, moving, copying, deleting ...

Creating a File value

At this point, it's important to understand that a File object represents an abstraction of a file that may or may not physically exist. For example, when creating a new file, only the call to the File:open() method will physically create the file on the computer's storage:

local newfile = sys.File("hello.txt") -- newfile holds a File value
print(newfile.exists) -- outputs false
newfile:open("write") -- creates the file physically on the disk 
newfile:close()       -- closes the opened File
print(newfile.exists) -- now outputs true
Enter fullscreen mode Exit fullscreen mode

File operations

A File object can be used to perform file operations:

local file = sys.File("test.txt") 
file:copy("test_copy.txt")   -- copies file
file:move("C:\")             -- moves file
file:remove()                -- deletes the file
Enter fullscreen mode Exit fullscreen mode

Opening and closing a File

A file can be opened to read or write its content. This is done by calling the File:open() method. By default, the file is open in "read" mode. The file encoding can be specified as a second argument or detected using Byte Mark Order :

local file = File("test.bin")
file:open()   -- opens the file "test.bin" in read mode (encoding is autodetected)
file:close()                   -- closes the file
file:open("write", "binary")   -- open the file in write mode (erasing its previous content), using "binary" encoding(ie raw binary)
Enter fullscreen mode Exit fullscreen mode

Do not forget to close a file after the transaction on this one ended. This is done automatically when the File object is garbage collected, but that cannot be predicted.

Reading and writing Files

Once the File object has been created, and the File:open() method called, you can write or read on the File (depending on the mode used in the call). These methods return Buffer objects in binary mode (containing in memory binary data) or strings in UTF8 or UNICODE mode.

Reading file content

There are two methods for reading the content of a file: File:read() and File:readln()

local file = File("README.TXT"):open()  -- opens the File for reading
print(file:read())  -- reads and prints all the file content 
Enter fullscreen mode Exit fullscreen mode

The File:read() method reads a number of characters (when using UTF8 or UNICODE mode) or bytes (in binary mode) specified as argument, or all the content of the file if no argument is provided.

The File:readln() method reads a line (until end of line characters "\r\n" or "\n" are encountered).

Writing to files

There are two methods for writing data to a file: File:write() and File:writeln()

Each method take one argument, converted to a string to be written to the file. In binary mode, Buffer objects can be used.

File:writeln() writes a line to the file, appending "\r\n" (corresponding to the End Of Line marker on Windows).

File position

The File.position property get or set the current file position, as a number. File position always starts at 1 (as for all indexed/positioned values in Lua).
File position interpretation depends on the file encoding.
In "binary" encoding : the position is expressed in bytes.
In "utf8" or "unicode" encoding : the position is expressed in characters.
The File.eof property checks if the end of the file have been reached.

File timestamps

The File.accessed, File.modified and File.created permits to set or get timestamps using a Datetime object (in LuaRT, Datetime objects represent a moment, a combination of a date and a time).

File attributes

The File.hidden, File.temporary and File.readonly permits to set or get the corresponding attributes.

File path and names

The File.fullpath, File.filename, File.extension, File.path permits to get access to the different parts of a filename.

As you can see, File objects provide easy access to all of the functionality related to creating, reading, writing and manipulating files in LuaRT. These features go beyond the capabilities offered by the standard Lua library.

Top comments (3)

tilkinsc profile image
Cody Tilkins • Edited

As the author of LuaConsole, I know how bare bones are dated the Lua IO library is. LuaRT seems a welcome addition. I like the direct open and close statements, but I do not like the passing of strings for parameters other than "rb" for example.

samyeyo profile image
Sam • Edited

Thank you so much for that comment !
"rb" "rw" and so on are from the "C world". As LuaRT philosophy is to be as much possible independent to C, I preferred the words "read" "write" "append" to approach Lua readability, but that might change in the future depending on community feedback :)

tilkinsc profile image
Cody Tilkins • Edited

Not so much "C world" its a commonly used paradigm. My favorite IO library is linux and ruby flavored. Back when I was developing things on the PSP.