From 977610705ad4056d157f8a481ac0300ca7c5883a Mon Sep 17 00:00:00 2001 From: Artem Krasnoshchok <1o1n1e1u1p1@gmail.com> Date: Thu, 16 Jan 2025 12:06:35 +0200 Subject: [PATCH] New flow.until_all_messages (#20) * new flow.untill_all_messages * Adjusted the description --- examples/flow/flow.script | 14 ++++++++++++++ ludobits/m/flow.lua | 29 +++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/examples/flow/flow.script b/examples/flow/flow.script index a2781c5..2efc2cc 100644 --- a/examples/flow/flow.script +++ b/examples/flow/flow.script @@ -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") @@ -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 diff --git a/ludobits/m/flow.lua b/ludobits/m/flow.lua index a30c20d..04eba88 100644 --- a/ludobits/m/flow.lua +++ b/ludobits/m/flow.lua @@ -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)