Hello developers! So am doing a test for the “for i , v in pairs” I want to ask if there is v functions and events! Thank you.
You mean:
local table1 = {workspace.Part, workspace.Part2, workspace.Part3}
for i, v in pairs(table1) do
v.Touched:Connect(function()
print("One of the 3 parts were touched")
end
end)
if so, yes.
There are, v is basically a children of a model or folder, etc. All functions can be applicable to v.
so what does the letter i do if v does that ?
The letter i is the index, basically it is the position number of the instance it is looping through in the table or parent.
(probably like that, anyone else correct me if I am wrong, but by my experience that’s what I understood.)
i is the index position of the array the loop is at.
v is the value of the index position of the array the loop is at.
Example:
local tbl = {"a string!","hi","i'm also a string","epic!"}
--[[
the beginning index of the table starts at the first value
which in this case is "a string!"
]]
for i,v in pairs(tbl) do
print(i,v)
end
Output:
1 a string!
2 hi
3 i'm also a string
4 epic!
You can also manually assign tables a custom index by doing this.
local custom_indexed_table = {
[5] = true,
[21] = false,
["a part"] = workspace.Part,
[workspace.AnotherPart.Name] = workspace.SomeOtherPart
}
A generic for loop consists of this:
for ... in f do
end
f is the function that takes the table, ... are the variables that the iterator function returns every iteration. Roblox provides the functions pairs and ipairs. pairs (or the function it returns) iterates through the table in an arbitrary order, ipairs iterates through an array in order and stops when nil is encountered.
They return the index and the value every iteration.
--this is the same as {"hello","test",true,1,"jdha"}, it is called an array
local t1 = {
[1] = "hello",
[2] = "test",
[3] = true,
[4] = 1,
[5] = "jdhaadfwf"
}
--dictionary
local t2 = {
["Hey"] = "gsadga",
[5] = false,
[workspace.Camera] = 1
}
for index, value in ipairs(t1) do
print(index, value)
end
for index, value in pairs(t2) do
print(index, value)
end
Instead of using pairs and ipairs you can also make your own functions.