lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi,

I'm writing a collection of tools in Lua, and I find it's not trivial to
organize the individual tools into directories. The problem is that each
tool usually depends on some other tool, which it has to load before
doing anything else.

The "require" function and LUA_PATH should be the means to solve such
problems, but I don't find them to be enough.

Imagine the easiest case, a tool consisting of several .lua files in one
folder. The user calls the main file from the command line, either with
  lua \path\to\mytool.lua <params>
or simply with
  \path\to\mytool.lua <params>
if the .lua extension was associated with lua.exe, or even just
  mytool.lua <params>
if the tool's folder is on the PATH. How would mytool.lua then load the
rest of its modules? If the folder is on the PATH, it should be
relatively easy, adding os.getenv"PATH" to LUA_PATH. But if it isn't,
then we need to find the folder it was called from. For that, we'd need
to parse arg[0] into path and filename, and load the other modules using
the startup path. This means that each tool which is expected to be used
standalone (called from the command line), should begin with a few lines
for filename parsing, like this:

local function splitFileName( filename )
	local fn = string.gsub( filename, "%\\", "/" )
	if not string.find( fn, "/", 1, true ) then return "", fn end
	local s, e, p, n = string.find( fn, "(.-%/)([^%/]-)$" )
	return p, n
end

local strStartPath, strStartName = splitFileName( arg[0] )

LUA_PATH = (LUA_PATH or "?;?.lua;../?.lua") .. ";" .. strStartPath ..
"?.lua"

local utils = require "utils"


However, that's not the only problem. Now imagine that the "utils"
package in turn depends on another package.
When we call utils with require, it won't get an arg[0] or whatever
other way to tell its own folder, so that it can load the other modules
it depends on...

How do you solve similar problems?

Can we develop some standard means for easy finding of modules? It
should require the least initial code (nothing like the splitFileName
function above) and be able to load any module from folders relative to
the original's module folder.
The best solution to me seems to be to add to LUA_PATH (or make another
global variable MODULE_PATH for this) the folder where the module
resides. And it should be present always, no matter if the module was
loaded by loadfile, require, or the interpreter.

Regards,
Ivan