How do I wait() until a table a table is empty?

I’m making an animated puzzle cube for my game and its animation uses a ton of tweens. A thing I need for this would be a way to know when all running tweens are done. So I made a do tween function that creates a runs a tween and adds it to a table called tweenQueue. When the tween is completed it removes it from the queue. I want something like:

wait(until the tweenQueue is empty)
print(“Next animation”)

ps also if you know a better way that would be great also!

1 Like
repeat task.wait() until #tables == 0
--Do code.

You can use the unary length operator, which is denoted by the “#” key to determine when a table is empty (has a length of 0).

3 Likes

You can use RBXScriptSignal:Wait and Tween.Completed to yield your program until your interpolations have been completed.

Since queues are in FIFO order, there is no need to concern yourself with what’s going on at the back of the line. You will keep your attention on the first element until there’s no Tween left to yield on:

local function waitForTweens(tweenQueue: {Tween})
    while true do
        local tween = table.remove(tweenQueue, 1)

        if not tween then
            break
        end

        if tween.PlaybackState == Enum.PlaybackState.Completed then
            continue
        end

        tween.Completed:Wait()
    end
end

This is ultimately better than busy-waiting.

4 Likes

Here is the solution I used:

--Will do wait() until all running tweens are completed
local function untilTweensCompleted()
	local index = 1
	while runningTweens[index] do
		if runningTweens[index].PlaybackState.Name == "Playing" then
			runningTweens[index].Completed:Wait()
		end
		index += 1
	end
	runningTweens = {}
end