Feche1320 Posted May 27, 2011 Share Posted May 27, 2011 When and where should I use 'pairs' or 'ipairs'? For example: local table = { "hello", "i", "am", "here", "not" } for i, tmp in ipairs(table) do outputChatBox(tmp) end local table = { "hello", "i", "am", "here", "not" } for i, tmp in pairs(table) do outputChatBox(tmp) end Will print the same: 'hello i am here not' So.. differences? Thanks Link to comment
DakiLLa Posted May 27, 2011 Share Posted May 27, 2011 ipairs is used to go through a table with integer indexes; pairs to go through string indexes. local t = { "hello", "i", "am" } for i, v in ipairs( t ) do print( v ); end -- I am local t = { ["hello"] = "I am", ["hello_again"] = "not here" } --local t = { hello = "I am", hello_again = "not here" } is equivalent of the previous line for i, v in pairs( t ) do print( v ); end -- I am not here By the way, you can't use pairs and ipairs to loop through tables with mixed types of indexes. Link to comment
proracer Posted May 27, 2011 Share Posted May 27, 2011 ipairs can be used to go trough string indexes also if I'm not wrong... Link to comment
Aibo Posted May 27, 2011 Share Posted May 27, 2011 ipairs will iterate the table by numeric index order starting from 1 and until next numeric key is not found, like: table = { "one", "two", "three", four = "four", five = "five", [5] = "five", six = "six" } ipairs(test) will stop after table[3] because table[4] is nil. and it will not find test[5], because [4] is missing. and pairs will output everything with any kind of index, be it number, string or MTA element. Link to comment
proracer Posted May 27, 2011 Share Posted May 27, 2011 Also I sometimes don't understand this, I saw many people use ipairs and with your example I think pairs is the best way. What is the reason? Link to comment
karlis Posted May 27, 2011 Share Posted May 27, 2011 ipairs is basically used where order is needed, while pairs iterates tru table completely random, thus making it a good random generator too. Link to comment
Discord Moderators Zango Posted May 27, 2011 Discord Moderators Share Posted May 27, 2011 pairs versus ipairs on numerically indexed tables is significantly slower. Link to comment
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now