getin

function getin( tab, ... ) --> val

Description

Returns the value val in a nested table tab, where are a sequence of keys. Returns nil if the key sequence not exist in the table.

Parameters

tab

The table with the value.

A sequence of keys.

Return Values

val

The value inside the table.

Code

--ZFUNC-getin-v1
local function getin( tab, ... ) --> val
   local path = { ... }

   local val = tab
   for i, v in ipairs( path ) do
      val = val[ v ]
      if not val then
         return nil
      end
   end

   return val
end

return getin

Examples

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

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

t.is( "Yarwood", getin( obj, "name", "last_name" ) )
t.is( "programming", getin( obj, "hobbies", 3 ) )
t.is( nil, getin( obj, "birthday" ) )

t.done()

Inspired by