Thread: Tables
View Single Post
07-13-10, 10:55 AM   #3
eGoh
A Defias Bandit
AddOn Author - Click to view addons
Join Date: Mar 2010
Posts: 3
Testing out the code formatting, but might as well post something useful while I'm at it!

Declare your register like thus:
Code:
local register = {}
Add data using this:
Code:
function AddData(day, ate, food, candy, drank, peed, gallonsPeed, poopt, regnum)
    register[day] = {
    	["ate"] = ate,
    	["food"] = food, 
    	["candy"] = candy, 
    	["drank"] = drank, 
    	["peed"] = peed, 
    	["gallonsPeed"] = gallonsPeed, 
    	["poopt"] = poopt, 
    	["regnum"] = regnum
    }
    candyindex[day] = true
end
This creates a table using "day" as the primary key and it has to be unique for every entry. This also means that searches based on the "day" will be very fast. i.e.

Code:
function GetDayData(day)
	local value = register[day]
	return value.peed, value.gallonsPeed, value.poopt
end
However, aggregate functions like the one you want will get slower as you add more entries to the table. Simply, because you have to loop through every value. This is no problem if you only want to store a few hundred entries.

Code:
function GetCandyData()
    local poopt=0
    local peed=0
    local gallonsPeed=0
    
    for i,v in pairs(register) do
        if candy then
            poopt =  poopt + v.poopt
            peed =  peed + v.peed
            gallonsPeed =  gallonsPeed + v.gallonsPeed
        end
    end
    
    return poopt, peed, gallonsPeed
end
If you are going to store lots and lots of entries, AND you know that you are going to do this sort of search often, AND you know that you don't eat candy very often, you can create an index, and populate it every time you add to the table.

Code:
local register = {}
local candyindex = {}

function AddData(day, ate, food, candy, drank, peed, gallonsPeed, poopt, regnum)
    register[day] = {
    	["ate"] = ate,
    	["food"] = food, 
    	["candy"] = candy, 
    	["drank"] = drank, 
    	["peed"] = peed, 
    	["gallonsPeed"] = gallonsPeed, 
    	["poopt"] = poopt, 
    	["regnum"] = regnum
    }
    candyindex[day] = true
end
So when you rewrite, the candy function, it will be more efficient, and only slow down when you eat too much candy, as opposed to the number of days you record.

Code:
function GetCandyData()
    local poopt=0
    local peed=0
    local gallonsPeed=0
        
    for i,v in pairs(candyindex) do
        local values = register[i];
        poopt =  poopt + values.poopt
        peed =  peed + values.peed
        gallonsPeed =  gallonsPeed + values.gallonsPeed
    end
    
    return poopt, peed, gallonsPeed
end
Of course, if you eat candy every day, then this code will most likely end up being slower than without the index!

P.S. Okay! Okay! I give up! How do you switch on the fancy schmancy syntax hilighting?

Last edited by eGoh : 07-13-10 at 01:59 PM. Reason: careless coding
  Reply With Quote