How do I read my txt file in assets folder?

image

I have “/assets/texts/mytext.txt” in my project folder. I am trying to read the file line by line, and return a table containing the lines.

For example,

--mytext.txt
--Hello,
--World!

--to {"Hello,", "World!"}

So I wrote the code,

function ReadTxt(file_path)
	local lines = {}
	local file = sys.load_resource(file_path)
	if file then
		for line in file:gmatch("([^\n]*)\n?") do
			table.insert(lines, line)
		end
	end
	return lines
end

But when I run this,

local script = ReadTxt("/assets/texts/mytext.txt")

This error occurs.

DEBUG:SCRIPT: Error: Unable to open file at	/assets/texts/mytext.txt

What’s wrong with my code? I’ve tried io.open as well, but I have no idea to reach my txt file (it means, I don’t know the directory of the file!).

Sorry, I wrote an old version of code. The new version:

function ReadTxt(file_path)
	local lines = {}
	local file = sys.load_resource(file_path)
	if file then
		for line in file:gmatch("([^\n]*)\n?") do
			table.insert(lines, line)
		end
	else
		print("Error: Unable to open file.")
	end
	return lines
end	

And the else statement makes the debug script.

Have you added the folder to the list of custom resource folders in game.project?

Thank you for the quick answer.
In conclusion, this was the happy ending:

function ReadTxt(file_path)
	local lines = {}
	local file = io.open(file_path, "r")

	if file then
		for line in io.lines(file_path) do
			table.insert(lines, line)
		end
	end

	io.close(file)
	return lines
end

local script = ReadTxt("assets/texts/mytext.txt")
  1. “assets/”, instead of “/assets/”.
  2. I used io.lines.

So, it was a little complexed problem not only dealing with directory but also code itself!

1 Like