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

Functions with tables?

Asked by 9 years ago

I was wondering how I could know if something is in a table, like:

List = {"Blah" , "Bloop" , "BSI"}
if List:FindFirstChild("Blah") then
--do whatever
end
0
What did I do to deserve a vote down? BSIncorporated 640 — 9y

2 answers

Log in to vote
2
Answered by 9 years ago

You can use a for loop to iterate throughout the table.

function InTable(Tab,Value)
    for _,n in pairs(Tab) do
        if n == Value then
            return true
        end
    end
end

List = {"Blah" , "Bloop" , "BSI"}

if InTable(List,"Blah") then
    --Stuff
end

You could place the function inside the table to use it as a method:

List = {"Blah" , "Bloop" , "BSI"}

function List:Find(Value)
    for _,n in pairs(List) do
        if n == Value then
            return true
        end
    end
end

if List:Find("Blah") then
    --Stuff
end

If you wanted a generic function you could place into any table you could use metatables.(Without having to modify the function)

local FindMeta = {
    __index = function(self,key)
        if key == "Find" then
            return function(Value)
                for _,n in pairs(self) do
                    if Value ==n then
                        return true
                    end
                end
            end
        end
    end
}
List = {"Blah" , "Bloop" , "BSI"}
setmetatable(List,FindMeta)
List2 = {"Blah" , "Bloop" , "BSI"}
setmetatable(List2,FindMeta)

if List.Find("Blah") and List2.Find("Bloop") then
    --Stuff
end
0
Should MetaTables have List:Find or List.Find? I thougt List.Find() tends not to accept parmaters. RM0d 305 — 9y
0
@RM0d: List:Find() just means "List.Find(List)". Thus, on line 19, it should be either 'List.Find(List, "Blah")' or 'List:Find("Blah")' chess123mate 5873 — 9y
Ad
Log in to vote
0
Answered by 9 years ago

It is generally more efficient to use dictionaries instead of repeatedly searching through a list. If you start with a list, you can convert it into a dictionary (though you only save time if you save the Dictionary for use later instead of recreating it every time you want to use it)

List = {"Blah" , "Bloop" , "BSI"}
Dictionary = {}
--Convert List to Dictionary
for i = 1, #List do
    Dictionary[List[i]] = true
end
--Use Dictionary instead of List from now on.
--To add: Dictionary["newItem"] = true
--To remove: Dictionary["itemToRemove"] = nil
if Dictionary["Blah"] then
    --do whatever
end
--To go over the list:
for k,v in pairs(Dictionary) do
    --'k' is the variable of interest (ex it will contain "Blah", "Bloop", etc), 'v' will just hold 'true'
end

Answer this question