Hello once again.
My program is almost finished. but there is one thing i just cant figure out. i searched a long time, but all solutions i got werent the right ones.
So, here´s my problem:
I want to sort values in a table:
--this is tabelA. all the times are stored in it. the times are NOT ordered.
tabelA = {
["train1"] = {"20"},
["train2"] = {"60"},
["train3"] = {"40"},
["train4"] = {"80"}
}
--this is tabelB, at the end it should contain the times of all four trains. The key is for defining and the value should be the corresponding train.
tabelB = {
[1] = " "
[2] = " "
[3] = " "
[4] = " "
}
-- so as an example of an correctly filled tabel:
[1] = "train1"
[2] = "train3"
[3] = "train2"
[4] = "train4"
cant figure out how to sort these.
any help is appreciated ;)/>
by my understanding, your table will never sort and be abled to output your desired results.
becase your keys are what you want to change the order of.
you would have to store the table as fx. tableA[1] = "train1", 60 … This way you maybe abled to run a sort on the 60…
I found this under a quick search… Then I played around a bit also and wrote this bit of code to make it work in CC….
local tableA = {
[0] = {"train0", "20"},
[1] = {"train1", "60"},
[2] = {"train2", "40"},
[3] = {"train3", "80"},
[4] = {"train4", "20"},
}
t = tableA
table.sort(t, function(a, B)/> -- why does it add a /> here every time i edit...
return tonumber(a[2]) > tonumber(b[2])
end)
for i = 1,#t do
print(t[i][1])
end
the above code outputs …
Spoiler
train3
train1
train2
train4this should return a check on the second value in a table to see if e1 is bigger than e2 (the larger value goes first when sorted).
(I had troubles with getting it to work at first with attempt to compare nil and nil…) that was untill i realised I had forgotten to tonumber the text numbers.
this is the example table I found… just to give the full example.
Spoiler
table = {
[1] = {"something", "high"}
[2] = {"something else", "low"}
[3] = {"something further", "medium"},
[4] = {"yet more something", "medium"},
}
priorities = {high = 2, medium = 1, low = 0}
table.sort(t, function(e1, e2)
return priorities[e1[2]] > priorities[e2[2]]
end)
to be a bit more fancy… you could make a data entry for the train and times…
eg ask on screen "train no : " then get input of a number as "trnr" . then ask for time as "trti".
use
trnr = "train" .. trnr – this makes out number into a string that says for example "train5" if we entered 5
– could insert a table check here to see if train5 exists in the table already
table.insert(tableA, newdata(trnr, trti))
have a function that inserts the data into a table value.
function newdata(nr, ti) -- insert data
local u = {}
u[1] = nr
u[2] = ti
return u
end
this then stores our new data in the next slot. and voila an updateable table that adds new entries. (entering the same train number is not checked here…