Load Lua-files by relative path

前端 未结 4 1704
故里飘歌
故里飘歌 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条回答
  •  旧时难觅i
    2020-12-23 12:02

    There is a way of deducing the "local path" of a file (more concretely, the string that was used to load the file).

    If you are requiring a file inside lib.foo.bar, you might be doing something like this:

    require 'lib.foo.bar'
    

    Then you can get the path to the file as the first element (and only) ... variable, when you are outside all functions. In other words:

    -- lib/foo/bar.lua
    local pathOfThisFile = ... -- pathOfThisFile is now 'lib.foo.bar'
    

    Now, to get the "folder" you need to remove the filename. Simplest way is using match:

    local folderOfThisFile = (...):match("(.-)[^%.]+$") -- returns 'lib.foo.'
    

    And there you have it. Now you can prepend that string to other file names and use that to require:

    require(folderOfThisFile .. 'baz')     -- require('lib.foo.baz')
    require(folderOfThisFile .. 'bazinga') -- require('lib.foo.bazinga')
    

    If you move bar.lua around, folderOfThisFile will get automatically updated.

提交回复
热议问题