3

I have two local files in Lua and want to use a function in one that is implemented in the other. The use case is on Windows. My folder structure is as follows:

src/
---- main.lua
---- test.lua

There is a function in the main file:

function doSomething ()
    return true
end

I would like to include this in test.lua:

require("main")
print(doSomething())

This works if I compile from the src/ folder (lua test.lua.)

But if I compile from the main folder (lua src/test.lua), I get an error message because it looks for main.lua in the main folder. Is there any way to just always, no matter where I compile from, include the file in the same directory? Just as I can always write import file in Python and only the relative path of the file that performs the import is relevant.

I have seen hacky tricks that read the current directory (os.getenv("CD")), but is there any clean way to do that?

grottenolm
  • 352
  • 1
  • 3
  • 14
  • 2
    Does this answer your question? [Load Lua-files by relative path](https://stackoverflow.com/questions/9145432/load-lua-files-by-relative-path) – Luke100000 Sep 22 '22 at 10:28
  • Thank you very much, but I have already stumbled across this question in my research. My question is about how to compile from different folders. However, the linked question assumes that you always compile from the same place. – grottenolm Sep 22 '22 at 13:36
  • 2
    Hmm, I see the issue now. The linked example works fine, and I recommend using it wherever possible. However I didn't know that `arg`, or `...` does not contain the current path when started via command line. https://stackoverflow.com/questions/6380820/get-containing-path-of-lua-file seems to help here, it uses the debug library (assuming you have access to it). Modifying `package.path` would also help but feels more hacky here. – Luke100000 Sep 22 '22 at 16:11
  • 1
    Thank you very much, that helped me a lot. I had also seen manipulations of `package.path`, but they are indeed a bit hacky. The solution with the debug library is perfect for my use case. I will post an answer with my code. – grottenolm Sep 23 '22 at 13:38

1 Answers1

3

With the help of @Luke100000 I found a way to solve this problem. The path can be read out through the debug library. My code in the test file now looks like this:

function get_script_path()
    local str = debug.getinfo(2, "S").source:sub(2)
    return str:match("(.*[/\\])")
end

require(get_script_path() .. "main")
print(doSomething())

Please note that this code is for Windows. For other operating systems, the regex must be changed. For more information please look here: Get containing path of lua file

grottenolm
  • 352
  • 1
  • 3
  • 14