Lua 通过元方法简单实现属性Get/Set访问

通过元方法__index、__newindex、rawset,我们可以实现属性的Get/Set访问,类似于C#:

csharp 复制代码
public string name;
public string Name
{
    get => name;
    set => name = value;
}

方法一:将属性数据存在元表中

lua 复制代码
local meta = { name = "meta" }
meta.__index = function(self, key)
	print("Get Key = " .. tostring(key))
	return meta[key]
end
meta.__newindex = function(self, key, value)
	print("Set Key = " .. tostring(key) .. " , value = " .. tostring(value))
	meta[key] = value
end
local table = {}
setmetatable(table, meta)
print("------ 1 ------")
print(table.name)
print("------ 2 ------")
table.name = "table"
print("------ 3 ------")
print(table.name)

---输出结果:
-- ------ 1 ------
-- Get Key = name
-- meta
-- ------ 2 ------
-- Set Key = name , value = table
-- ------ 3 ------
-- Get Key = name
-- table

__index 可视为该table中所有属性的Get方法,通过参数Key区分不同的属性;
__newindex 可视为该table中所有属性的Set方法,通过参数Key区分不同的属性;

该方法的局限性在于,子表不得绕过元方法对属性进行修改(比如通过 rawset 方法),这是为了防止:因为子表有对应的属性,而无法触发到元表的 __index 方法

这也意味着,之后对于子表所有的属性获取与修改,都会反馈到元表上,子表永远都会是个空的table

方法二:将属性数据存在子表中

lua 复制代码
local meta = {
	__index = function(self, key)
		print("Get Key = " .. tostring(key))
		return self._TEMP_META_DATA_[key]
	end,
	__newindex = function(self, key, value)
		print("Set Key = " .. tostring(key) .. " , value = " .. tostring(value))
		rawset(self._TEMP_META_DATA_, key, value)
	end,
}
local table = {}
table._TEMP_META_DATA_ = {}
setmetatable(table, meta)
print("------ 1 ------")
print(table.name)
print("------ 2 ------")
table.name = 5
print("------ 3 ------")
print(table.name)

---输出结果:
-- ------ 1 ------
-- Get Key = name
-- 
-- ------ 2 ------
-- Set Key = name , value = 5
-- ------ 3 ------
-- Get Key = name
-- 5

该方法的优势在于,对子表的修改都能反馈到子表上,并由此可以衍生许多进阶写法

未完待续......

相关推荐
怀旧,18 小时前
【C++】20. unordered_set和unordered_map
开发语言·c++
alibli18 小时前
一文学会CMakeLists.txt: CMake现代C++跨平台工程化实战
开发语言·c++·系统架构
Florence2319 小时前
GPU硬件架构和配置的理解
开发语言
李游Leo19 小时前
JavaScript事件机制与性能优化:防抖 / 节流 / 事件委托 / Passive Event Listeners 全解析
开发语言·javascript·性能优化
JJJJ_iii20 小时前
【左程云算法09】栈的入门题目-最小栈
java·开发语言·数据结构·算法·时间复杂度
枫叶丹420 小时前
【Qt开发】显示类控件(三)-> QProgressBar
开发语言·qt
Bear on Toilet20 小时前
继承类模板:函数未在模板定义上下文中声明,只能通过实例化上下文中参数相关的查找找到
开发语言·javascript·c++·算法·继承
码猿宝宝20 小时前
浏览器中javascript时间线,从加载到执行
开发语言·javascript·ecmascript
OEC小胖胖20 小时前
App Router vs. Pages Router:我应该如何选择?
开发语言·前端·前端框架·web·next.js
max50060021 小时前
OpenSTL PredRNNv2 模型复现与自定义数据集训练
开发语言·人工智能·python·深度学习·算法