为什么Lua在递归函数中在表中创建表?

时间:2018-03-19 13:54:17

标签: recursion lua

我想将table中的每个值替换为另一个值。我的代码:

function substitute_in_table(requests)
    local function helper(r, result)
        for k, v in pairs(r) do
            if type(v) == "table" then
                result[k] = helper(v, result)
            else
                result[k] = 'someValue'
            end
        end
        return result
    end

    return helper(requests, {})
end


r = {
    request = {
        headers = "a",
        body = "b"
    }
}
result = substitute_in_table(r)
print(inspect(result))

在结果中,我有一个这样的表:

{
   headers = "someValue"
   body = "someValue",
   request = {
      headers = "someValue"
      body = "someValue"
   }
}

但预期的结果是

request = {
    headers = "someValue"
    body = "someValue"
}

1 个答案:

答案 0 :(得分:1)

看起来你应该换行

result[k] = helper(v, result)

result[k] = helper(v, {})

所以你要将子表复制到新表中,然后将结果插入到原始表中,而不是将子表直接复制到原始表中