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

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

未完待续......

相关推荐
纵有疾風起33 分钟前
C++——类和对象(3)
开发语言·c++·经验分享·开源
Full Stack Developme42 分钟前
java.text 包详解
java·开发语言·python
文火冰糖的硅基工坊1 小时前
[嵌入式系统-135]:主流AIOT智能体开发板
开发语言·嵌入式·cpu
yudiandian20142 小时前
02 Oracle JDK 下载及配置(解压缩版)
java·开发语言
要加油哦~2 小时前
JS | 知识点总结 - 原型链
开发语言·javascript·原型模式
鄃鳕2 小时前
python迭代器解包【python】
开发语言·python
new coder2 小时前
[c++语法学习]Day10:c++引用
开发语言·c++·学习
驰羽2 小时前
[GO]GORM 常用 Tag 速查手册
开发语言·后端·golang
Narcissiffo3 小时前
【C语言】str系列函数
c语言·开发语言
workflower3 小时前
软件工程与计算机科学的关系
开发语言·软件工程·团队开发·需求分析·个人开发·结对编程