Skip to content

Instantly share code, notes, and snippets.

@tzuryby
Created June 6, 2020 14:10
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 tzuryby/187d62f107d7f610d9337d37cf1d21d6 to your computer and use it in GitHub Desktop.
Save tzuryby/187d62f107d7f610d9337d37cf1d21d6 to your computer and use it in GitHub Desktop.
lua implementaiton of python's default dict
function defaultdict(callable)
local T = {}
setmetatable(T, {
__index = function(T, key)
local val = rawget(T, key)
if not val then
rawset(T, key, callable())
end
return rawget(T, key)
end
})
return T
end
a = defaultdict(function() return {} end)
a.foo.bar = "a"
a.foo2.bar = "b"
print (a.foo.bar) -- 'a'
print (a.foo2.bar) -- 'b'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment