Jump to content

How to loop this table


Hero192

Recommended Posts

Example

local ranks = { 
  ["Fireman"] = { 
  {"Level1", 1}, 
  {"Level2", 2}, 
  {"Level3", 3}, 
  {"Level4", 4} 
  } 
} 
  
function rankSet() 
     for _, v in ipairs (ranks) do 
         --code what you want 
     end 
end 

Edited by Guest
Link to comment

@-Doc- Absolutely wrong.

The index is a string, not integer, ipairs won't work.

The best way to handle this is:

local ranks = { 
  ["Fireman"] = { 
  {"Level1", 1}, 
  {"Level2", 2}, 
  {"Level3", 3}, 
  {"Level4", 4} 
  } 
} 
  
function rankSet() 
     for faction, array in pairs ( ranks ) do      -- index is string, so for i=1, #ranks or ipairs won't work here 
          -- faction is "Fireman" here --- 
          for i=1, #array do        -- that's way faster than ipairs 
               -- array[i][1] is "Level1", array[i][2] is 1 in the first loop -- 
          end 
     end 
end 

The difference between ipairs and for i=1, #array are:

ipairs is slow and stops when the index isnt going from i=1 to n without space like:

"1, 2, 3, 5, 6, 7, 8"

ipairs will stop at 3.

for i=1, #array is faster, but doesnt stop.

"1, 2, 3, 5, 6, 7, 8"

It will give out an error because there is no array[4].

But you can handle it by asking:

if array[i] then 

and it's still faster than ipairs.

Some guys use ipairs with getElementsByType:

DON'T DO THAT

Thats stupid, it's slow and useless.

Use that:

local players = getElementsByType ( "player" ) 
for i=1, #players do 
     -- players[i] is the player 
end 

That's faster

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...