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

How to correctly use tables with "If"?

Asked by
Mokiros 135
9 years ago

So, i have a table with some string values:

table = {"Part","Brick","Something"}

And i have script which destroys anything it touches:

function destroy(WhoTouched)
    WhoTouched:Destroy()
end
script.Parent.Touched:connect(destroy)

But i need to check the name of the brick, and if name in the table, do not destroy that part:

for index,value in pairs(table) do
    if WhoTouched.Name ~= value then
        WhoTouched:Destroy()
    end
end

The problem is - if table contains more than one value, script destroys everything, even parts with names in the table. So how exactly do i check name?

1 answer

Log in to vote
3
Answered by 9 years ago

Instead of using a for loop use a trick some people use, a "map-style" table or a Dictionary.


Dictionary

It's an array where you can actually SET the index in the table.

table = {
["ROBLOX"] = "Multiplayer game",
["LordDragonZord"] = "Amazing",
["Scripting"] = "Cool"
}

print(table["ROBLOX"]) --Will print "Multiplayer game"


Final Product

safe = {
["Part"] = true,
["Brick"] = true,
["Something"] = true
}--You can fit this on one line, I just did this so it's easier to read.

script.Parent.Touched:connect(function(p)
    if not safe[p.Name] then
        p:Destroy()
    end
end)


Hope it helps!

Ad

Answer this question