1

Suppose I have the following structure on my computer:

directory 
    a.lua
    subdirectory
        b.lua

and this Lua code:

-- a.lua
foo = "bar"

-- b.lua
dofile("../a.lua")
print(foo)

If I now run lua b.lua from directory, the relative path "../a.lua" is relative to directory, and the interpreter complains that b.lua does not exist. If I run the same command from within subdirectory, then the relative path "../a.lua" is relative to subdirectory, so it works.

My question: Why is it that relative paths are relative to where we execute the script, and how do I make it so that they are relative to where the script lives instead, like in the CJS require?

Nirvana
  • 405
  • 3
  • 15
  • Does this answer your question? [get current working directory in Lua](https://stackoverflow.com/questions/6032268/get-current-working-directory-in-lua) – Piglet Nov 01 '21 at 09:54
  • relative paths are relative to the current working directory. not the directory containing the current script file. – Piglet Nov 01 '21 at 09:54

1 Answers1

0

This code (Lua 5.2+ required) works from any directory

-- b.lua
local path = (({...})[2] or arg[0]):gsub("[^/]*$", "")
dofile(path.."../a.lua")
print(foo)
Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64