Description
WIP, tested on Linux. Windows has different file paths but everything should work. If you are a Windows user and find this useful, I would appreciate a comment about whether this works.
Lua's built-in require function is not available in the secure mod environment. Instead, another built-in, dofile, is used. However, dofile has a few weak points when used to replace require: mainly, it does not cache results, which leads to duplicated work that could be avoided.
This mod introduces the helper function import that fixes these flaws: if an imported file returns a non-nil value, that value is cached. When the file is imported again, that value is returned instead. In addition, relative paths can be used as input, which makes managing deeply nested directory structures much easier.
For instance, let us consider the following layout:
mod
├─dir1
│ ├─dir2
│ │ └─file2.lua
│ └─file1.lua
└─init.lua
How would we get file2.lua from file1.lua?
file2.lua:
local export = {}
function export.function(x)
-- ...
end
return export
with dofile: 🔗
file1.lua:
local path = core.get_modpath("mod")
local imported = dofile(path .. "/dir1/dir2/file2.lua")
with import 🔗
file1.lua:
local imported = import("dir2/file2.lua")
In this simple example the difference is not too great. With more complex structures, however, the advantages become apparent.
API 🔗
import(path) 🔗
Imports a file from path, which can be absolute or relative. The result will be cached for subsequent calls.