Let's say, I have a table.
1 | local player 1 = { "username" , "username2" , "etc" } |
1 | Player.Name = = player 1 [ 1 ] or player 1 [ 2 ] or payer 1 [ 3 ] or player 1 [ 4 ] or player 1 [ 5 ] |
How could I let's say do
1 | Player.Name = = player 1 [ all ] |
instead of repeating player[1]/player[#] and so on?
I tried a for i,v; didn't work.
I tried doing
1 | for i = 1 , #player 1 do |
2 | print (player 1 [ i ] ) |
3 | end |
but it only goes through one player, then stops.
If you want to get all table values then use a for loop
1 | local table = { 1 , 3 , 4 , 5 , 6 , 5 , 56 , 7 , 7 } -- Can contain anything |
2 |
3 | for i,v in pairs (table) do |
4 | --[[ |
5 | do whatever you want |
6 | i = the place of the object being used. if i is 2 then it's meaning the 2nd element |
7 | v = is the element, like if it's dealing with the 2nd element of the table then v is 3 and i 2 |
8 | --]] |
9 | end |
Simple! You just use the pairs()
loop or ipairs()
loop.
There are two loops for doing this. Pairs
and ipairs
. The main difference is ipairs
will break if you have a nil value in the table.
1 | local Table 1 = { 1 , 2 , 3 , "NIL" , nil , 5 , 6 , 9 , "Randomstuff" } |
2 |
3 | for index, value in pairs (Table 1 ) do |
4 | print (value) -- This would output every value in the table |
5 | end |
6 |
7 | for index, value in ipairs (Table 1 ) do |
8 | print (value) -- This would output every value up to the nil value |
9 | end |
Thats how to loop around tables and what pairs
and ipairs
do.
Hope this helps!