Skip to content

Lesson 6 of 9 · 26m

Sandboxing and Performance: Letting Scripts Run Without Owning You

How to restrict libraries, isolate environments, bound execution, and measure Lua hot paths before they become frame spikes or request latency.

The dangerous sentence in Lua embedding is 'we control the scripts, so sandboxing can wait.' Then a content author copies an example from a forum, a customer uploads a plugin, or a compromised feed writes automation logic. Sandboxing is not just security; it is how you keep one bad script from turning into a host outage.

Restrict the environment, not just the interpreter

Before loading user code, decide which globals exist:

local env = { print = print, math = math, string = string, table = table, world = host_world_api }
local chunk, err = load(user_source, "user-script", "t", env)
if not chunk then report_compile_error(err) return end

This pattern depends on Lua version. In 5.1, environments use setfenv; in 5.2+, load accepts the environment directly. In both cases, the principle is the same: scripts receive a capability table, not the real global namespace.

Dangerous or usually unnecessary surface includes:

  • os.execute, os.exit, os.remove, io.open, and io.popen
  • require, unrestricted load/loadstring, and bytecode loading

Infinite loops are not a syntax error

Lua cannot interrupt a running function from another thread safely. The standard tool is an instruction-count hook:

static void quota_hook(lua_State *L, lua_Debug *ar) {
  long *budget = lua_touserdata(L, lua_upvalueindex(1));
  if (--*budget <= 0) {
    luaL_error(L, "script instruction quota exceeded");
  }
}

lua_sethook(L, quota_hook, LUA_MASKCOUNT, 1000);

Instruction counts are approximate fairness, not real time. A single host binding can still sleep, allocate, scan a huge table, or call expensive engine code. Put limits around dangerous host functions too.

Memory pressure is part of the sandbox

Tables grow silently. A script can exhaust memory with a loop appending strings. Use a custom allocator when hard caps matter, or isolate scripts into processes when a hard operating-system boundary is required. Lua's garbage collector is incremental but tunable:

collectgarbage("setpause", 110)
collectgarbage("setstepmul", 200)

Tuning without measuring is superstition. Capture allocation counts, GC time, and script execution time per owner.

Performance rules that survive contact

  • Keep hot loops inside host/native code.
  • Cross the boundary less often: batch operations instead of one C call per entity per frame.
  • Cache Lua functions in the registry rather than performing global lookups every tick.
  • Prefer plain arrays and local variables in hot script code; measure with representative scripts, not allocation-free microbenchmarks.

Field notes

  • Whitelisting beats blacklisting. If you start with everything and remove dangerous pieces, you will miss one.
  • Coroutines do not provide CPU isolation; a yielded loop still consumes its entire slice when resumed.
  • Disable bytecode input for untrusted scripts unless you understand the verifier and version-specific risks.
  • A script sandbox inside the host process is not a security boundary against native-code exploitation. Use process isolation when the threat model requires it.

Was this lesson helpful?

Sign in to rate