【问题标题】:Is this an inappropriate use for coroutines?这是对协程的不恰当使用吗?
【发布时间】:2016-02-12 03:48:51
【问题描述】:

我正在编写一个脚本来在游戏中将物品移入和移出存储。如果我运行脚本时没有足够的可用空间,我计划允许项目队列。我还计划一次允许存在多个队列(例如:将物品移入库存的队列,以及将物品移入存储的第二个队列)。

我原本以为我应该使用协程来实现这一点。第一个队列将一直运行,直到项目(存储或库存)的目的地已满,然后将使用 coroutine.yield 暂停并允许下一个队列运行。当空闲空间打开时,队列将重新启动。

threads = {}

local co = coroutine.create(function(list, target) 
    --list: a list of items to be moved
    --target: inventory or storage (where the item is to be moved)
    while list.n > 0 do
        if target.count < target.max then
            move(list:last(), target)
        else
            coroutine.yield()
        end
    end
end)

threads:append(co)

-- this code would run when free spaces were detected
for i = 1, #threads do
    local status = coroutine.resume(threads[i])
    if not status then
        threads:remove[i]
    end
end

但是,我意识到我不一定需要使用协程。

inventory_lists = {}
-- lists of items to be moved to the inventory
storage_lists = {}
-- lists of items to be moved to the storage

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

-- this code would run when free spaces were detected
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

这些代码完成了同样的事情,我看不出有任何理由使用其中一个。在这种情况下我是否应该避免使用协程,因为似乎没有优势?

【问题讨论】:

  • 我没有看到在第二种情况下完成线程后删除线程的部分。
  • 你说得对,需要添加。可能还有其他错误,因为我快速写了它以提供示例。
  • 为什么不将它们存储在主“队列”表的子表中,然后遍历它们,循环每一个。为什么这需要协程?

标签: lua coroutine


【解决方案1】:

这似乎是对协程的不恰当使用,因为根本不需要使用它们:表都是全局可用的,不需要存储任何变量的状态,所有信息都可以立即使用(没有什么需要阻止)。 我想从它仍然运行的意义上说它不是不正确的,但它类似于做

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

当您可以简单地打印“Hello\nWorld”时。

【讨论】:

    猜你喜欢
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    相关资源
    最近更新 更多