local test = {
["One"] = game.Workspace.Platform_1,
["Two"] = game.Workspace.Platform_2,
["Three"] = game.Workspace.Platform_3,
["Four"] = game.Workspace.Platform_4
}
for i, CollidedPart in pairs(test) do
CollidedPart.Touched:Connect(function(TouchedPart)
print(CollidedPart.Name .. " Touched " .. TouchedPart.Name)
end)
end
I have a table and a loop that looks for parts that collided with stored parts in the table. My main question is how I could store the part that collided with the parts in the table.
Insert the part into the table using: table.insert(table, part) (the index will automatically turn into a number using this)
Code
local test = {
[1] = game.Workspace.Platform_1,
[2] = game.Workspace.Platform_2,
[3] = game.Workspace.Platform_3,
[4] = game.Workspace.Platform_4
}
for i, CollidedPart in pairs(test) do
CollidedPart.Touched:Connect(function(TouchedPart)
print(CollidedPart.Name .. " Touched " .. TouchedPart.Name)
if not table.find(test, TouchedPart) then
table.insert(test, TouchedPart)
end
end)
end
(this code can only supports number index)
You can also place the part in a custom index (number or string): table["Part_1"] = part
Code
local test = {
["Part_1"] = game.Workspace.Platform_1,
["Part_2"] = game.Workspace.Platform_2,
["Part_3"] = game.Workspace.Platform_3,
["Part_4"] = game.Workspace.Platform_4
}
local function dictionaryLength(dictionary)
local length = 0
for i,v in pairs(dictionary) do
length += 1
end
return length
end
local function dictionaryFind(dictionary, value)
for i,v in pairs(dictionary) do
if v == value then
return true
end
end
end
for i, CollidedPart in pairs(test) do
CollidedPart.Touched:Connect(function(TouchedPart)
print(CollidedPart.Name .. " Touched " .. TouchedPart.Name)
local testLength = dictionaryLength(test)
local customIndex = ("Part_%s"):format(testLength + 1)
if test[customIndex] == nil then
test[customIndex] = TouchedPart
end
end)
end
Tables are both Arrays and Dictionaries, they can hold multiple datatypes.
They have an “index” and a “value”, when you do something like: table[index] it’ll give you the value of that index.
Arrays have ordered indexes starting from 1 to how ever many are added, in arrays you do not give the index; instead it gives the index itself.
An array will look like:
local Array = {3, 2, 1}
Loop through this and you’ll see how they’re ordered:
for index, value in pairs(Array) do
print(string.format("%d | %d", index, value))
end
--[[
1 | 3
2 | 2
3 | 1
]]
In Dictionaries you give the index, they’re not ordered.
A Dictionary will look like: