I Apologize if this Question has been already asked, But This would DEEPLY Help me in my Study. What are the Differences Between Pairs,iPairs, and Next? I've seen these three written with a in as the Beginning. like:
- in pairs
- in ipairs
- in next
I Apologize if this Question has been already asked, But This would DEEPLY Help me in my Study. What are the Differences Between Pairs,iPairs, and Next? I've seen these three written with a in as the Beginning. like:
They are all iterator functions, used in generic for loops.
ipairs iterates through the integer keys of a Table, starting at 1 and stopping when the next consecutive integer key has a value of nil:
local t = {"gradea", 245, false}
t[6] = "This string won't be reached"
for key, value in ipairs(t) do
print(key)
print(value)
end
pairs and next are, effectively, the exact same thing. next is faster, slightly, since pairs uses next internally. They iterate through all members of a Table, but in an undetermined order (between server instances, that is):
local privateKey = {}
local t = {someStringKey = false, [24] = 16, [privateKey] = "swaggy", 1325, false, "anchored"}
for key, value in pairs(t) do
print(key)
print(value)
end
--This is, basically, the same as:
for key, value in next, t do
print(key)
print(value)
end
These iterators work with Tables. I used 'random' data in my Tables, so sorry if that confused you.
ipairs works, effectively, like this:
local index = 1 --index is another word for 'key'.
local t = {"gradea", 245, false}
t[6] = "This string won't be reached"
while t[index] ~= nil do --~= nil is necessary here because values of `false` are important. `(false ~= nil) == true` Only `nil` Values stop the loop.
print(t[index])
index = index + 1
end
That while loop will print the values of t using only consecutive integer keys, starting at 1.
In my Table t, keys 1, 2, 3, and 6 have defined values, so the while loop (and thus, ipairs), will print the values at t[1], t[2], and t[3] and then stop because t[4] == nil.
This discussion is preserved as it was. New answers, comments, and votes are closed.
3 comments
so ipairs works more with the Strings?
I think he means that ipairs goes through the loop until there is a predefined variable that takes place of the key that is not a integer/number. Though I could be wrong.
Sorta. I'll add some pseudocode for ipairs for further explanation.