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:
FILread and FILwrite functions offer convenient wrappers to read and write files
FILwrite is passed the FileName, containing the path of the file, and the Contents to be written. It uses io.open() 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: What does it mean when we read a file in binary?
The provided Content is written to the open file using io.write() and then closed ( io.close()).
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 io.read().
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 Translator and view the Annotation Windows to see the results. For example, here we are writing “Hello!“ to a file and then reading the file confirming its contents:
![]()
FILextension uses pattern matching to get the file extension type of a file (ex. "txt")
The FILextension function takes the filename and uses String:match() and Pattern Matching to match and return the file extension (LastDotIndex). Conditional logic ( if statements) 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.
FILfilename uses pattern matching to get the filename from the full file path (directory location and name)
Applying the same foundational concepts, the FILfilename function uses lua pattern matching to extract the filename from the full filepath.
function FILfilename(FilePath)
-- Find the last path separator (either / or \) in the filepath
local i = FilePath:match("[\\/]([^\\/]+)$")
if i then
return i:match("(.+)%..\*") or i
else
-- If there is no path separator, just return the input as the file name
return FilePath:match("(.+)%..\*") or FilePath
end
end
You can see an example of this in the Translator by calling FILfilename:
![]()
Just the filename “ message“ is extracted and returned.