示例工程 35-plugin-system
35-plugin-system/03-timeout-hook/main.lua
-- @runtimes lua54 luajit
--- 演示:插件执行超时(指令计数)。
local M = {}
local function run_with_limit(source, limit)
local env = {}
local chunk = assert(load(source, "=plugin", "t", env))
local count = 0
debug.sethook(function()
count = count + 1
if count > limit then
error("plugin timeout", 0)
end
end, "", 1000)
local ok, err = pcall(chunk)
debug.sethook()
return ok, err
end
--- @return table { ok = boolean, message = string }
function M.run(log)
log = log or print
local ok, err = run_with_limit("local x = 0 for i = 1, 1e9 do x = x + i end", 50)
log(("ok=%s message=%s"):format(tostring(ok), tostring(err)))
return { ok = ok, message = tostring(err) }
end
if not ... then
M.run()
end
return M