Created
June 6, 2020 14:10
-
-
Save zuriby/187d62f107d7f610d9337d37cf1d21d6 to your computer and use it in GitHub Desktop.
lua implementaiton of python's default dict
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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