[Solved]How to sort data (when table.sort cannot be used)?
Posted: Wed Oct 09, 2024 2:56 pm
A simple example :
However, this is inefficient if number of records become huge. To reduce memory size :
1) Each field is a lua table. Then we only need three long lua sequences.
db[field][id] == value
db["Age"][1] == 32
db["Weight"][220] = 65
...
2) C Array/Struct
ID(4byte)-Age(1byte)-Height(1byte)-Weight(1byte)...
For these methods, inserting and removing records were not that difficult - but I am having a trouble in sorting them as there is no provided standard function. As a half measure, I am currently using a temporary sequence of ID :
As it seems to be a common problem, I speculate that there are more proficient ways to handle this. What would you recommend?
Always thankful for your help, forum!
If each record is a lua table (e.g {1, 32, 175, 70}), we can just use table.sort.ID | Age | Height(cm) | Weight(kg)
001 | 32 | 175 | 70
002 | 24 | 182 | 82
(...)
220 | 62 | 168 | 65
However, this is inefficient if number of records become huge. To reduce memory size :
1) Each field is a lua table. Then we only need three long lua sequences.
db[field][id] == value
db["Age"][1] == 32
db["Weight"][220] = 65
...
2) C Array/Struct
ID(4byte)-Age(1byte)-Height(1byte)-Weight(1byte)...
For these methods, inserting and removing records were not that difficult - but I am having a trouble in sorting them as there is no provided standard function. As a half measure, I am currently using a temporary sequence of ID :
Code: Select all
local function sort(a, b)
return db[field][a] > db[field][b]
end
local tmp = {1, 2, 3, ..., 220}
table.sort(tmp, sort)
newDB = clone(DB) -- copy same structure
for i=1, #tmp do
newDB:set(i, tmp[i], db["Age"][tmp[i]], db["Height"][tmp[i]], ...) -- db:set(index, id, field1, field2, ...)
end
DB = newDB
Always thankful for your help, forum!