Log in to vote

How would I check when an array gets a value then wait and remove it?

Asked by
uhi_o 417 Moderation Voter
1 year ago
Edited 1 year ago

Hey guys,

I have a table in my script where it's a cooldown where every userId is placed in it. I want to detect when a value is added to it then wait a certain amount and then remove the user.

I know how to achieve that but my issue here is I only get to wait for the first value in the table.

Here is my attempted code.

local CooldownList = {}

--I insert values in the table elsewhere

    print("Running coroutine")
    while true do
        if #CooldownList >= 1 then
                    print("Waiting and trying to remove user from array")
                    table.remove(CooldownList, 1)
                    print("Successfully removed user from array")
                until #CooldownList < 1

Tbh, I just went with coroutines because I thought that was best.

Have a great day everybody ;)

1 answer

Log in to vote
Answered by 1 year ago
Edited 1 year ago

I think I understand what you're trying to do, but I think polling (using a coroutine enclosed in a while loop that constantly runs) is the wrong answer. Plus, you've got a coroutine inside of a coroutine; that can get messy!

You can either use metatables or a function-based approach, but the former is generally over-engineering. Opting for the latter choice, here's what I would do:

local userIds = {}

local function addUserId(id)
    table.insert(userIds, id) -- insert the id into the table
    print("Added", id, "to userIds.")
    delay(45, function() -- operate on a separate thread so this function does not yield any code it's used in
        local index = table.find(userIds, id) -- locate where our userId async is via table.find's return argument
        if index then -- ensure the index is legitimate
            table.remove(userIds, index) -- remove the userId from the index
            print("Removed", id, "from userIds index", index)

You can use this example code to test it:

for i = 1, 5 do
    addUserId(, 1000000))

I would stress you remove the prints after you can ensure it's working properly. Hope this helps out, and please mark this as a solution if it does!!! Happy scripting.


Answer this question