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

Searching tables is broken? (for i = 1, #TABLE do)

Asked by 8 years ago

Ok, well, I am trying to do a command in table thing where when you chat, it checks to see if any of the commands in the commands table match the chat, but it doesn't even try searching the table, just breaks at that point.

local Commands = {
    Message         = {Text=Prefix.."sm",Module=IM.Message,HasRecipt=false,HasMessage=true},
}

Stuff later...

game.Players.PlayerAdded:connect(function(Player)
print("player")
    Player.Chatted:connect(function(Chat)
print("chat")
        for i = 1, #Commands do
print("checking")
        end
    end)
end)

Tried this too...

game.Players.PlayerAdded:connect(function(Player)
print("player")
    Player.Chatted:connect(function(Chat)
print("chat")
        for i,v in ipairs(Commands) do
print("checking")
        end
    end)
end)

It stops at "chat" and doesn't print "checking".

2 answers

Log in to vote
2
Answered by 8 years ago

You are using ipairs as an iterator. ipairs skips values in a table that have non-numerical indexes. ipairs also stops iterating when it reaches a value that is nil. In your table the index is Message which is not a numerical value.


In this example the value 90 is not printed because its index is non numerical.

for _,n in ipairs({bob = 90; 80}) do
    print(n)
end

The # operator operates similarly. The operator returns the amount of values with numerical indexes.

for i = 1, #Commands do
    print("checking")
end

Is actually

for i = 1, 0 do
    print("checking")
end

To fix this you can use the pairs iterator which will iterate over all indexes.

for i,v in pairs(Commands) do
    print("checking")
end
0
Thank you! It works now! TypicalModerator 110 — 8y
Ad
Log in to vote
0
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
8 years ago

Your Problem

If your table is set up as a dictionary, like you have, then the # operator will always return 0. Because this will return 0 then your for loop will iterate 0 times, and never run your code inside the for loop.



How to fix

There are two ways you can do this. One, you can make a function to iterate through the whole table, counting the index and make it return the count, then call this function.

local Commands = {
    Message = {
        Text = Prefix.."sm",
        Module = IM.Message,
        HasRecipt = false,
        HasMessage = true
    }
}

function num(tab)
    local n = 0
    for i,v in pairs(tab) do
        n = n + 1
    end
    return n
end

game.Players.PlayerAdded:connect(function(Player)
    Player.Chatted:connect(function(Chat)
        for i = 1, num(Commands) do
            print("checking")
        end
    end)
end)
0
I'll stick with the other answer, 99.9% easier. TypicalModerator 110 — 8y
0
It's ultimately the same exact thing but okay(: Goulstem 8144 — 8y

Answer this question