say I've a project folder like:
mxn:lab axn$ tree .
.
├── lib
│ ├── a.lua
│ └── b.lua
└── main.lua
where main.lua:
require("lib.a")
and in a.lua I just use the string "b", trying to tell lua - find a file whose name is b.lua in the same folder of a.lua first:
require("b")
and b.lua:
print('b loaded!')
then I run command lua main.lua and get error:
[Running] lua "/Users/axn/lab/main.lua"
lua: ./lib/a.lua:1: module 'b' not found:
no field package.preload['b']
no file './b.lua'
no file '/usr/local/share/lua/5.1/b.lua'
no file '/usr/local/share/lua/5.1/b/init.lua'
no file '/usr/local/lib/lua/5.1/b.lua'
no file '/usr/local/lib/lua/5.1/b/init.lua'
no file './b.so'
no file '/usr/local/lib/lua/5.1/b.so'
no file '/usr/local/lib/lua/5.1/loadall.so'
stack traceback:
[C]: in function 'require'
./lib/a.lua:1: in main chunk
[C]: in function 'require'
/Users/axn/lab/main.lua:1: in main chunk
[C]: ?
I know solutions like package.path = package.path..';'..'lib/?.lua', but what if the structure changes to:
.
├── foo
│ └── lib
│ ├── a.lua
│ └── b.lua
└── main.lua
I don't want to modify the package.path again. No matter what the structrue is, require("b") in a.lua will always make lua to search b in the same folder of a.lua first.
Rather than rewriting
requireand affecting the behavior of all code everywhere, it's best to create a special function for this purpose:Note that this function forces you to separate the local path from the name of the module being required. The given
local_pathis always expected to be local to the most recent nested call ofrequire_local_path. It is also expected to end in a/directory separator character.If you absolutely must give it a single string rather than a separate path, I'm sure you can write a version of this which splits the given module into a base name and a local path.