Key-value pairs in a table don't have a stable order. For each run through with the pairs
or next
functions, you may see a different sequence of key-value pairs. (Presumably the sequence might change as a result of adding or removing from the table.)
Except for setting or getting at specific keys, other table operations use the positive integer keys. maxn
gets the maximum key n that does not have a nil value. The others assume the keys are contiguous. For such tables, the positive integer keys can be considered to have a definite range and are ordered so sorting would make sense.
The positive integer keys in List
are not contiguous. So, sort
's behavior is not useful (and, in general, non-deterministic).
Perhaps, you wanted something like this operation over all positive integer keys:
local values = {}
-- extract values from positive integer keys
for key, value in pairs(List)
if (type(key) = "number") and key > 0 then
table.insert(values, value)
List[key] = nil
end
end
-- sort and restore them to the table
table.sort(values, function(a,b) return tonumber(a)<tonumber(b) end)
for key, value in values
List[key] = value
end