Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

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

Asked by
uhi_o 417 Moderation Voter
3 years ago
Edited 3 years 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

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

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

Have a great day everybody ;)

1 answer

Log in to vote
1
Answered by 3 years ago
Edited 3 years 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)
        end
    end)
end

You can use this example code to test it:

for i = 1, 5 do
    addUserId(Random.new():NextInteger(100000, 1000000))
end

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.

Ad

Answer this question