我正在编写一个脚本,用于在游戏中将项目移入和移出存储空间。我计划在运行脚本时没有足够的可用空间的情况下允许项目队列。我还计划允许一次存在多个队列(例如:将项目移动到库存中的队列,以及将项目移动到存储中的第二个队列)。
我原本以为我应该使用协程来实现这一点。第一个队列将一直运行,直到项目(存储或库存)的目标已满,然后将使用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
这些代码完成了同样的事情,我没有看到任何理由使用其中一个。在这种情况下我应该避免使用协程,因为似乎没有优势吗?
答案 0 :(得分:2)
It seems this is an inappropriate use for coroutines as there simply isn't any need to use them: the tables are all available globally, there's no need to store the state of any variables, and all of the information is immediately available (nothing needs to block). I suppose it's not incorrect in the sense that it still runs, but it's similar to doing
co = coroutine.wrap(function()
print('Hello') coroutine.yield() print('World')
end)
co() co()
When you could simply print 'Hello\nWorld'.