Search code examples
luarequire

How can a file be imported in Lua relative to the folder of the importing file?


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?


Solution

  • 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