Get occurences of a string in table

Here’s an example:

local myTable = {
	"String1",
	"String1",
	"String2"
}

I want to see how many occurrences of “String1” is in the table. How would I do that? Is there a table function for this purpose?

There’s no table function for counting elements but you can do this:

local n = 0

for i,v in pairs(myTable) do
    if v == "String1" then
       n = n + 1
    end
end
1 Like
local myTable = {
	"String1",
	"String1",
	"String2"
}


local CheckOccurences = function(Table, String)
	local Occurences = 0
	for i,v in ipairs(myTable) do 
		if (v == String) then 
			Occurences += 1
		end
	end
	
	return Occurences
end

print(CheckOccurences(myTable, "String1")) --> 2
1 Like

Both of these helped, thank you guys!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.