Search tables for number of occurrences?

Post Reply
Tahlnaith
Posts: 8
Joined: Sat Oct 23, 2010 6:19 am

Search tables for number of occurrences?

Post by Tahlnaith »

I'm looking for a way to search through a table and return how many times a string appears in any key in that table, as well as each key it appears in. For example, I have a table with the values "applepie", "banana", "cherrypie", and "orange". I want to search that table for each occurrence of "pie", return each string it appears in, "applepie" and "cherrypie", and return the number of times it appears, 2. Is this possible or would it be prohibitively complex?

User avatar
Heiko
Site Admin
Posts: 1548
Joined: Wed Mar 11, 2009 6:26 pm

Re: Search tables for number of occurrences?

Post by Heiko »

That's a pretty simple script. You simply iterate over the keys and do a string search on them.

Iocun
Posts: 174
Joined: Wed Dec 02, 2009 1:45 am

Re: Search tables for number of occurrences?

Post by Iocun »

Code: [show] | [select all] lua
function giveMePies()
	local foodlist = {"applepie", "aircraft", "banana", "cherrypie", "anotherpie", "orange", "cake", "apple"}
	local counter = 0
	local pielist = {}
	for _,v in ipairs(foodlist) do
		if string.find(v, "pie") then
			counter = counter+1
			pielist[#pielist+1] = v
		end
	end
	echo("I found "..counter.." pies!\n")
	echo("And here are the pies:")
	display(pielist)
end
This goes through the whole table, checks if it finds the string "pie" in each entry, and if it does, adds 1 to a counter and adds the item to another table, that only contains the pies. In the end it prints the number of pies and displays our new list.

Tahlnaith
Posts: 8
Joined: Sat Oct 23, 2010 6:19 am

Re: Search tables for number of occurrences?

Post by Tahlnaith »

Awesome, thank you two. I had something similar done already but I was using the wrong syntax for the foor loop like an idiot. Oh well.

Post Reply