I have an empty table, and my script adds in a string every time I press a button. How would I go about counting the amount of times a particular string appears in the table?
Getting the number of occurrences of a string in a table?
2 answers
One way of doing this would be the __newindex metamethod
__NewIndex
the new index metamethod fires when a script attempts to assign a new index of the table to a value. An example of something that would fire the metamethod would be:
local meta = {
__newindex = function(self,key,value)
print("attempted to index: "..key.." as value: "..value)
end
}
local tbl = {}
setmetatable(tbl,meta)
tbl[3] = "hi" -- "attempted to index: 3 as value: hi"
we can particularly use the value portion of the function to see if it is the particular string you wanted, if so, add one to a counter variable.
For example:
local counter = 0
local Target = --target string here
local meta = {
__newindex = function(self,key,value)
if value == Target then
counter = counter + 1
end
end
}
local tbl = {}
setmetatable(tbl,meta)
Iterating
An alternative to doing that would be to iterate through the table when the button in question is clicked.
An example of that would be:
local counter = 0
local target = --target String
local button = --textbutton hierarchical position here
button.Activated:Connect(function()
for k,v in pairs(strings) do
if v == target then
counter = counter + 1
end
end
end)
Hopefully this helped, be sure to accept if it did!
Writing this in scriptinghelpers website, so don't be suprised if it doesn't work.
function getStringAppearances(table, string)
local appearances = 0
if type(string) == "string" then
for _, strings in pairs(table) do
if strings == string then
appearances = appearances + 1
end
end
end
return appearances
end
local myTable = {"cat", "cat", "dog"}
print(getStringAppearances(myTable, "cat")) -- should be 2? Tell me if not and i'll debug it for you
1 comment
Exactly what I was looking for, thanks!
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
uh so how much times a single string is added to the table