accessor

function accessor( tab, mkpath, ... ) --> acsr

Description

Returns a pointer to a value in a nested table tab, where are a sequence of keys. The mkpath allows to create a path to the value.

Parameters

tab

The table with the value.

mkpath

Boolean that allows to create the path.

A sequence of keys.

Return Values

acsr

A pointer to a value inside the table.

Code

--ZFUNC-accessor-v1
local function accessor( tab, mkpath, ... ) --> acsr
   local path = { ... }

   local acsr = { parent=nil, value=tab, key=nil }

   for i, k in ipairs( path ) do
      if not acsr.value[ k ] and i ~= #path then
         if mkpath then acsr.value[ k ] = {} else return nil end
      end
      acsr.parent = acsr.value
      acsr.value = acsr.value[ k ]
      acsr.key = k
   end

   acsr.get = function( self )
      return self.value
   end
   acsr.set = function( self, v )
      self.value = v
      self.parent[ self.key ] = self.value
   end

   return acsr
end

return accessor

Examples

local t = require( "tapered" )
local accessor = require( "accessor" )

local obj = {
   name = { first_name = "Dave",
            last_name = "Yarwood" },
   age = 28,
   hobbies = { "music", "languages", "programming" }
}

local age = accessor( obj, false, "age" )
t.is( "age", age.key )
t.is( 28, age:get() )
age:set( 29 )
t.is( 29, obj.age )

local city = accessor( obj, true, "address", "city" )
t.is( nil, city:get() )
city:set( "Durham" )
t.is( "Durham", obj.address.city )

t.done()

See also