Lua

Lesson 07

Sandboxed execution

Limit the environment for dynamic Lua chunks so scripts can use approved helpers without reaching host globals.

Good Code

src/rule_sandbox.lua
local function compile_rule(source)
  local env = {
    tonumber = tonumber,
    math = { min = math.min, max = math.max },
  }

  -- The chunk sees only the helpers copied into env.
  return load(source, "review_rule", "t", env)
end

Bad Code

rule_sandbox.lua
local function compile_rule(source)
  -- The chunk can read and change the host global environment.
  return load(source)
end

Review Notes

What to review

Good Code

The good version gives the loaded chunk a small environment with only approved helpers. The script cannot reach unrelated globals by default.

Bad Code

The bad version loads code into the default environment. A rule script can access global functions or mutate state the host never intended to expose.

Takeaways

  • Dynamic Lua execution should run with a small explicit environment instead of the full global table.