Skip to content

Instantly share code, notes, and snippets.

@cloudwu
Last active August 29, 2015 14:14
Show Gist options
  • Save cloudwu/879a6c305c0389374471 to your computer and use it in GitHub Desktop.
Save cloudwu/879a6c305c0389374471 to your computer and use it in GitHub Desktop.
local index_cache = setmetatable({} , { __mode = "k" })
local meta = {}
function meta.__newindex(t, k, v)
index_cache[t] = nil
rawset(t, k, v)
end
function meta.__pairs(t)
local index = index_cache[t]
if not index then
index = {}
local i = 1
for k in next, t do
index[i] = k
i=i+1
end
table.sort(index)
index_cache[t] = index
end
local i = 0
return function(t)
i = i + 1
for j = i,#index do
local k = index[j]
local v = t[k]
if v then
return k , v
end
end
end, t
end
function make_order(t)
return setmetatable(t or {}, meta)
end
function test(map)
map.a = 1
map.b = 2
map.c = 3
map.d = 4
map.e = 5
map.f = 6
map.d = nil
map.b = nil
map.g = 7
for k,v in pairs(map) do
print(k,v)
end
end
local tbl = {}
print "===table"
test(tbl)
print "===order map"
test (make_order(tbl))
--[[
===table
e 5
c 3
a 1
g 7
f 6
===order map
a 1
c 3
e 5
f 6
g 7
]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment