lua-users home
lua-l archive

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


I have found a better solution with debug.getinfo:

-- Find the source of the current file.
function lk.source(level)
  local level = level or 0
  return debug.getinfo(level + 2).source
end

-------------------------------- lk.dir()
-- Find the directory of the current file.
function lk.dir(level)
  local level = level or 0
  local source = string.gsub(lk.source(level+1), '/[^/]+$', '')
  return string.match(source, '^@(.*)$')
end


On Thu, Feb 24, 2011 at 11:06 AM, Gaspard Bucher <gaspard@teti.ch> wrote:
Hi list,

To ease installation and improve stability when moving scripts around, I need to load Lua files relative to the current file. What I basically need is a local FILE_DIR variable set to the file's directory.

My solution involves inserting a "local FILE_DIR" at the top of the files on file load but I wonder if there is a better way to solve this problem...

Gaspard

Typical usage script:
================ foo_test.lua
require 'lubyk'
FILE_DIR = FILE_DIR or lfs.currentdir() -- in case the file is run alone

...
function should.do_this_and_that()
  local fixture = fixture.readall(FILE_DIR, 'xxx.txt')
end
================

================ lk.dofile

function lk.dofile(filepath)
  local abs_path = filepath
  local cur_path = lfs.currentdir()
  if not string.match(abs_path, '^/') then
    abs_path = string.format('%s/%s', cur_path, filepath)
  end
  ----------- FILE_DIR hack -----------
  local code_str = string.format("local FILE_DIR = '%s';%s", string.gsub(abs_path, '/[^/]+$', ''), lk.readall(abs_path))
  local code = assert(loadstring(code_str))
  code()
end
================