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( "taptest" )
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( age.key, "age" )
t( age:get(), 28 )
age:set( 29 )
t( obj.age, 29 )

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

t()

See also