Skip to content

Commit

Permalink
New flow.until_all_messages (#20)
Browse files Browse the repository at this point in the history
* new flow.untill_all_messages

* Adjusted the description
  • Loading branch information
Artem-Krasnoschok authored Jan 16, 2025
1 parent fdf5e69 commit 9776107
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
14 changes: 14 additions & 0 deletions examples/flow/flow.script
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ function init(self)
msg.post("#", "abc")
flow.delay(0.2)
msg.post("#", "booo")

flow.delay(0.2)
msg.post("#", "msg3")
flow.delay(0.2)
msg.post("#", "msg1")
flow.delay(0.2)
msg.post("#", "msg2")
end, { parallel = true })

print("This flow will continue to run without waiting for the parallel flow to finish")
Expand All @@ -68,6 +75,13 @@ function init(self)
-- wait for a specific message (the message will be posted by the parallel flow created above)
local message_id, message, sender = flow.until_message(hash("booo"))
print("flow.until_message()", message_id, message, sender)

-- wait for all specific messages
print("Waiting for all specified messages...")
flow(function()
local last_message_id, last_message, last_sender = flow.until_all_messages(hash("msg1"), hash("msg2"), hash("msg3"))
print("flow.until_all_messages()", last_message_id, last_message, last_sender)
end)

-- wait until a callback is invoked
-- in this case we make a http.request call and wait for the callback
Expand Down
29 changes: 29 additions & 0 deletions ludobits/m/flow.lua
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,35 @@ function M.until_message(...)
return coroutine.yield()
end

--- Waiting to receive all specific messages.
-- @param message_1 Message to wait for
-- @param message_2 Message to wait for
-- @param message_n Message to wait for
-- @return message_id id of the last message
-- @return message message of the last message
-- @return sender sender of the last message
function M.until_all_messages(...)
local message_ids_to_wait_for = ensure_hashes({ ... })
local instance = create_or_get(coroutine.running())
instance.state = WAITING
instance.on_message = function(message_id, message, sender)
for i, message_id_to_wait_for in pairs(message_ids_to_wait_for) do
if message_id == message_id_to_wait_for then
table.remove(message_ids_to_wait_for, i)
break
end
end

if #message_ids_to_wait_for == 0 then
instance.result = table_pack(message_id, message, sender)
instance.on_message = nil
instance.state = READY
resume(instance)
end
end
return coroutine.yield()
end


--- Wait until input action with pressed state
-- @param action_1 Action to wait for (nil for any action)
Expand Down

0 comments on commit 9776107

Please sign in to comment.