How to make modules in sub-folders available both from the root folder, and in the interpreter? (Details inside)
Hi,
something I've always wondered, despite having programmed in Lua for some time now:
Let's say I have a project like this
Project/
script.lua
plugins/
log.lua
db.lua
My script.lua requires both files in plugins/ using something like local log = require "plugins/log". And the content of log.lua looks like:
local log = {}
... ...
return log
(i.e. doesn't merge into _G).
This way, I can use log from my main script, and I can also go into the plugins directory, run lua -llog, and test my plugin from the interpreter.
But what happens if, for instance, log also needs to require db? Since I call script.lua from the root folder, the require in log looks like local db = "plugins/db", even though db is in the same directory.
If I want to test log from the interpreter now, I cannot run it from the plugins folder. I need to stay at the root folder, and either
- run
lua, then manually calllog = require "plugins/log(something I would like to avoid, since it requires manual typing every time) - call
lua -lplugins/log, which puts a key "plugins/log" into _G automatically, but that makes it hard to properly uselog.
Is there any way around this? Ideally, I would like to require db inside log like this: local db = require "db" (without the plugin path), but also make both of these require-able from script.lua in the root folder.
If possible, I would prefer something that doesn't involve messing with package.path during runtime. Something like this LUA_PATH=";;./plugins/?.lua" lua -llog would be fine for me, but is there also another way?
Posted Jun 17, 2017, 12:12 PM UTC