示例工程 30-embedding-and-cpp

30-embedding-and-cpp/02-instruction-limit/main.lua

lua · 0.7 KB

-- @runtimes lua54 luajit
--- 演示:用 debug.sethook 限制执行时间(指令计数)。
local M = {}
 
local function spin()
	local total = 0
	for i = 1, 1e9 do
		total = total + i
	end
	return total
end
 
--- @return table { aborted = boolean, message = string }
function M.run(log)
	log = log or print
	local count = 0
	debug.sethook(function()
		count = count + 1
		if count > 100 then
			error("instruction limit exceeded", 0)
		end
	end, "", 1000)
	local ok, message = pcall(spin)
	debug.sethook()
	local aborted = not ok
	log(("aborted=%s message=%s"):format(tostring(aborted), tostring(message)))
	return { aborted = aborted, message = tostring(message) }
end
if not ... then
	M.run()
end
return M