So I have been learning roblox lua for the past few days but the I, V or _, V confuses me as I don't know what situations to use it in or what it really does please help!
Basically, it's a better way of iterating through a table. To iterate through something is basically to run code for every object in the table.
So, for example, this is how you use ipairs:
local tab = {"a","b","c"} for i, v in ipairs(tab) do print(i, ": ", v) end
So, as you can see, you create a for loop by stating two loop variables (i
and v
), the keyword in
, and then you wrap the function ipairs
around the table you wish to loop over. Inside the loop, i
now represents your index (the position of the item in the table, which will be 1, 2, and 3 in that example), and v
is your value (the items themselves, which is "a"
, "b"
, and "c"
).
So, therefore, the output of the above will be:
1: a 2: b 3: c
the variable _
is just that, a variable, and can be used in place of either variable when making a for loop. It basically means that you don't want to use the variable in the code. It's purely for show.
There's another method like ipairs
called pairs
. It basically works like ipairs
, but you use it with tables that are maps instead of lists:
local tab = { a="x", b="y", c="z", } for i, v in pairs(tab) do print(i, ": ", v) end
This will print out:
a: x b: y c: z
Anatomy
tab = ["Lol","Lol2",'Lol3"] for i,v in pairs(tab) do print(i) print(v) end
Okay so for i,v in pairs() does is iterate thru a table
i is the number the iteration is on and the v is usually the thing that is in the spot that correlates to the number!
So if i was on 2 then v would be "Lol2"
for _,v in pairs() is exactly the same thing! _ is just used in case you don't want to use the number count but I would personally disregard it and use something you would remember because when you get into complex iterations example multidimensonal ones then you would usually use it!
Uses Say you want to change all the parts of a player into the color green, instead of going seperately and using about 20 lines you could do it in less than 5
for i,v in pairs(game.Players.LocalPlayer.Character:GetChildren()) do -- :GetChildren() returns a table version of the heiarchy sorta if v.ClassName == "Part" then -- v is what part is the iterator on right now this will skip anything thats not a part v.BrickColor = "Green" end end
Edit
pairs() is the same as ipairs() but pairs doesn't stop at a negative and ipairs breaks at a negative!
Most answers already given, can explain what each part does, but they don't show (in simple terms) what this is used for.
for number,object in pairs(game.Workspace:GetChildren()) do if object:IsA("Hat") then object:Destroy() end end
This code is the normal type of scripting you see used in games. Not an answer,but a demonstration to help you get to grips. :)