tibaiwan1888 发表于 2026-6-4 23:59:30

用协程实现非阻塞任务队列——告别定时器嵌套地狱

-- TaskQueue.lua
-- 用协程模拟异步序列,避免多层定时器嵌套导致代码难以维护

local TaskQueue = {}
TaskQueue.__index = TaskQueue

function TaskQueue.new()
    return setmetatable({ _queue = {} }, TaskQueue)
end

-- 添加一个延迟任务(delay单位:秒)
function TaskQueue:wait(delay, fn)
    table.insert(self._queue, { delay = delay, fn = fn })return self
end

-- 执行队列(依赖引擎的 SetTimer 或等效接口)
function TaskQueue:run()
    local elapsed = 0
    for _, task in ipairs(self._queue) do
      elapsed = elapsed + task.delay
      local capturedFn = task.fn
      SetTimer(elapsed * 1000, function()
            local ok, err = pcall(capturedFn)
            if not ok then print(" 执行错误: " .. tostring(err)) end
      end)
    end
end

return TaskQueue



实例:

local TaskQueue = require("TaskQueue")

TaskQueue.new():wait(0,function() BroadcastMap("传送门开启……") end)
    :wait(2,function() PlayEffect("portal_open") end)
    :wait(3,function() BroadcastMap("BOSS即将降临!") end)
    :wait(2,function() SpawnMonster("暗影魔王", 100, 200) end)
    :wait(1,function() BroadcastMap("战斗开始!") end)
    :run()

qq154886255 发表于 2026-6-5 23:10:19

很厉害啊!学到了

jz9005 发表于 2026-6-6 00:35:05

快了快了,马上就能用VV了
页: [1]
查看完整版本: 用协程实现非阻塞任务队列——告别定时器嵌套地狱