Load Lua-files by relative path

前端 未结 4 1710
故里飘歌
故里飘歌 2020-12-23 11:22

If I have a file structure like this:

./main.lua
./mylib/mylib.lua
./mylib/mylib-utils.lua
./mylib/mylib-helpers.lua
./mylib/mylib-other-stuff.lua

4条回答
  •  无人及你
    2020-12-23 12:23

    I'm using the following snippet. It should work both for files loaded with require, and for files called via the command line. Then use requireRel instead of require for those you wish to be loaded with a relative path.

    local requireRel
    if arg and arg[0] then
        package.path = arg[0]:match("(.-)[^\\/]+$") .. "?.lua;" .. package.path
        requireRel = require
    elseif ... then
        local d = (...):match("(.-)[^%.]+$")
        function requireRel(module) return require(d .. module) end
    end
    

提交回复
热议问题