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

What's the difference between pairs and ipars and how do they work?

Asked by 4 years ago

I keep seeing these in coding examples but they're not making any sense to me. Help?

0
This question has been asked about a thousand times. Please search for what you're asking before asking a question. DeceptiveCaster 3761 — 4y

1 answer

Log in to vote
3
Answered by
Elyzzia 1294 Moderation Voter
4 years ago
Edited 4 years ago

pairs will iterate through every value in a table that isn't nil (the indices here don't matter, i just chose them randomly)

local tbl = {
    ok = true;
    [1] = "test";
    [2] = "O_O";
    stupid = nil;
    [4] = "test test";
    dumb = false;
}
for i, v in pairs(tbl) do
    print(i, v)
end

if you run that code using pairs, this will be the output (or at least all of these values will be in the output)

-- ok true
-- 1 test
-- 2 O_O
-- 4 test test
-- dumb false

as you can see, it went through every value in the table, except for stupid, since it was nil

on the other hand, ipairs only iterates through numeric indices, and will stop if there isn't an index for the next number

if you ran the same code, but with ipairs instead of pairs, this would be the output

-- 1 test
-- 2 O_O

that's because ipairs only went through the indices that were numbers, and it didn't print index 4 because the table skipped index 3

Ad

Answer this question