Lua: Include file in the same directory
Asked Answered
F

2

5

I'm using IMAPFilter, and I'd like to keep my global configuration in a public repository, while keeping the local (and secret) configuration in a separate file. So I'm running imapfilter from some directory, it includes ~/.imapfilter/config.lua, and that should include ./config_local.lua, where "." is the directory of config.lua, not the shell $PWD or the location of imapfilter. Here's what I've tried so far:

require "config_local"
require "./config_local"

Edit: An absolute path works:

dofile(os.getenv("HOME") .. "/.imapfilter/config_local.lua")

Not very elegant, but at least it's compatible with cron.

Figureground answered 11/5, 2011 at 8:56 Comment(1)
require loads modules, not files: so no paths and no extensions. To load files, use dofile.Corrigan
C
10

Add the path to package.path.

Something like this (not tested):

package.path = package.path .. ";" .. os.getenv("HOME") .. "/.imapfilter/?.lua"
Cleanthes answered 11/5, 2011 at 10:21 Comment(0)
S
0

A more generalized solution for adding to package.path, if you want to use relative paths from where your entry .lua is located:

local separator = package.config:sub(1,1)

function get_directory_path(sep)
    local file_path = debug.getinfo(2, "S").source:sub(2)
    local dir_path = file_path:match("(.*" .. sep .. ")")
    return dir_path
end

local dir_path = get_directory_path(separator)

package.path = package.path .. ";" .. dir_path .. "?.lua"

-- or to specify a subdirectory:

package.path = package.path .. ";" .. dir_path .. ".imapfilter" .. separator .. "?.lua"

Slippage answered 22/3, 2024 at 18:10 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.