国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

理解Lua中的__index和__newindex

2024-07-21 23:04:37
字體:
來源:轉載
供稿:網友

 

復制代碼 代碼如下:

--example: 
local temp_table ={ 
    10, 
    1, 
    Index1 = "hello", 
    Index2 = "world", 
    Index3 = "lua", 
    Index4 = "language", 
    lang = "lua language", 

 
temp_table.__add = function(a, b) return 3 end 
 
 
for _, Value in pairs(temp_table) do 
    print(Value) 
end 
 
local temp_metable_table = { 
    Index1 = "temp_new_metable_Index1", 
    Index2 = "temp_new_metable_Index2", 
    Key = "temp_new_metable_Key_end", 

 
 
for _, Metable_Value in pairs(temp_metable_table) do 
    print(Metable_Value) 
end 
--只能訪問temp_table的方法 
--setmetatable(temp_metable_table,  temp_table) --如果setmetable 為這種方式的話,那么我不能夠對metable進行原子操作 
--print(temp_metable_table + temp_table) 
 
--如果是這種方式的話,我們只能訪問它的原子,也就是它的數據成員 
--[[setmetatable(temp_metable_table, {__index = temp_table} )  
 
print(temp_metable_table[1]) 
print(temp_metable_table["lang"])--]] 
 
--如果是__newindex的話,我們可以訪問原table,找到相關的key,除此之外,你還可以自己給原table添加數據成員 
setmetatable(temp_metable_table, {__newindex = temp_table} )  
temp_metable_table[5] = 100 
print(temp_metable_table[5]) 
print(temp_table[5]) 

 

 

復制代碼 代碼如下:

Window = {} 
 
Window.prototype = {x = 0 ,y = 0 ,width = 100 ,height = 100,} 
Window.mt = {} 
function Window.new(o) 
    setmetatable(o ,Window.mt) 
    print(getmetatable(o)) 
    print(getmetatable(Window.mt)) 
    return o 
end 
 
Window.mt.__index = function (t ,key) //由于__index 給賦予了funcion,一個匿名函數 
    -- body 
    return 1000 
end 
 
w = Window.new({x = 10 ,y = 20}) 
print(w.a) //在這里雖然沒有a這個成員,但是會默認a為__index所綁定的function返回值作為a的值 

 

 

復制代碼 代碼如下:

Window = {} 
Window.mt = {} 
 
function Window.new(o) 
    setmetatable(o ,Window.mt) 
    return o 
end 
Window.mt.__index = function (t ,key) 
    return 1000 
end 
Window.mt.__newindex = function (table ,key ,value) 
    if key == "wangbin" then 
        rawset(table ,"wangbin" ,"yes,i am") 
    end 
end 
w = Window.new{x = 10 ,y = 20} 
w.wangbin = "55" 
print(w.wangbin) 

總結:
如果在元table中去找相應的操作,例如__index,__newindex等,如果有則直接訪問,如果沒有就新添加進元table中
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 昌江| 安图县| 凌源市| 乐业县| 新竹县| 彭阳县| 同心县| 通许县| 南开区| 永兴县| 多伦县| 雅安市| 凉山| 辛集市| 凤台县| 湖南省| 福建省| 荆门市| 曲松县| 淅川县| 都昌县| 宿州市| 交城县| 清新县| 湖州市| 阿克| 老河口市| 襄垣县| 沭阳县| 建水县| 泰宁县| 淮阳县| 峨山| 安阳县| 来凤县| 鸡东县| 志丹县| 巩义市| 武山县| 青阳县| 姜堰市|