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

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

未完待续......

相关推荐
sugarzhangnotes24 分钟前
【无标题】
开发语言·人工智能·python
geovindu27 分钟前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
周杰偷奶茶2 小时前
【Java】数组的定义和使用(附管理系统实战案例)
java·开发语言
橙子圆1232 小时前
JUC之集合类不安全
java·开发语言
阿里嘎多学长3 小时前
2026-09-29 GitHub 热点项目精选
开发语言·程序员·github·代码托管
Bruce_Liuxiaowei3 小时前
网页版 DeepSeek “harness desktop“ WebGL 上下文创建失败排查实录
开发语言·javascript·webgl
狗凯之家源码网3 小时前
PHP 用户反馈系统源码深度评测与实战指南
开发语言·php·用户反馈系统
白山编程大哥3 小时前
Lua 中使用 C 语言的用户自定义类型——userdata
c语言·junit·lua
谢亮_vipxieliang3 小时前
Stream API 不是银弹:常见坑与性能建议
java·开发语言
迅猛龙办公室4 小时前
实现第一个python程序(HelloWorld)
开发语言·python