Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

How to iterate through a table properly?

Asked by
Radstar1 270 Moderation Voter
7 years ago
Edited 7 years ago

BackGround In my game I'm trying to loop through a table to check and see if the table's contents matches my player's value. If it matches the value, then it takes the correctly matched table item and puts whatever it is in the Player's Charcater.

Example:

1local Tab = {Water,Earth,Fire,Air}
2 
3if Player.Value == Tab then
4 Value = Tab
5 Value.Parent = Player.Character
6end

Question Is this the correct way to loop through it? I don't want to have to make anif statement checking if the value matches because then I would have to put it in manually.

2 answers

Log in to vote
5
Answered by 7 years ago
Edited 7 years ago

Here's how you iterate through a table quickly (there no 'proper' way in this situation):

1.

Here's the simplest way - but this only works on arrays (tables that only use numbers to index their values). Every iteration it adds 1 to i, which it then uses to get the value 'saved' to the number (this number is called the index). For example, using the table inside the below code, Value is saved to the number 1 and OtherValue is saved to the number 2.

1local Array = {Value,OtherValue}
2 
3for i = 1,#Array do
4    local Value = Array[i]
5    if Value == Player.Name then
6        -- do stuff
7    end
8end

2.

This is my preferred way - it also has many variations, but this is roughly how it works (and it does work for any type of table).

1local Table = {Value,OtherValue}
2 
3for Index,Value in pairs(Table) do
4    if Value == Player.Name then
5        -- do stuff
6    end
7end

3.

You can iterate through a table with the two other loops, also (while and repeat). Both of these loops only work with arrays in the way I coded them.

1local Array = {}
2local Index = 0
3 
4while Index < #Array do
5    Index = Index + 1
6    local Value = Array[Index]
7end
1local Array = {}
2local Index = 0
3 
4repeat
5    Index = Index + 1
6    local Value = Array[Index]
7until Index == #Array

Hope I helped!

~TDP

0
Thank you so much! Radstar1 270 — 7y
Ad
Log in to vote
0
Answered by
TrollD3 105
7 years ago
1local Tab = {Water,Earth,Fire,Air};
2 
3 
4for i,v in pairs (Tab) do --iterates through everything in the table (i is the key, v is the value inside)
5    if Player.Value == v then
6        Value.Value = v; --values have a .Value property so make sure you're setting the value
7        Value.Parent = Player.Character
8    end;
9end;

Answer this question