lua-users home
lua-l archive

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


Greg McCreath wrote:
>> Have you seen http://lua-users.org/wiki/AutomagicTables ?
> Nice.  Thanks.  I hadn't seen that.  I had been looking though.

I've attached a module-ized version of the code on the wiki page. Just
put it in your package.path and use:

require'autotable'
a = autotable.new()
a.b.c.d = "a.b and a.b.c are automatically created"

I found it useful. Hope it helps someone else.

Doug

-- 
--__-__-____------_--_-_-_-___-___-____-_--_-___--____
Doug Rogers - ICI - V:703.893.2007x220 www.innocon.com
-_-_--_------____-_-_-___-_--___-_-___-_-_---_--_-__-_
-- Based on code at http://lua-users.org/wiki/AutomagicTables, by Rici Lake
-- and Thomas Wrensch. Module by Doug Rogers. This code is in the public
-- domain.

-- Some further words from that site:

-- Building on some of the techniques illustrated in FuncTables, here are
-- some implementations of Perl-style automagic tables. An automagic table
-- creates subtables on demand, as it were; i.e.:

-- require'autotable'
-- a = autotable.new()
-- a.b.c.d = "a.b and a.b.c are automatically created"

local getmetatable = getmetatable
local setmetatable = setmetatable

module("autotable")

local auto, assign

function auto(tab, key)
  return setmetatable({}, {
          __index = auto,
          __newindex = assign,
          parent = tab,
          key = key
  })
end

local meta = {__index = auto}

-- The if statement below prevents the table from being
-- created if the value assigned is nil. This is, I think,
-- technically correct but it might be desirable to use
-- assignment to nil to force a table into existence.

function assign(tab, key, val)
-- if val ~= nil then
  local oldmt = getmetatable(tab)
  oldmt.parent[oldmt.key] = tab
  setmetatable(tab, meta)
  tab[key] = val
-- end
end

-- Creates and returns a new table with automagic properties.
function new()
  return setmetatable({}, meta)
end