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

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

未完待续......

相关推荐
小短腿的代码世界几秒前
从KB到字节:Qt行情数据压缩与传输优化的全链路透视——LZ4、Snappy与自定义二进制协议的极限压榨
开发语言·qt
灵机一物16 分钟前
灵机一物AI原生电商小程序、PC端(已上线)-【技术深度解析】Bun 6 天 AI 重写 96 万行代码:从 Zig 迁移 Rust 全流程与行业影响
开发语言·人工智能·rust
Nontee17 分钟前
Java 后端面试题目全集
java·开发语言·面试
lsx20240621 分钟前
CSS 选择器
开发语言
Chase_______38 分钟前
【Java杂项】0.1 + 0.2 为什么不等于 0.3?IEEE 754 与 BigDecimal 精度避坑
java·开发语言·python
ch.ju40 分钟前
Java Programming Chapter 4——Static part
java·开发语言
geovindu41 分钟前
python: Monitor Pattern
开发语言·python·设计模式·监控模式
之歆43 分钟前
DAY_11JavaScript BOM与DOM深度解析:底层原理与工程实践(上)
开发语言·前端·javascript·ecmascript
会编程的土豆1 小时前
Go ini 配置加载:`ini.MapTo` 详细解析
开发语言·数据库·golang
ChoSeitaku1 小时前
04.数组
java·开发语言·数据结构