LUA Metatables

本文深入探讨了Lua语言中的元方法__index和__newindex的工作原理及其应用场景。通过具体实例展示了如何利用这些元方法实现表的查找和赋值操作,同时介绍了rawget和rawset函数的用途。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

__index:当我们访问一个表中的元素不存在时,则会触发去寻找__index元方法,如果不存在,则返回nil,如果存在,则返回结果。

 

博主注:__index有点像异常处理的意思

 

__newindex: 当给你的表中不存在的值进行赋值时,lua解释器则会寻找__newindex元方法,发现存在该方法,则执行该方法进行赋值,注意,是使用rawset来进行赋值,至于原因,后面会讲到。

rawget: 是为了绕过__index而出现的,直接点,就是让__index方法的重写无效,可以理解为单纯的获取本表而不关联到父表(元表)(我这里用到"重写"二字,可能不太对,希望能得到纠正)

rawset: 设置表[索引]值,真正的值没有调用任何元方法。表必须是一个表,索引从不同的无任何值,Lua的任何值。这个函数返回表

 

__index
This is a very commonly used and versatile metamethod, it lets you run a custom function or use a "fallback" table if a key in a table doesn't exist. If a function is used, its first parameter will be the table that the lookup failed on, and the second parameter will be the key. If a fallback table is used, remember that it can trigger an __index metamethod on it if it has one, so you can create long chains of fallback tables. 


local func_example = setmetatable({}, {__index = function (t, k)  -- {} an empty table, and after the comma, a custom function failsafe
  return "key doesn't exist"
end})

local fallback_tbl = setmetatable({   -- some keys and values present, together with a fallback failsafe
  foo = "bar",
  [123] = 456,
}, {__index=func_example})

local fallback_example = setmetatable({}, {__index=fallback_tbl})  -- {} again an empty table, but this time with a fallback failsafe

print(func_example[1]) --> key doesn't exist
print(fallback_example.foo) --> bar
print(fallback_example[123]) --> 456
print(fallback_example[456]) --> key doesn't exist

  

 

http://lua-users.org/wiki/MetamethodsTutorial

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值