日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LUA Metatables

發布時間:2024/8/26 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。