For iterative table , like {thing1,thing2} i know how it work and why ipairs is way better but i don’t get how pairs work the only way i can think about it , is that pairs search for every index combinaison but this would require a insane amount of iteration and would be way too laggy so i wonder if anybody know how it really work
Honestly, I don’t understand the difference. I was taught to use pairs
but I’d like to know how ipairs
and pairs
differ as well.
pairs basically loops through a table, ipairs does the same purpose of pairs but does it in order and is faster but slower in vanilla Lua.
ipairs can only be use on list like {thing1,thing2} and not dictionary {thing1 = thing1b,thing2 = thing2b} because the i of ipairs is for index , it work with a code like that :
local i = 1
while table[i] do
--Action
i+=1
end
So it require a continue index but it’s way faster
Okay, but why is it faster ?
Idk lol. Maybe because it runs an iterator? Idk.
Yeah but the question was how it can loop through a dictionary
I’m not exactly sure how it works. Maybe it keeps a list of the keys in a table and iterates through that, accessing the value in the dictionary every time it gets another key? I don’t really know .
Interesting , so that would explain why lua start index to 1 since 0 is reserve to key list to do something like that
for i,v in ipairs(table[0]) do
yield v,table[v]
end
(i use yield as in python , a return that don’t stop the program idk if this work in lua)
I think ipairs
is faster because the programs only understand numbers, and since pairs
can use keys with letters, it must transform the other characters to numbers, it takes slightly a little longer for the conversion.
PS: this post should be in #help-and-feedback:scripting-support
Smart, because computers are good at numbers while pairs can also be used in string dictionaries.
This page should be a good way to see how ipairs and pairs works internally.
https://www.lua.org/pil/7.3.html
From what I see, ipairs is a simple loop that keeps adding and indexing, until the returned value becomes nil.
Now with pairs it does the same but instead of doing i += 1
it does i = next(t, i)
.
Next is a built in function that returns the next index and value in a dictionary.
next(t)
on its own would return the first index in the dictionary, and then you use that one as the i
arguement again.
for i,v in next, {['key'] = 'value'} == for i, v in pairs({['key'] = 'value'}