I keep seeing these in coding examples but they're not making any sense to me. Help?
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