Why is my table loop only getting the first index and then breaking?

Alright so, I’ve been working on a codes system for one of my games, its pretty much like any other codes system you’ve seen. It works properly until one part. The part that actually checks if the the player typed the correct code.

So what happens is, I can only redeem one code because for some reason only one index is left in the table. There are no table.remove()'s but for some reason it only prints 1 index.

here is the code;


                for codes, code in pairs(CodesConst.CODES) do
                        if CodeBox.Text == codes then
                            task.spawn(function()
                                RedeemSignal:Fire(codes, code, CodeBox, Player)
                                task.wait(3)
                                UI.codesframe:TweenPosition(UI.codesframe.Position + UDim2.new(0,0,2,0), Enum.EasingDirection.InOut, Enum.EasingStyle.Quart, 0.3)
                                task.wait(2)
                                UI:Destroy()
                            end)
                    elseif CodeBox.Text ~= codes then
                        FLICKERUI:FlickerUI(CodeBox, CodesConst.NO_CODE_ENTERED_COLOR, CodesConst.NORMAL_TEXT_COLOR, 0.2, 3, false)
                        CodeBox.Text = CodesConst.TEXT_FOR_WRONG_OR_NO_CODE
                         task.wait(2)
                         UI.codesframe:TweenPosition(UI.codesframe.Position + UDim2.new(0,0,2,0), Enum.EasingDirection.InOut, Enum.EasingStyle.Quart, 0.3)
                         task.wait(2)
                         UI:Destroy()
                end
            end 

Here is the table code

Const.CODES = {

    ['Christmas Madness V2'] = 500;

    ['BigFlair'] = 150;

    ['Sunshiner'] = 150;

    ['Calkuless'] = 150;

}

There is a better way of doing this. Instead of iterating over the entire codes table, you can instead index the table directly.

For example: (untested)

Const.CODES = {

    ['Christmas Madness V2'] = 500;

    ['BigFlair'] = 150;

    ['Sunshiner'] = 150;

    ['Calkuless'] = 150;

}

function CheckCode(code)
    if Const.CODES[code] ~= nil then -- checks if the table contains the code
        print("code exists!!!")
    else
        print("code does not exist!")
    end
end

CheckCode("BigFlair") -- should print "code exists!!!" (works)
CheckCode("BigFlair1") -- should print "code does not exist!" (doesn't work)

This is only an example, and you should port it to your current UI setup if you choose to try it.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.