Skip to content

Instantly share code, notes, and snippets.

@R0bl0x10501050
Created October 22, 2021 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save R0bl0x10501050/026aaf96b81b688645d2bec83ed9126d to your computer and use it in GitHub Desktop.
Save R0bl0x10501050/026aaf96b81b688645d2bec83ed9126d to your computer and use it in GitHub Desktop.
indexedhashmap.lua
local IndexedHashmap = {
['new'] = function()
local self = setmetatable({
_IndexKey = {},
_KeyValue = {}
}, {
__newindex = function(t, k, v)
if not table.find(t._IndexKey, k) then
table.insert(t._IndexKey, k)
end
rawset(t._KeyValue, k, v)
end,
__index = function(t, k)
return rawget(t._KeyValue, k)
end,
__len = function(t)
return #t._KeyValue
end,
})
return self
end,
['ipairs'] = function(t)
local idxkey = t._IndexKey
local keyval = t._KeyValue
local idx = 1
return function()
local oldidx = idx
local oldval = keyval[idxkey[idx]]
if oldidx and oldval then
if idx <= #idxkey then
idx += 1
return oldidx, oldval
end
end
end
end,
['pairs'] = function(t)
local idxkey = t._IndexKey
local keyval = t._KeyValue
local idx = 1
return function()
local oldkey = idxkey[idx]
local oldval = keyval[oldkey]
if oldkey and oldval then
if idx <= #idxkey then
idx += 1
return oldkey, oldval
end
end
end
end,
['ikpairs'] = function(t)
local idxkey = t._IndexKey
local keyval = t._KeyValue
local idx = 1
return function()
local oldidx = idx
local oldkey = idxkey[idx]
local oldval = keyval[oldkey]
if oldidx and oldkey and oldval then
if idx <= #idxkey then
idx += 1
return oldidx, oldkey, oldval
end
end
end
end
}
return IndexedHashmap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment