Is there a Python's defaultdict functionality available in Lua

defaultdict, lua, python

Solution

Is there a Lua standard function to do it? No. But you can do it easily enough 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

Note that each element will get the same default value. So if you make the default value a table, each "empty" element in the returned table will effectively reference the same table. If that's not what you want, you'll have to modify the function.

Problem

Is there a functionality in Lua similar to `collections.defaultdict` available in Python, which automatically handles default values for non-existent associative array keys? I want the code below to set `nil` to `v` instead of an error. So basically a way to `a[2]` (non-existent key) be a `table` by default: ``` 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 it can be done like this: ``` >>> import collections >>> a = collections.defaultdict(dict) >>> print a[2] {} ```

Original source