lua - Lua 从父表修改元表属性
问题描述
我有这段代码,但我不希望tbl
变量得到width
并height
分配给它,而是我希望base_table
'swidth
和properties 被修改为 200,而height
不是tbl
被分配200。height
width
function deepCopy(original)
local copy = {}
for k, v in pairs(original) do
if type(v) == "table" then
v = deepCopy(v)
end
copy[k] = v
end
return copy
end
function PrintTable(t)
for k, v in pairs(t) do
if v == "table" then
PrintTable(v)
else
print(k, v)
end
end
end
local base_table = {
width = 0,
height = 0,
x = 0,
y = 0,
SetSize = function(self, w, h)
self.width, self.height = w, h
end,
SetPos = function(self, x, y)
self.x, self.y = x,y
end
}
local tbl = {}
local meta = {__index = deepCopy(base_table)}
setmetatable(tbl, meta)
PrintTable(tbl) -- prints nothing
tbl:SetSize(200, 200)
PrintTable(tbl) -- prints height 200, width 200 which I don't want, I want it to print nothing like above. though if I do tbl.x I want it to 200, since it would be on the metatable, rather than the tbl itself
解决方案
local function deepCopy(original)
local copy = {}
for k, v in pairs(original) do
if type(v) == "table" then
v = deepCopy(v)
end
copy[k] = v
end
return copy
end
local function PrintTable(t)
for k, v in pairs(t) do
if v == "table" then
PrintTable(v)
else
print(k, v)
end
end
end
local base_table = {
width = 0,
height = 0,
x = 0,
y = 0,
SetSize = function(self, w, h)
self.width, self.height = w, h
end,
SetPos = function(self, x, y)
self.x, self.y = x,y
end
}
local tbl = {}
local cpy = deepCopy(base_table)
setmetatable(cpy, {__newindex = function(_, k, v) rawset(tbl, k, v) end})
setmetatable(tbl, {__index = cpy; __newindex = cpy})
PrintTable(tbl) -- prints nothing
tbl:SetSize(200, 200)
tbl.someproperty = "some value"
PrintTable(tbl) -- prints only someproperty
推荐阅读
- mysql - 相关模型的动态范围,然后按距离排序
- python - 如何将数组中的所有对象拆分为 2 列?
- javascript - 从react Native中的userEffect中的异步函数返回一个清理函数
- javascript - javascript onClick事件找不到循环php的ID
- python - 安装pyaudio后出现ModuleNotFoundError
- bash - printf 转义码未在 Bash 脚本中格式化
- uwp - Xbox One S 启动错误:尝试从零售模式切换到开发模式时,它崩溃并出现错误系列 E200
- php - XAMPP 使用 SQLServer 更新 MSSQL 中的表,注意:数组到字符串的转换
- javascript - 如何使用 JS join() 在数组元素之前附加自定义字符串
- javascript - 访问另一个元素内的元素 JavaScript 数据