How the FIL library works

The FIL library is a great helper library for basic file operations like reading a file, writing a file and has a few other utilities like getting a file extension and file name from a full file name.

This is how it works:

FILwrite is passed the FileName, containing the path of the file, and the Contents to be written. It uses to open the file in “wb+” mode, treating the file as a binary to be updated (overwriting all previous data) or will create the file if it does not exist.

See:

The provided Content is written to the open file using and then closed ().

function FILwrite(FileName, Content) local F = io.open(FileName,'wb+') F:write(Content) F:close() end

Similarly, for reading a file with FILread, the FileName is passed, opened in “rb” binary read mode for the entire (“*a”) contents of the file to be read using .

function FILread(FileName) local F = io.open(FileName,'rb') Result = F:read("*a") F:close() return Result end

You can try FILread and FILwrite in the and view the to see the results. For example, here we are writing “Hello!“ to a file and then reading the file confirming its contents:

The FILextension function takes the filename and uses and to match and return the file extension (LastDotIndex). Conditional logic () is used to return the extension or an empty string if it does not exist.

function FILextension(FileName) local LastDotIndex = FileName:match(".*%.(.*)$") if LastDotIndex then return LastDotIndex else return "" end end

You can see an example of this in the Translator by calling FILextension:

Just the extension “txt“ was extracted and returned.

Applying the same foundational concepts, the FILfilename function uses lua pattern matching to extract the filename from the full filepath.

You can see an example of this in the Translator by calling FILfilename:

Just the filename “message“ is extracted and returned.