Jump to content

ipairs and pairs


mjau

Recommended Posts

use ipairs when you have an indexed table like this:

local ourTable = {} 
ourTable[1] = 3 
ourTable[2] = "helloworld" 
ourTable[3] = "another" 

and pairs when your table looks like this:

local ourTable = {} 
ourTable["helloworld"] = "this is an example" 
ourTable[2] = 3.14 
ourTable[localPlayer] = 22 

you can use pairs on the first example too, but its not sure if it will start on ourTable[1] and end on ourTable[3].

Link to comment
Can someone tell me whats the diffference with pairs and ipairs and which can be used where ?

ipairs loop only number indexes ( start from 1 index ) and only in order.

pairs loop all.

Examples (ipairs)

  
-- Example 1 
for n, s in ipairs{ 'new', 'next' } do -- { [1] = 'new', [2] = 'next' } is some 
    print( n, s ) 
end 
  
--[[ 
1 new 
2 next 
]] 
  
-- Example 2  
for n, s in ipairs{ [1] = 'new', [3] = 'next' } do 
    print( n, s ) 
end 
  
--[[ 
1 new 
]] 
  
-- Example 3 
for n, s in ipairs{ [0] = 'new', [1] = 'next' } do 
    print( n, s ) 
end 
  
--[[ 
1 new 
]] 
  

Link to comment

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...