setin

function setin( tab, val, ... )

Description

Sets a value in a nested table, where val is the new value and a sequence of keys. If any level do not exist, a table will be created.

Parameters

tab

The table that should get the new value.

val

The new value.

A sequence of keys.

Code

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

   local parent = nil
   local value = tab
   local key = nil
   for i, k in ipairs( path ) do
      if not value[ k ] and i ~= #path then
         value[ k ] = {}
      end
      parent = value
      value = value[ k ]
      key = k
   end

   parent[ key ] = val
end

return setin

Examples

local t = require( "taptest" )
local setin = require( "setin" )

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

setin( obj, 29, "age" )
t( obj.age, 29 )

setin( obj, "Durham", "address", "city" )
t( obj.address.city, "Durham" )

t()

Inspired by