Una tabella in Lua è un insieme di mappature chiave-valore con chiavi univoche. Le coppie vengono memorizzate in ordine arbitrario e pertanto la tabella non viene ordinata in alcun modo.
Quello che puoi fare è iterare sopra il tavolo in qualche ordine. Lo standard pairs
non fornisce alcuna garanzia dell'ordine in cui le chiavi vengono visitate. Ecco una versione personalizzata di pairs
, che ho chiamato spairs
perché itera sul tavolo in un modo ordinato:
function spairs(t, order)
-- collect the keys
local keys = {}
for k in pairs(t) do keys[#keys+1] = k end
-- if order function given, sort by it by passing the table and keys a, b,
-- otherwise just sort the keys
if order then
table.sort(keys, function(a,b) return order(t, a, b) end)
else
table.sort(keys)
end
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
Ecco un esempio di utilizzo di tale funzione:
HighScore = { Robin = 8, Jon = 10, Max = 11 }
-- basic usage, just sort by the keys
for k,v in spairs(HighScore) do
print(k,v)
end
--> Jon 10
--> Max 11
--> Robin 8
-- this uses an custom sorting function ordering by score descending
for k,v in spairs(HighScore, function(t,a,b) return t[b] < t[a] end) do
print(k,v)
end
--> Max 11
--> Jon 10
--> Robin 8
fonte
2013-03-29 16:01:40
possibile duplicato di [ copiare i dati dalla tabella ad un altro con ordine] (http://stackoverflow.com/questions/5153642/copying-data-from-table-to-antoher-with-order) – finnw
La tabella non viene ordinata in serie o qualcosa del genere. Non ha ordine manifestato. – texasbruce