Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ffiUtil: Make orderedPairs behave with mixed key types #1517

Merged
merged 3 commits into from Sep 15, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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