Lua的深拷贝和浅拷贝
2023-02-18 16:41:10 时间
今天在写游戏的时候,遇到了一个数据问题,就开始查资料
代码如下
--- Deep copies a table into a new table.
-- Tables used as keys are also deep copied, as are metatables
-- @param orig The table to copy
-- @return Returns a copy of the input table
local function deep_copy(orig)
local copy
if type(orig) == "table" then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[deep_copy(orig_key)] = deep_copy(orig_value)
end
setmetatable(copy, deep_copy(getmetatable(orig)))
else
copy = orig
end
return copy
end
--- Copies a table into a new table.
-- neither sub tables nor metatables will be copied.
-- @param orig The table to copy
-- @return Returns a copy of the input table
local function shallow_copy(orig)
local copy
if type(orig) == "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
例子如下:
深拷贝
local a = { aa = 1, bb = 2, cc = { dd = { ee = 3 } } }
--local b = deep_copy(a)
local b = shallow_copy(a)
b.cc.dd.ee = 111
b.bb = 111
ngx.say(cjson.encode(a))
ngx.say(cjson.encode(b))
结果:{“aa”:1,”bb”:2,”cc”:{“dd”:{“ee”:111}}}
{“aa”:1,”bb”:111,”cc”:{“dd”:{“ee”:111}}}
浅拷贝
local men = { mkey = 555 }
local a = { aa = 1, bb = 2, cc = { dd = { ee = { ff = 3 } } } }
setmetatable(a, { __index = men })
local b = deep_copy(a)
ngx.say(a.cc.dd.ee.ff)
ngx.say(a.mkey)
ngx.say(b.mkey)
3
555
555
相关文章
- 如何去除pycharm中警告波浪线
- Gradle与IDEA整合
- Drawio v20.2.3 开源跨平台绘图软件
- Gradle入门
- Typecho优化加速 - Gzip压缩
- Java反编译工具JAD下载和使用
- H3C交换机堆叠配置及命令详解
- Typecho文章里添加版权链接 - 纯代码
- 假期还要卷,24个免费数据集送给你
- FastStone Capture 屏幕录制截图工具
- Brother标签机连续打印多个标签
- SpringCache基本操作
- 网站外链发布工具 - SEO优化工具
- RabbitMQ之发布高级
- H3C - S6800交换机升级系统版本、补丁
- PyCharm无法导入第三方模块解决办法
- ElasticSearch的基本操作
- RabbitMQ之延迟队列
- Flutter异常监控 - 肆 | Rollbar源码赏析
- 红帽RHEL8与RHEL7的区别详细介绍