Skip to content

Instantly share code, notes, and snippets.

@Frank-Buss
Last active May 1, 2025 17:34
Show Gist options
  • Save Frank-Buss/73bfd3d6059fc73d0aaa07770d46e64c to your computer and use it in GitHub Desktop.
Save Frank-Buss/73bfd3d6059fc73d0aaa07770d46e64c to your computer and use it in GitHub Desktop.
redefine pairs for all tables
local original_next = next
local original_pairs = pairs
local function sorted_next(t, k)
local keys = {}
for key in original_pairs(t) do
table.insert(keys, key)
end
table.sort(keys)
local current_index = 1
if k ~= nil then
for i, key in ipairs(keys) do
if key == k then
current_index = i + 1
break
end
end
end
local next_key = keys[current_index]
if next_key then
return next_key, t[next_key]
else
return nil
end
end
_G.next = sorted_next
function _G.pairs(t)
return sorted_next, t, nil
end
local t = {
dog = "woof",
cat = "meow",
bird = "tweet",
fish = "blub"
}
print("pairs test:")
for k, v in pairs(t) do
print(k, v)
end
print("next test:")
local k, v = next(t)
while k do
print(k, v)
k, v = next(t, k)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment