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:
local Tab = {Water,Earth,Fire,Air} if Player.Value == Tab then Value = Tab Value.Parent = Player.Character end
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.
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.
local Array = {Value,OtherValue} for i = 1,#Array do local Value = Array[i] if Value == Player.Name then -- do stuff end end
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).
local Table = {Value,OtherValue} for Index,Value in pairs(Table) do if Value == Player.Name then -- do stuff end end
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.
local Array = {} local Index = 0 while Index < #Array do Index = Index + 1 local Value = Array[Index] end
local Array = {} local Index = 0 repeat Index = Index + 1 local Value = Array[Index] until Index == #Array
Hope I helped!
~TDP
local Tab = {Water,Earth,Fire,Air}; for i,v in pairs (Tab) do --iterates through everything in the table (i is the key, v is the value inside) if Player.Value == v then Value.Value = v; --values have a .Value property so make sure you're setting the value Value.Parent = Player.Character end; end;