【问题标题】:How to rename fields in array in .lua如何在 .lua 中重命名数组中的字段
【发布时间】:2023-01-27 16:31:17
【问题描述】:

我是 .lua 的新手。我阅读了文档,但没有找到问题的答案。

有一个空间“公司”. 里面是一个“信息”地图。 这张地图里面有一个“工作”对象和数组“用户”对象。 这“用户”数组由 2 个对象组成。每个对象有 4 个字段。

我需要重命名 2 个字段: 旧字段名称 ->速度地址. 新字段名称 ->用户率用户地址

"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"
          }
        ]
    }
}

我的解决方案如下:

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} })

在这里我试图重命名速度至 ->用户率地址至 ->用户地址然后进行更新。

请告诉我这里出了什么问题。

请帮我弄清楚。

【问题讨论】:

    标签: lua lua-table tarantool tarantool-cartridge


    【解决方案1】:
    for _, attr in pairs(users) do
        local user_rate = attr.rate
        local user_address = attr.address
    end
    

    他只是在创建两个局部变量并为它们赋值。在循环之后,它们超出了范围。所以你真的没有做任何有用的事情。

    如果你想“重命名”表字段,你需要将这些字段的值分配给新字段名称并将 nil 分配给旧字段。

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

    【讨论】:

      猜你喜欢
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 2015-10-19
      • 2012-02-25
      • 1970-01-01
      • 2022-11-14
      相关资源
      最近更新 更多