1---@diagnostic disable: undefined-global
2
3-- Create a sandbox environment
4local sandbox = {}
5
6-- For now, add all globals to `sandbox` (so there effectively is no sandbox).
7-- We still need the logic below so that we can do things like overriding print() to write
8-- to our in-memory log rather than to stdout, we will delete this loop (and re-enable
9-- the I/O module being sandboxed below) to have things be sandboxed again.
10for k, v in pairs(_G) do
11 if sandbox[k] == nil then
12 sandbox[k] = v
13 end
14end
15
16-- Allow access to standard libraries (safe subset)
17sandbox.string = string
18sandbox.table = table
19sandbox.math = math
20sandbox.print = sb_print
21sandbox.type = type
22sandbox.tostring = tostring
23sandbox.tonumber = tonumber
24sandbox.pairs = pairs
25sandbox.ipairs = ipairs
26
27-- Access to custom functions
28sandbox.search = search
29sandbox.outline = outline
30
31-- Create a sandboxed version of LuaFileIO
32-- local io = {};
33--
34-- For now we are using unsandboxed io
35local io = _G.io;
36
37-- File functions
38io.open = sb_io_open
39
40-- Add the sandboxed io library to the sandbox environment
41sandbox.io = io
42
43-- Load the script with the sandbox environment
44local user_script_fn, err = load(user_script, nil, "t", sandbox)
45
46if not user_script_fn then
47 error("Failed to load user script: " .. tostring(err))
48end
49
50-- Execute the user script within the sandbox
51local success, result = pcall(user_script_fn)
52
53if not success then
54 error("Error executing user script: " .. tostring(result))
55end