LUA Metatables

简介:

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

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

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
__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
本文转自jiahuafu博客园博客,原文链接http://www.cnblogs.com/jiahuafu/p/6824734.html如需转载请自行联系原作者

jiahuafu

相关文章
|
1月前
Lua
Lua
13 0
|
10月前
|
Ubuntu 云计算 C++
C++与lua的结合,LuaBridge的使用及遇到的坑
C++与lua的结合,LuaBridge的使用及遇到的坑
Lua 函数
Lua 函数
163 0
Lua 函数
LUA Metatables
__index:当我们访问一个表中的元素不存在时,则会触发去寻找__index元方法,如果不存在,则返回nil,如果存在,则返回结果。   博主注:__index有点像异常处理的意思   __newindex: 当给你的表中不存在的值进行赋值时,lua解释器则会寻找__newindex元方法,发现存在该方法,则执行该方法进行赋值,注意,是使用rawset来进行赋值,至于原因,后面会讲到。
|
API Go
Lua相关的知识
http://stackoverflow.com/questions/5438751/how-to-debug-lua-remotely http://cn.bing.com/search?q=org.
895 0