62

My directory structure looks like this:

|-- ball.lua
|-- entity.lua
|-- test
    `-- ball_test.lua

I'm using the following code in test/ball_test.lua to require ball.lua from the parent directory:

package.path = package.path .. ";../entity.lua"
require("entity")
package.path = package.path .. ";../ball.lua"
require("ball")

entity.lua is a dependency of ball.lua. So I require("entity") first otherwise I get a module 'entity.lua' not found error. This seems like a hack, what's a better way to do this?

Seth Reno
  • 5,350
  • 4
  • 41
  • 44
  • have ball module require entity.lua, so you just have to require'ball' – Łukasz Gruner Apr 23 '11 at 11:35
  • 3
    @Lukasz - ball does require entity.lua. I get the error because require can't find entity.lua when it's executed from the test subdirectory. Sorry I didn't make that clear in my question. – Seth Reno Apr 23 '11 at 12:45

1 Answers1

90
package.path = package.path .. ";../?.lua"

will work for both.

Doug Currie
  • 40,708
  • 1
  • 95
  • 119
  • 11
    I would switch this around to `package.path = ";../?.lua" .. package.path` so I don't have unknown modules beating the local ones. – Stuart P. Bentley May 24 '11 at 14:22
  • 26
    I'm guessing you meant ``package.path = "../?.lua;" .. package.path`` (the path delimiter should be moved). Otherwise, good idea. – Todd Apr 30 '12 at 04:11
  • 7
    +1 for anyone looking for how to do this for C extension modules, you need to modify `package.cpath` not `package.path`; otherwise it is much the same – wakjah Sep 30 '15 at 13:51
  • 3
    this is bad idea if you use NGINX LUA modul. package.path is global. Each request, this code executed and concate infinitely. At the end, it will explose. I have a bad experience in PROD with this code. Please use lua_package_path instead. Read this article also https://medium.com/@fabricebaumann/how-we-reduced-the-cpu-usage-of-our-lua-code-cc30d001a328 lua_package_path ";;/your/folder/lua/?.lua" ; _;;_ is a symbolic link to your defaut package lua directory. Do not remove it. – uwevil Nov 20 '20 at 09:18