I'm trying to make a Discord bot with lua and its going well so far, but I'm having a couple problems with the IO portion of lua. I'm trying to read a large list.txt file in lua and inserting each line into a table, but so far all of my attempts didn't work. Any advice?
Attempt #1 spits out nil:
local open = io.open
local function read_file(path)
local file = open(path, "r") -- r read mode and b binary mode
if not file then return nil end
local content = file:read "*a" -- *a or *all reads the whole file
file:close()
return content
end
local fileContent = read_file("list.txt")
local vga_files = {}
table.insert(vga_files, fileContent)
I was not able to replicate your error running your code. Your code is valid, and is likely doing what you asked it to do.
here you tell the
read_filefunction to returnnil:So if the
fileis not found you will getnil. A good step in debugging would be to add a print in the body of this if statement and see if it is getting entered.When you call
read_file:you pass in only a file name, this means lua will look for that where ever the code is being executed, and this location maybe different from what you expect.
I validated your code works by pointing the read at itself, and printing the result.
Additionally to get the lines you should really used
io.lineswhich creates an iterator that you can use in a for loop.Or alternatively you can read the file and then split the lines using gmatch.