lua-users home
lua-l archive

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


My solution that uses debug.getinfo works well. In your case, you could use a special require:

local files_done = {}

function relative_require(file)
  local filepath = string.match(debug.getinfo(2).source, '^@(.*)$')
  local dir = string.gsub(filepath, '/[^/]+$', '')
  local abspath = dir .. '/' .. file
  if not files_done[abspath] then
    dofile(abspath)
    files_done[abspath] = true
  end
end

2011/2/24 "J.Jørgen von Bargen" <jjvb.primus@gmx.de>
Hi, folks

The problem lies in nested scripts that do not (and should not) know the absolute position of the required sub-scripts (relative to "/" or to the running application).

I have a similar problem with loading libraries for our testing system. The layout is about this (well, with lot's more of files)

testlib/database/client.lua
testlib/communication/client.lua
testlib/communication/jxml.lua
testlib/api/client.lua
testlib/path.lua

in testlib/path.lua I simply have

local package=package
module("testlib.path")
package.path=package.path..";testlib/?.lua"

(because the way module/require works, this will only be executed once, no matter how often require"testlib.path" is used)


I a testenvironment I copy the testlib into a subfolder (well, really I check it out from a subversion repository, but that does not matter here, and there are *many* testenvironments, which share the testlib in this way)
So it looks like this

testfordevicexyz/testlib/database/client.lua
testfordevicexyz/testlib/communication/client.lua
testfordevicexyz/testlib/communication/jxml.lua
testfordevicexyz/testlib/api/client.lua
testfordevicexyz/testlib/path.lua
testfordevicexyz/testcase1.lua
testfordevicexyz/testcase2.lua
testfordevicexyz/testcase3.lua
testfordevicexyz/testcase4.lua

The testcases then look like this

require"testlib.path"    -- get path to the testlib
require"communication.client"        -- load the client
--
-- connect to device
--
local dev=communication.client.Connect("DeviceXYZ")
--
-- call some functions
--
local result=dev:InvokeMethodXyz("SomeTestParameter")


This works nearly fine but one problem remains:

In communication/client.lua I do a require"communication.jxml", which is ok when called from testcaseX, because the path is set accordingly.
But when I want use the client.lua and jxml.lua somewhere else, the require will fail, so I have to do
package.path=package.path..";../?.lua" in the client.lua to get it working, which doesnt make me happy.

On the other hand, when I do require"jxml", the client will work standalone, but will not be usable in the testlib, because the require then will fail.

Any suggestions to solve this better?

Regards, Jørgen