[SOLVED] Table Order Problem

[lua]local wireCM = {[“14”] = 4110, [“12”] = 6530, [“10”] = 10380, [“8”] = 16510, [“6”] = 26240, [“4”] = 41740, [“3”] = 52620, [“2”] = 66360, [“1”] = 83690, [“1/0”] = 105600,
[“2/0”] = 133100, [“3/0”] = 167800, [“4/0”] = 211600, [“250”] = 250000, [“300”] = 300000, [“350”] = 350000, [“400”] = 400000, [“500”] = 500000, [“600”] = 600000,
[“700”] = 700000, [“750”] = 750000, [“800”] = 800000, [“900”] = 900000, [“1000”] = 1000000, [“1250”] = 1250000, [“1500”] = 1500000, [“1750”] = 1750000, [“2000”] = 2000000 }[/lua]

I am working on an electricians app as a side project and i have been having a problem with grabbing the correct key and value from the table above. What should happen is after the user inputs all the info a number comes up and that number will be within the values above. So if the number is 5791 i want it to display “12” because “12” has a value of 6530 and it is the closest to the number that is not below 5791. The problem i am having is after the table is created the order is way off and i can not get a proper return, I’ve tried using the sort function but i can not seem to get it to work correctly since my keys are all different, if i could sort it by their values that would work great.

Here is the function i am using to grab the key and value that is closest to the number applied.
[lua]for k,v in pairs(wireCM) do
if v > 5791 then
print (k, v)
break
end
end
–Should return (“12”, 5791) but since the table is all out of wack it does not.[/lua]

so if i could get some help, Iv’e looked at the api and the docs but i can not quite grasp it to make table.sort work with what i want. Thanks in advance. [import]uid: 126161 topic_id: 22831 reply_id: 322831[/import]

In Lua, when tables are accessed via keys instead of numbers, the order isn’t guaranteed.

I would switch it to a table that is an array instead.

wireCM = {}  
wireCM[1] = {}  
wireCM[1].key = "14"  
wireCM[1].value = 4100  
wireCM[2] = {}  
wireCM[2].key = "12"  
wireCM[2].value = 6350  
  

etc.

Then you can do:

for i = 1, #wireCM do  
 if wireCM[i].value \> inputValue then  
 print(wireCM[i].key)  
 break;  
 end  
end  

That will keep the table in order.

[import]uid: 19626 topic_id: 22831 reply_id: 91187[/import]

Ive used tables that like before to keep it in order but never tried doing the sub table. It works perfectly, thanks for all the help! I will have a lot of data to put in so this will help big time to keep things organized. [import]uid: 126161 topic_id: 22831 reply_id: 91232[/import]