Quote:
What I need is some way pull the name of the table with the highest atob value (IE, if tbl.locationA_resourceB.atob has the highest value, I need to store "tbl.locationA_resourceB" into said variable). It would be extra nice if I could store the bits on either side of the _ into separate variables, but I can at least (and what I'm planning on doing) is throw a mess of ifchecks at it, and assign the two needed values that way.
From your earlier code snippet, it seems to me you are doing things the hard way anyway, which is why you are having problems getting the data back. This is your code:
tbl = {
Resource_AtoA = { a = 1.11, b = 1.11, c = 5 },
Resource_BtoA = { a = 2.22, b = 1.11, c = 5 },
Resource_CtoA = { a = 3.33, b = 1.11, c = 5 },
Resource_AtoB = { a = 1.11, b = 9.99, c = 5 },
Resource_BtoB = { a = 2.22, b = 1.11, c = 5 },
Resource_CtoB = { a = 3.33, b = 1.11, c = 5 },
Resource_AtoC = { a = 1.11, b = 1.11, c = 999 },
Resource_BtoC = { a = 2.22, b = 2.22, c = 999 },
Resource_CtoC = { a = 3.33, b = 3.33, c = 999 },
}
Since you want to get out the "AtoA" part, why not put that into the table as a variable? In other words, the table would look like this instead:
tbl = {
{ from = "A", to = "A", a = 1.11, b = 1.11, c = 5 },
{ from = "A", to = "B", a = 1.11, b = 9.99, c = 5 },
{ from = "A", to = "C", a = 1.11, b = 1.11, c = 999 },
{ from = "B", to = "A", a = 2.22, b = 1.11, c = 5 },
{ from = "B", to = "B", a = 2.22, b = 1.11, c = 5 },
{ from = "B", to = "C", a = 2.22, b = 2.22, c = 999 },
{ from = "C", to = "A", a = 3.33, b = 1.11, c = 5 },
{ from = "C", to = "B", a = 3.33, b = 1.11, c = 5 },
{ from = "C", to = "C", a = 3.33, b = 3.33, c = 999 },
} -- end tbl
Notice each item does not have a name like, so Lua assigns numeric keys (ie. 1, 2, 3 etc.).
We can still calculate a to b value:
-- calculate a to b
for k, v in ipairs (tbl) do
v.atob = (v.b - v.a) / v.c -- difference divided by a constant
end -- for loop
Now to find the highest we simply sort the table:
-- sort table
table.sort (tbl, function (ka, kb) return ka.atob > kb.atob end)
I used a custom sort function to specify that the sort comparison was the "atob" value in each item.
The highest is simply the first item (subscript 1):
-- get highest atob value
print ("Highest atob is", tbl [1].atob, "from", tbl [1].from, "to", tbl [1].to)
My example printed:
Highest atob is 1.776 from A to B
Your problem now is putting new values into the table, as the table is not keyed by A, B, C etc. (they are inside the table but not keys). There are a couple of ways you can do that, and I might leave that as an exercise.
I suspect you are not totally comfortable with using tables, I would read up on Lua tables a bit and make a few examples for yourself. It is easier to do more complex code when you are familiar with doing easier code. |