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

How to check if the value is already in table?

Asked by
Yuuwa0519 197
5 years ago

I have a script where it adds the name of player when it touches the part, but right now it keeps on adding multiple times(every bodypart that touches), and when i touch again it adds additional same person. To prevent that, i want to make a function where it checks if the value already exists so it wont spam the username in table.

Ex.

 myTable = {}

local part = script.Parent

part.Touched:Connect(function(registeredTeleport)
    if registeredTeleport.Parent:FindFirstChild("Humanoid") then
        if registeredTeleport.Parent.Name --[already exists--] then
            table.remove(myTable,registeredTeleport.Parent.Name(the one inside table))
        elseif registeredTeleport.Parent.Name ~= --[already exist--] then
            table.insert(myTable,registeredTeleport.Parent.Name)
        end
    end
end)


wait(10)
table.sort(myTable)

repeat 
    local temporaryName = myTable[1]:FindFindFirstChild("Head")
    if temporaryName == ~~~~"Head" and temporaryName:FindFirstAncestorOfClass("Model") then
        temporaryName.Cframe = Cframe.new(X,Y,Z)    
    end 
    table.remove(myTable,[1]
until
    #myTable == 0
end

1 answer

Log in to vote
1
Answered by 5 years ago

There is two ways I can think of.

1. Linear Search

A linear search is a searching algorithm that searches for an element in a list.

lua local function tableContains(tbl, element) for _, v in ipairs(tbl) do if (rawequal(v, element)) then return true; end end return false; end

This function returns true if the table contains element, checking each element in tbl one by one.

2. Dictionaries

Table have an array part and a dictionary part. The dictionary part is an unordered mapping of keys to values.

It looks more or so like this:

lua { key = "value", key2 = "value2" -- and so on }

So you can use the name of the player as the key, and use true as the value, just to show that they are in the table. Also duplicates will not be an issue.

lua myTable[player.Name] = true

0
the dictionary way worked out. Thank you for help :D Yuuwa0519 197 — 5y
Ad

Answer this question