Lua add package path

Date: 2016-03-30

The add_package_path function:

local gmatch = string.gmatch
local append = table.insert
local join = table.concat

function to_array(iterator)
    local arr = {}
    for v in iterator do
        append(arr, v)
    end
    return arr
end

function add_path(package_path, path)
  local paths = to_array(gmatch(package_path, "[^;]+"))
  -- check if the path does not exist?
  append(paths, path)
  return join(paths, ";")
end

function add_package_path(path)
  package.path = add_path(package.path, path)
end

function add_package_cpath(path)
  package.cpath = add_path(package.cpath, path)
end


print(add_path(package.path, './lua_modules/?.lua'))




Luarocks example:

mkdir app
cd app/
luarocks install --tree=lua_modules promise-es6 
luarocks install --tree=lua_modules luv
luarocks list --tree=lua_modules

Example usage of the add_package_path function:

add_package_path("./lua_modules/share/lua/5.3/?.lua")
add_package_cpath("./lua_modules/lib/lua/5.3/?.so")

local Promise = require("Promise")
local luv = require("luv")
1890cookie-checkLua add package path