Resource Limits and Instrumentation
Use debug.sethook to count instructions and enforce CPU budgets.
Why Resource Limits?
Untrusted code can cause DoS by running forever (CPU), allocating huge amounts of memory, or generating excessive output. Resource limits protect the host.
CPU Limit via debug.sethook
Count executed instructions and abort when the limit is exceeded.
local function withCPULimit(fn, maxOps)
local ops = 0
debug.sethook(function()
ops = ops + 1
if ops > maxOps then error("CPU limit exceeded", 2) end
end, "", 50) -- check every 50 instructions
local ok, result = pcall(fn)
debug.sethook()
return ok, result
endAll lessons in this course
- The _ENV Model in Lua 5.2+
- Building a Restricted Sandbox
- Preventing Sandbox Escapes
- Resource Limits and Instrumentation