Skip to content

Commit 9904be9

Browse files
author
cheapie
committed
Add library support to Luacontrollers
This allows mods to provide their own libraries that can be accessed from within a Luacontroller, for example to make working with advanced digilines peripherals somewhat easier. Libraries can be added to the mesecon.luacontroller_libraries table, and then the code running in the Luacontroller can use require() to request one. require() will return nil if the library is not present.
1 parent 93aa24d commit 9904be9

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

mesecons/util.lua

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,25 @@ function mesecon.tablecopy(obj) -- deep copy
193193
return obj
194194
end
195195

196+
-- Performs a deep copy of a table, changing the environment of any functions.
197+
-- Adapted from the builtin table.copy() function.
198+
function mesecon.tablecopy_change_env(t, env, seen)
199+
local n = {}
200+
seen = seen or {}
201+
seen[t] = n
202+
for k, v in pairs(t) do
203+
if type(v) == "function" then
204+
local newfunc = v
205+
setfenv(newfunc, env)
206+
n[(type(k) == "table" and (seen[k] or mesecon.tablecopy_change_env(k, env, seen))) or k] = newfunc
207+
else
208+
n[(type(k) == "table" and (seen[k] or mesecon.tablecopy_change_env(k, env, seen))) or k] =
209+
(type(v) == "table" and (seen[v] or mesecon.tablecopy_change_env(v, env, seen))) or v
210+
end
211+
end
212+
return n
213+
end
214+
196215
-- Returns whether two values are equal.
197216
-- In tables, keys are compared for identity but values are compared recursively.
198217
-- There is no protection from infinite recursion.

mesecons_luacontroller/init.lua

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,16 @@ local function get_digiline_send(pos, itbl, send_warning)
459459
end
460460
end
461461

462+
mesecon.luacontroller_libraries = {}
463+
464+
local function get_require(env)
465+
return function(name)
466+
if mesecon.luacontroller_libraries[name] then
467+
return mesecon.tablecopy_change_env(mesecon.luacontroller_libraries[name],env)
468+
end
469+
end
470+
end
471+
462472
local safe_globals = {
463473
-- Don't add pcall/xpcall unless willing to deal with the consequences (unless very careful, incredibly likely to allow killing server indirectly)
464474
"assert", "error", "ipairs", "next", "pairs", "select",
@@ -546,6 +556,8 @@ local function create_environment(pos, mem, event, itbl, send_warning)
546556
for _, name in pairs(safe_globals) do
547557
env[name] = _G[name]
548558
end
559+
560+
env.require = get_require(env)
549561

550562
return env
551563
end

0 commit comments

Comments
 (0)