Skip to content

Instantly share code, notes, and snippets.

@adrian-alberto
Last active July 6, 2017 17:29
Show Gist options
  • Save adrian-alberto/7d7dff74bed0d32bcb26015d75a47b7c to your computer and use it in GitHub Desktop.
Save adrian-alberto/7d7dff74bed0d32bcb26015d75a47b7c to your computer and use it in GitHub Desktop.
Dict = {}
function Dict.__newindex(table, key, value)
if value ~= nil and table.__INNER[key] == nil then
table.__LENGTH = table.__LENGTH + 1
elseif value == nil and table.__INNER[key] ~= nil then
table.__LENGTH = table.__LENGTH - 1
end
rawget(table,"__INNER")[key] = value
end
function Dict.__index(table, key)
return rawget(table, "__INNER")[key]
end
function Dict.__len(table)
return rawget(table,"__LENGTH")
end
function dict()
return setmetatable({__INNER = {}, __LENGTH = 0}, Dict)
end
myDictionary = dict()
myDictionary["hello"] = "world"
myDictionary["world"] = "!"
myDictionary["world"] = "?"
print(#myDictionary)
myDictionary["world"] = nil
print(#myDictionary)
print(myDictionary.hello)
print(myDictionary.world)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment