簡介
模塊庫類似一個(gè)封裝庫锅锨,存放公用代碼,以api接口形式被其他調(diào)用
-- module.lua模塊
-- 定義模塊
module={}
-- 定義常量
module.a=1
-- 定義公有函數(shù)
function module.fun1()
print("public");
end
-- 定義私有函數(shù)
local function module.fun2()
print("private");
end
-- return
return module
-- test.lua調(diào)用
require("module")
module.fun1()
元表
元表(metatable)提供兩個(gè)table之間的操作
-
set:將table設(shè)置為元表 (若元表存在_metatable鍵值 則設(shè)置失斔洳选)
mytable={} --普通表 metatable={} --元表 setmetatable(mytable,metatable) --設(shè)置為元表
-
get:獲取對(duì)象的元表
getmetatable(mytable)
元方法
-
__index
:訪問表橡类,表中沒有對(duì)應(yīng)值時(shí),去元表的__index
中找(__table
可以是表包含很多)t1={a=1,b=2}; t2={}; setmetatable(t1,t2); print(t1.c); -- 包含表 t3={a=1,b=2}; t4={__index={c=3}}; setmetatable(t3,t4); print(t3.c); -- 包含函數(shù)(function注意包含t6參數(shù)) t5={a=1,b=2}; t6={__index= function(t6,key) if(key=="c") then return 3; else return nil; end end }; setmetatable(t5,t6); print(t5.c); -- 或者寫法 t7={a=1,b=2}; setmetatable(t7,{__index={c=3}}); print(t7.c);
-
__newindex
:更新表芽唇,賦值對(duì)應(yīng)鍵值顾画,若沒有,就會(huì)去元表的__newindex
中找m={d=4}; meta={__newindex=m}; mytable={a=1,b=2}; setmetatable(mytable,meta); mytable.c=3; -- 將c鍵值加到m中 print(mytable.c,m.c,mytable.d,m.d); -- nil 3 nil 4 m={d=4}; meta={__newindex=m,__index=m}; mytable={a=1,b=2}; setmetatable(mytable,meta); mytable.c=3; -- 將c鍵值加到m中 此刻m含有c鍵值 print(mytable.c,m.c,mytable.d,m.d); -- 3 3 4 4 -- 或者寫法 m={d=4}; mytable={a=1,b=2}; setmetatable(mytable,{__newindex=m,__index=m}); mytable.c=3; print(mytable.c,m.c,mytable.d,m.d);
-
rawget rawset:rawget可以直接獲取索引實(shí)際值匆笤,不通過
__index
元方法 rawset可以直接對(duì)表中索引賦值研侣,不通過__newindex
元方法-- rawget調(diào)用方式不同 t7={a=1,b=2}; setmetatable(t7,{__index={c=3}}); --print((t7.c)); print(rawget(t7,c)); -- rawset賦值方式不同 m={}; mytable={a=1,b=2}; setmetatable(mytable,{__newindex=m}); --mytable.c=3; rawset(mytable,"c",3); print(mytable.c,m.c);
-
操作符:就是對(duì)應(yīng)符號(hào)對(duì)應(yīng)的”__名字“,主要還是對(duì)應(yīng)操作符后面寫的方法
mytable={a=1,b=2,c=3}; meta={__add= function(first,second) for k,v in pairs(second) do table.insert(first,v); end return first; -- 元表就是一個(gè)操作 end } mytable = setmetatable(mytable,meta) secondtable={d=4,e=5,f=6}; mytable=mytable+secondtable; for k,v in pairs(mytable) do print(v); end --[[ 對(duì)應(yīng)其他的操作 + => __add -(減號(hào)) => __sub * => __mul / => __div % => __mod -(負(fù)號(hào)) => __unm .. => __concat == => __eq < => __lt <= => __le ]]
-
__call:在Lua調(diào)用一個(gè)值時(shí)調(diào)用炮捧,就是調(diào)用每個(gè)值可能要進(jìn)行統(tǒng)一操作
mytable={"111","222"}; meta={__call= function(first,a) return("id="..a.." is "..first[a]); end } mytable=setmetatable(mytable,meta) print(mytable(2));
-
__tostring:修改表的輸出行為
mytable={"111","222"}; meta={__tostring= function(first) for k,v in ipairs(first) do return("id="..k.." is "..v); end end } setmetatable(mytable,meta) print(mytable);
總結(jié)
- meta元表代表的是一種操作庶诡,放在其他地方也這樣寫,與具體的表無關(guān)
- meta元表可以做很多操作咆课,命名不同末誓,具體做什么在function里面實(shí)現(xiàn)
- meta元表可以做很多初始化或者類似構(gòu)造函數(shù)的功能,面向?qū)ο缶幊?/li>
- pairs:是迭代器的元方法书蚪,__pairs