[SOLVED] Can't open .txt file

This is my first attempt to use Defold and i can’t figure out how to use files here(
The file is in main, it has text in it, but it return nil.

ERROR:SCRIPT: main/text.script:9: attempt to index local ‘file’ (a nil value)
stack traceback:
main/text.script:9: in function <main/text.script:4>

function init(self)
	local file = io.open("/main/sceneinfo.txt", "r")
	if not file then
		print("Не удалось открыть файл!")
	end
	local text = file:read("*all")
	file:close()
	print(text)
	label.set_text("#label", text)
	
end

It should be

local file = io.open("main/sceneinfo.txt", "r")

because / at the start of the path implies the root of the drive, so

local file = io.open("/main/sceneinfo.txt", "r")

would look for C:\main\sceneinfo.txt.

2 Likes

Also, if you don’t want the file to be in the folder of the release, but bundled in the archive, you should use custom resources instead, by putting /main/sceneinfo.txt as a custom resource in game.project, and using:

local text = sys.load_resource("/main/sceneinfo.txt")

where / is the root of your project, and not the drive.

io.open() is more useful if the file can change during the game, or if the player is supposed to edit it.

See here: https://defold.com/manuals/file-access/

2 Likes

You can use API reference (sys) to load your resource file. Remember set it as a resource file in game.project.

If you want to use io.open, you will need to use an absolute file path. You can use sys.get_save_file() to get it but it’s not located in your project workspace, it’s stored in user document folder or other storages

1 Like

Note that custom files are not automatically bundled with your game. I advise you to read the Files manual to learn the various ways in which you can work with and include custom files in your game:

2 Likes