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

Getting the number of occurrences of a string in a table?

Asked by
crome60 43
5 years ago

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?

0
uh so how much times a single string is added to the table EXpodo1234ALT 18 — 5y

2 answers

Log in to vote
1
Answered by 5 years ago

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!

Ad
Log in to vote
1
Answered by
rokedev 71
5 years ago

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
0
Exactly what I was looking for, thanks! crome60 43 — 5y

Answer this question