Reputation: 73
I was writing a script to move items in and out of storage in a game. I'd planned to allow for item queues in the event that there was not sufficient free space when I ran the script. I'd also planned to allow for more than one queue to exist at a time (ex: a queue to move items into the inventory, and a second queue to move items into the storage).
I originally thought that I should use coroutines to achieve this. The first queue would run until the destination for items (storage or inventory) was full, then would pause using coroutine.yield and allow the next queue to run. The queues would be restarted when a free space opened up.
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
However, I realized that I didn't necessarily need to use coroutines.
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
These pieces of code accomplish the same thing, and I don't see any reason to use one over the other. Should I avoid using coroutines in this case, since there doesn't seem to be an advantage?
Upvotes: 1
Views: 194
Reputation: 73
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'.
Upvotes: 2