PDA

View Full Version : Pairs



Centauri Soldier
02-25-2010, 08:48 AM
I have a very complex table containing index and key values and each of those sub tables contain index and key values as well. I want to read all the info from the master table with a single function but I'm just not getting how to use the pairs(), ipairs() or next() functions to do this. Any ideas?

RizlaUK
02-25-2010, 03:11 PM
i maybe off track here, but is this what you mean


t={}
t.A="First"
t.B="Second"
t.C="Third"

l={}
l.E="Forth"
l.F="Fith"
l.G="Sixth"

m={}
m.H="Seventh"
m.I="Eith"
m.J="Ninth"

k={}
k.A={t.A,t.B,t.C}
k.B={l.E,l.F,l.G}
k.C={m.H,m.I,m.J}

for keyA,valueA in next,k,nil do

Debug.Print(keyA.." - "..tostring(valueA).."\r\n")
if type(valueA) == "table" then
for keyB,valueB in next,valueA,nil do
Debug.Print(keyB.." - "..tostring(valueB).."\r\n")
if type(valueB) == "table" then
for keyC,valueC in next,valueB,nil do
Debug.Print(keyC.." - "..tostring(valueC).."\r\n")


end
end
end
end
end

Centauri Soldier
02-25-2010, 04:28 PM
That's kinda what I'm after but I have decoded to reduce the amount of sub-tables in order to avoid using a recursive algorithm. I have put a firm cap on the amount of sub-tables present and although this method has increased my initial work load it will make future manipulation of the data much simpler.

I've got a few thousand lines worth of tables so I'd better think a little farther ahead. Thank Riz.

RizlaUK
02-25-2010, 05:55 PM
you could make it recursive over many levels and print out each pair it encounters by just calling the function again

try like this, it will go as deep as your tables go


t={}
t.A="First"
t.B="Second"
t.C="Third"

l={}
l.E="Forth"
l.F="Fith"
l.G="Sixth"

m={}
m.H="Seventh"
m.I="Eith"
m.J="Ninth"

k={}
k.A={t.A,t.B,t.C}
k.B={l.E,l.F,l.G}
k.C={m.H,m.I,m.J}

function DebugTable(t)

for key,value in next,t,nil do
Debug.Print(key.." - "..tostring(value).."\r\n")
if type(value) == "table" then
DebugTable(value)
end
end

end

-- call the function with the main table
DebugTable(k)

Centauri Soldier
02-25-2010, 06:22 PM
Oh wow! That's way cool. I didn't know the code would be so short...I was anticipating writing a phone book to get that result.

I am still going with my other plan but I'm certain that I can find a use for this code in a few other sections of my app.

For those particular tables I built a scripting function that processes my pre-made script files and converts the data into files that contain my tables.

Thanks again, Rizla. :D

RizlaUK
02-26-2010, 02:45 AM
I was anticipating writing a phone book to get that result.

lol, simplicity is brilliance

i always use that little trick for recursive functions, loading files/xml/etc, i used to write *phone book* functions too

the worst one iv encountered, i spent 4/5 days writing a function in PB (ended up at nearly 5k lines of code) and it was replaced with a single function call to API!!!

it was then i started researching the API :p