Good Code
The good version gives the loaded chunk a small environment with only approved helpers. The script cannot reach unrelated globals by default.
Lesson 07
Limit the environment for dynamic Lua chunks so scripts can use approved helpers without reaching host globals.
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)
endlocal function compile_rule(source)
-- The chunk can read and change the host global environment.
return load(source)
endThe good version gives the loaded chunk a small environment with only approved helpers. The script cannot reach unrelated globals by default.
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.