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
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
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
Should MetaTables have List:Find or List.Find? I thougt List.Find() tends not to accept parmaters.
@RM0d: List:Find() just means "List.Find(List)". Thus, on line 19, it should be either 'List.Find(List, "Blah")' or 'List:Find("Blah")'
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
This discussion is preserved as it was. New answers, comments, and votes are closed.
1 comment
What did I do to deserve a vote down?