lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 7/3/2013 9:46 PM, Scott Fial wrote:
What if there was a formal way to set/get the internal "default value"
of a table?  For example, if I were to call setdefault(t, -1), then t
could contain any value except -1.  Reading a non-existent key would now
return -1.  Assigning -1 to a key would delete it.
Scott

Continuing this thought. For convenience, "table" could provide the basic functions and a pre-made "undef" atom for general use as an alternative default:

  function table.getdefault(t) --[[ magic ]] end

  function table.setdefault(t, d) --[[ magic ]] end

  function table.has(t, k) return t[k] ~= table.getdefault(t) end

  function table.delete(t, k) t[k] = table.getdefault(t) end

  table.undef = {__tostring = function () return "undef" end}
  setmetatable(table.undef, table.undef)


Scott