Is there a Python defaultdict function available in Lua

Is there any functionality in Lua, similar collections.defaultdict, available in Python, that automatically handles default values ​​for nonexistent associative array keys?

I want the code below to set nilin vinstead of an error. Thus, essentially the a[2]default method (non-existent key) table:

a = {}
v = a[2][3] 

>>> PANIC: unprotected error in call to Lua API (main.lua:603: attempt to index field '?' (a nil value))

In Python, this can be done as follows:

>>> import collections
>>> a = collections.defaultdict(dict)
>>> print a[2]
{}
+3
source share
2 answers

Is there a standard Lua function? No. But you can do it quite easily with metatables. You can even write a function to create such tables:

function CreateTableWithDefaultElement(default)
  local tbl = {}
  local mtbl = {}
  mtbl.__index = function(tbl, key)
    local val = rawget(tbl, key)
    return val or default
  end
  setmetatable(tbl, mtbl)
  return tbl
end

, . , , "" . , , .

+5

, , - , , , .. , Nicol, .

function defaultdict(default_value_factory)
    local t = {}
    local metatable = {}
    metatable.__index = function(t, key)
        if not rawget(t, key) then
            rawset(t, key, default_value_factory(key))
        end
        return rawget(t, key)
    end
    return setmetatable(t, metatable)
end

:

d = defaultidct(function() return {} end)
table.insert(d["people"], {"Bob", "The Builder"})

names = defaultdict(function(key) return key end)
print(names["bob"]) -- bob
names["bob"] = "bob the builder"
names["ashley"] = "ashley the fire princess"
+1

All Articles