LUA Metatables
生活随笔
收集整理的這篇文章主要介紹了
LUA Metatables
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
__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 failsafereturn "key doesn't exist" end})local fallback_tbl = setmetatable({ -- some keys and values present, together with a fallback failsafefoo = "bar",[123] = 456, }, {__index=func_example})local fallback_example = setmetatable({}, {__index=fallback_tbl}) -- {} again an empty table, but this time with a fallback failsafeprint(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
轉載于:https://www.cnblogs.com/jiahuafu/p/6824734.html
總結
以上是生活随笔為你收集整理的LUA Metatables的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Andorid ListView使用技巧
- 下一篇: 关于box-shadow、border-