modlib/init.lua

77 lines
2.1 KiB
Lua
Raw Normal View History

2019-05-01 16:53:01 +02:00
-- Lua version check
if _VERSION then
if _VERSION < "Lua 5" then
2020-02-09 01:39:54 +01:00
error("Outdated Lua version! modlib requires Lua 5 or greater.")
2019-05-01 16:53:01 +02:00
end
2019-08-12 12:36:08 +02:00
if _VERSION > "Lua 5.1" then -- TODO automatically use _ENV instead of s/getfenv if _VERSION > 5.1
2020-02-09 01:39:54 +01:00
-- not throwing error("Too new Lua version! modlib requires Lua 5.1 or smaller.") anymore
loadstring = load
function setfenv(fn, env)
local i = 1
while true do
name = debug.getupvalue(fn, i)
if name == "_ENV" then
debug.setupvalue(fn, i, env)
break
elseif not name then
break
2019-07-13 19:55:49 +02:00
end
end
2020-02-09 01:39:54 +01:00
return fn
2019-07-13 19:55:49 +02:00
end
2020-02-09 01:39:54 +01:00
function getfenv(fn)
local i = 1
local name, val
repeat
name, val = debug.getupvalue(fn, i)
if name == "_ENV" then
return val
2019-05-01 16:53:01 +02:00
end
2020-02-09 01:39:54 +01:00
i = i + 1
until not name
2019-05-05 15:09:26 +02:00
end
2019-05-03 19:04:47 +02:00
end
2020-02-09 01:39:54 +01:00
end
2019-07-13 19:55:49 +02:00
2020-02-28 22:12:05 +01:00
local function loadfile_exports(filename)
2020-02-09 01:39:54 +01:00
local env = setmetatable({}, {__index = _G, __call = _G})
local file = assert(loadfile(filename))
setfenv(file, env)
file()
return env
end
2020-02-28 22:12:05 +01:00
-- TODO automatically know current mod
2019-07-13 19:55:49 +02:00
2020-02-09 01:39:54 +01:00
local components = {
2020-02-28 22:12:05 +01:00
mod = {},
2020-02-09 01:39:54 +01:00
class = {class = "global"},
conf = {conf = "global"},
data = {data = "global"},
file = {file_ext = "global"},
log = {log = "global"},
minetest = {mt_ext = "global"},
number = {number_ext = "global"},
player = {player_ext = "global"},
table = {table_ext = "global"},
2020-02-28 22:12:05 +01:00
text = {string_ext = "global", string = "local"},
2020-02-09 01:39:54 +01:00
threading = {threading_ext = "global"}
2019-05-01 16:53:01 +02:00
}
2020-02-09 01:39:54 +01:00
modlib = {}
2019-05-01 16:53:01 +02:00
2020-02-09 01:39:54 +01:00
for component, additional in pairs(components) do
local comp = loadfile_exports(get_resource("modlib", component .. ".lua"))
modlib[component] = comp
for alias, scope in pairs(additional) do
if scope == "global" then
_G[alias] = comp
else
modlib[alias] = comp
2019-05-01 16:53:01 +02:00
end
end
2020-02-09 01:39:54 +01:00
end
2019-05-01 16:53:01 +02:00
2020-02-28 22:12:05 +01:00
modlib.mod.loadfile_exports = loadfile_exports
2020-02-09 01:39:54 +01:00
_ml = modlib