lua

Update values in a Lua table from values of another table


Let's say I have the following table in Lua:

t1 = {
  name = "alfa",
  weight = 10,
  height = 5,
  speed = 4,
  price = 100,
}

Now I want to clone this, but replace some values within, but not all. So it's kind of like this:

-- this deepcopy function is provided by a 3rd party library
t2 = deepcopy(t1)
t2_diff = {
  name = "beta",
  weight = 20,
  speed = 6,
}
function_to_update_table(t2, t2_diff)
-- at this point, I expect the t2 table's values to be like this:
--   t2.name == "beta"
--   t2.weight == 20
--   t2.height == 5 (so, no change from the value in t1)
--   t2.speed == 6
--   t2.price == 100 (also no change from t1)

In other words, something similar to Python's dict.update() method.

Is there such a function to perform table update?


Solution

  • Lua (5.4) does not include the described function in its Standard Library (see: 6.6 – Table Manipulation). table.move is the closet analogue, but it behaves like the C function memmove, working on array-like tables (i.e., a sequence).

    You will have to implement this function yourself. In the simplest of terms, it can be written as:

    local function update(to, from)
        for key, value in pairs(from) do    
            to[key] = value                          
        end                                    
    end