协程是否适合这个功能?

我在编写一个用来在游戏中将物品移出和移入储存的脚本。我计划在运行脚本时允许物品队列,以防空间不足。我还计划允许多个队列同时存在(比如一个队列将物品移动到物品库存,另一个队列将物品移动到储存中)。

起初我认为我应该使用协程来实现这一点。第一个队列将一直运行直到物品的目的地(储存或库存)满了,然后会使用coroutine.yield来暂停并允许下一个队列运行。当空间空闲时,队列将重新启动。

threads = {}

local co = coroutine.create(function(list, target)
    --list:要移动的物品列表
    --target:目标物品库或储存(物品将移动到此处)
    while list.n > 0 do
        if target.count < target.max then
            move(list:last(), target)
        else
            coroutine.yield()
        end
    end
end)

threads:append(co)

-- 这段代码在检测到空闲空间时运行
for i = 1, #threads do
    local status = coroutine.resume(threads[i])
    if not status then
        threads:remove[i]
    end
end

然而,我意识到我不一定需要使用协程。

inventory_lists = {}
-- 要移动到库存的物品列表
storage_lists = {}
-- 要移动到储存中的物品列表

run_threads = function(list, target)
    while list.n > 0 and target.count < target.max do
        move(list:last(), target)
    end
end

-- 这段代码在检测到空闲空间时运行
for i = 1, #inventory_lists do
    run_threads(inventory_lists[i], inventory)
end
for i = 1, #storage_lists do
    run_threads(storage_lists[i], storage)
end

这些代码可以实现相同的功能,我并没有看到使用哪种更好的理由。由于这种情况似乎没有优势,所以我是否应该避免使用协程呢?

点赞
用户3610619
用户3610619

似乎这不是协程的合适使用方式,因为根本不需要使用它们:表格都是全局可用的,没有必要存储任何变量的状态,所有信息都是立即可用的(不需要阻塞)。我想这并不是错误的,因为它仍然可以运行,但这类似于做以下操作:

co = coroutine.wrap(function()
    print('Hello') coroutine.yield() print('World')
end)
co() co()

而你其实可以简单地打印出'Hello\nWorld'。

2016-02-12 19:36:54