【问题标题】:Shallow table copy in Lua 4Lua 4中的浅表副本
【发布时间】:2017-08-23 06:06:04
【问题描述】:

我正在为使用 Lua 4 的旧视频游戏制作模组,我需要一种方法来创建输入表的浅表副本。我在网上找到了这个例程:

http://lua-users.org/wiki/CopyTable

function shallowcopy(orig)
    local orig_type = type(orig)
    local copy
    if orig_type == 'table' then
        copy = {}
        for orig_key, orig_value in pairs(orig) do
            copy[orig_key] = orig_value
        end
    else -- number, string, boolean, etc
        copy = orig
    end
    return copy
end

但是,该例程是为更高版本的 Lua 编写的。例如,pairs 函数在 Lua 4 中不存在。此外,该函数不是递归的。我将如何编写一个在 Lua 4 中工作并且是递归的等效例程?谢谢!

[编辑]

更新帖子。

【问题讨论】:

  • 为什么您在创建浅拷贝时请求帮助,但发布创建深层拷贝的代码?
  • 我没有注意到这一点。接得好。我更新了问题。

标签: lua lua-4.0


【解决方案1】:

Lua 4 有一个用于表的 for 循环。

table for 语句遍历给定表的所有对(索引、值)。它的语法如下:

   stat ::= for name `,' name in exp1 do block end

请参阅 Lua 4 参考手册第 4.4.4 节

https://www.lua.org/manual/4.0/manual.html#4.4

浅拷贝例程不需要递归。这只会影响通过引用复制的表值,因此所有成员都参与其中。

【讨论】:

    猜你喜欢
    • 2019-11-16
    • 1970-01-01
    • 2013-04-22
    • 2015-02-22
    • 2021-04-12
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多