lua-users home
lua-l archive

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

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...


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')

================ 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)
  ----------- 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))