updatein

function updatein( tab, fv, ... )

Description

Updates a value in a nested table with the function fv, where is a sequence of keys. If any level fo not exist, a table will be created.

Parameters

tab

The table where a value should be updated.

f

Function that takes the old value and returns the new value.

A sequence of keys.

Code

--ZFUNC-updatein-v1
local function updatein( tab, fv, ... )
   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 ] = fv( parent[ key ] )
end

return updatein

Examples

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

local users = {
   {
      name = "James",
      age = 26
   },
   {
      name = "John",
      age = 43
   }
}

local function inc( i )
   return i+1
end
updatein( users, inc, 1, "age" )
t( users[ 1 ].age, 27 )

local function def( v )
   if not v then
      v = "a"
   end
   return v
end
updatein( users, def, 2, "notes", 1 )
t( users[ 2 ].notes[ 1 ], "a" )

t()

Inspired by

See also