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:

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

And i have script which destroys anything it touches:

1function destroy(WhoTouched)
2    WhoTouched:Destroy()
3end
4script.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:

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

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.

1table = {
2["ROBLOX"] = "Multiplayer game",
3["LordDragonZord"] = "Amazing",
4["Scripting"] = "Cool"
5}
6 
7print(table["ROBLOX"]) --Will print "Multiplayer game"


Final Product

01safe = {
02["Part"] = true,
03["Brick"] = true,
04["Something"] = true
05}--You can fit this on one line, I just did this so it's easier to read.
06 
07script.Parent.Touched:connect(function(p)
08    if not safe[p.Name] then
09        p:Destroy()
10    end
11end)


Hope it helps!

Ad

Answer this question