Import

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.

With the help of core.parse_json, JSON files can also be imported. They are returned as Lua tables.

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. When importing a Lua file, the return value of the file is returned. When importing a JSON file, a table is returned.

import.resolve(path) 🔗

Resolves a path relative to the Lua environment to be used in other functions.

import.resolve("init.lua")
-- e.g. /home/wiz/.minetest/games/devtest/mods/test/init.lua

Reviews

Review

Do you recommend this mod?

  • No reviews, yet.

Releases

2026-06-17-WIP

Download

2026-06-17 16:47 UTC

2026-06-17-WIP 🔗

added import.resolve

2025-06-15-WIP

Download

2026-06-15 07:48 UTC

2025-06-15-WIP 🔗

a small fix

2026-06-08-WIP

Download

2026-06-08 06:43 UTC

2026-06-08-WIP 🔗

Added the ability to import JSON files.

2026-06-06-WIP

Download

2026-06-06 11:52 UTC

2026-06-06-WIP 🔗

No release notes

All releases

Information

Provides

import

Dependencies

Required
No required dependencies

Information

Type
Mod
Technical Name
import
Languages
English
License
GPL-3.0-or-later
Maintenance State
Work in Progress
Added
2026-06-03 13:40 UTC
Maintainers
Wiz