Search code examples
lualua-tabletarantooltarantool-cartridge

How to rename fields in array in .lua


I'm new in .lua. I read the documentation, but didn't find the answer to my question.

There is a space "company". Inside it's an "information" map. Inside this map is a "job" object and an array of "users" objects. The "users" array consists of 2 objects. Each object has 4 fields.

I need to rename 2 fields: Old field names -> rate and address. New field names -> user_rate and user_address

"company": {
  "information":
    {
      "job":
        {
          "job_name": "N",
          "job_address": 1670392687114,
          "job_salary": 1234567890123,
          "contacts": 0
        },
      "users":
        [
          {
            "id": 1,
            "name": "Alex",
            "rate": 4,
            "address": "bla bla bla"
          },
          {
            "id": 2,
            "name": "Jenifer",
            "rate": 5,
            "address": "bla bla bla"
          }
        ]
    }
}

My solution was the following:

for _, tuple in space:pairs() do
   if tuple.params ~= nil or tuple.params.offer_params ~= nil then

      local information = tuple.information or {}
      local users = information.users

      for _, attr in pairs(users) do
         local user_rate = attr.rate
         local user_address = attr.address
      end

      local key = {}
      for _, part in ipairs(key_parts) do table.insert(key, tuple[part.fieldno]) end
      space:update(key, { {'=', 'information', information} })

Here I am trying to rename rate to -> user_rate and address to -> user_address and then doing an update.

Please tell me what is wrong here.

Please help me figure it out.


Solution

  • for _, attr in pairs(users) do
        local user_rate = attr.rate
        local user_address = attr.address
    end
    

    he're you're just creating two local variables and assign a value to them. After the loop they run out of scope. So you really didn't do anything useful.

    If you want to "rename" table fields you need to assign the values of those fileds to the new field names and assign nil to the old field.

    for _, user in pairs(users) do
      user.user_rate = user.rate
      user.rate = nil
      user.user_address = user.address
      user.address = nil
    end
    

    For more you might want to implement a function that does that to keep your code clean.