Skip to content

Commit

Permalink
ffiUtil: Make orderedPairs behave with mixed key types (#1517)
Browse files Browse the repository at this point in the history
Usually involves sorting numbers with strings, but could theoretically be more esoteric ;).

Still assumes that matching types supports comparisons, which may not always be true for custom types without an overloaded operator...

Should be fine for our current needs, though.

If need be, se the wiki page referenced in the function's description, as it features some more complex solutions.
  • Loading branch information
NiLuJe committed Sep 15, 2022
1 parent b8a77ba commit 66f8b4a
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions ffi/util.lua
Expand Up @@ -655,12 +655,20 @@ end
-- pairs(), but with *keys* sorted alphabetically.
-- c.f., http://lua-users.org/wiki/SortedIteration
-- See also http://lua-users.org/wiki/SortedIterationSimple
local function __genOrderedIndex( t )
local function __genOrderedIndex(t)
local orderedIndex = {}
for key in pairs(t) do
table.insert( orderedIndex, key )
table.insert(orderedIndex, key)
end
table.sort( orderedIndex )
table.sort(orderedIndex, function(v1, v2)
if type(v1) == type(v2) then
-- Assumes said type supports the < comparison operator
return v1 < v2
else
-- Handle type mismatches by squashing to string
return tostring(v1) < tostring(v2)
end
end)
return orderedIndex
end
Expand All @@ -669,10 +677,10 @@ local function orderedNext(t, state)
-- We use a temporary ordered key table that is stored in the table being iterated.
local key = nil
--print("orderedNext: state = "..tostring(state) )
-- print("orderedNext: state = "..tostring(state))
if state == nil then
-- the first time, generate the index
t.__orderedIndex = __genOrderedIndex( t )
t.__orderedIndex = __genOrderedIndex(t)
key = t.__orderedIndex[1]
else
-- fetch the next value
Expand Down

0 comments on commit 66f8b4a

Please sign in to comment.