1

I'm currently trying to open a file using io.open(file_name, "r")

My directory structure is

parent_dir  
   -src  
      -main.lua  
   -tests
      -test.txt

I'm currently trying to open the txt file from the tests folder in the main.lua using io.open(file_name, "r") but it won't recognize the file as existing. If I place the absolute path into the file_name it works. I'm not sure how to format a relative path? I've tried some version of ../../../tests/test.txt but I can't seem to get it to work. The actual path of the file is something like /Users/user_name/parent_dir/tests/test.txt

Zoe
  • 27,060
  • 21
  • 118
  • 148
Ann
  • 11
  • 3
  • 1
    If you are going to use a relative path (`../../tests.txt`), you need to properly generate it by considering your current working directory. Try printing current working directory and check whether the relative path is correctly pointing from there to the file you need. – Anubis Apr 16 '19 at 06:02

1 Answers1

1

The ../ syntax is correct to specify relative paths.

But this is not relative to the location of your Lua script but to your current working directory.

Refer to get current working directory in Lua

You cannot change the current working directory from within a Lua script unless you use libraries like LuaFileSystem.

If you're running a single script you can check if global arg[0] (if it is not nil) contains the path of that script. You can use that to build an absolute path from your script's location.

Piglet
  • 27,501
  • 3
  • 20
  • 43