lua-users home
lua-l archive

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


Hi all,

Having painted myself into a corner, I needed a script which would
look up the full path of a Lua module and run it as the main script.

So if test.lua is on the Lua module path, and is

for i = 1,#arg do print(arg[i]) end

then

$ lua lenv.lua test one two three
one
two
three

But what I get is, on both Windows and Ubuntu:

$ lua lenv.lua test one two three
one
two
three
nil

Here's the full script (the concept at least might be useful/interesting)

It does work with markdown.lua, which is distributed as a module but
often gets used as a program.

-- lenv.lua --------------------------------------------
local dir_separator = package.config:sub(1,1)

local function searchpath (mod,path)  -- Lua 5.2 provides us this
directly, of course
  mod = mod:gsub('%.',dir_separator)
  for m in path:gmatch('[^;]+') do
    local nm = m:gsub('?',mod)
    local f = io.open(nm,'r')
    if f then f:close(); return nm end
  end
end

local function package_path(mod)
    mod = mod:gsub('%.',dir_separator)
    local res = searchpath(mod,package.path)
    if res then return res end
    return nil,'cannot find module on path'
end

local modpath = package_path(arg[1])
if not modpath then
   return print ('cannot find module '..arg[1])
end

table.remove(arg,1)  -- the module name
arg[0] = modpath  -- this is now our program (some modules check this)
local res,err = dofile(modpath)
if not res then print(err) end
----------------------------------------------

Note that printing out the array items in arg after the modification
does print what I expect, except that the dofile() invocation adds the
extra nil, which some scripts may take exception to.

I suppose I could do an os.execute() at this point, but I'm curious
why there is an extra item in arg when the main script is run in
dofile().

(The particular corner problem is similar to the markdown case;
lake.lua would get distributed as a module by LuaRocks, but is usually
invoked as a program, and I want to avoid an install script.)

steve d.