lua的元表是表的一個擴展,可以簡化表的一些操作。setmetatable
關鍵字是設置元表的核心操作。
__index
相當于建立索引,為查找表元素提供了方便。
Lua 查找一個表元素時的規則,其實就是如下 3 個步驟: (參考自https://blog.csdn.net/xocoder/article/details/9028347)
給出代碼實例:
other = {foo = 3}
t = setmetatable({}, {__index = other})
print(t.foo)mytable = setmetatable({key1 = "key2"}, {__index = function(mytable, key)if key == "key2" thenreturn "metatablevalue"else return nilendend
})print(mytable.key1)
print(mytable.key2)
函數的輸出是:
3
key2
metatablevalue
lua self,可以給表添加操作符號,以__add
為例子:
function table_maxn(t)local mn = 0for k, v in pairs(t) doif mn < k thenmn = kendendreturn mn
endmytable = setmetatable({1, 2, 3}, {__add = function(mytable, newtable)for i = 1, table_maxn(newtable) dotable.insert( mytable, table_maxn(mytable) + 1, newtable[i])endreturn mytableend
})secondtable = {4, 5, 6}
mytable = mytable + secondtablefor k, v in ipairs(mytable) doprint(k, v)
end
同樣的,函數以mytable
和`操作符后面的表作為輸入。還有其他的操作符號,可以查找對應的表數據。
__call
方法在lua調用一個值時進行調用,給出代碼實例:
function table_maxn(tb) local mn = 0for k, v in pairs(tb) doif k > mn thenmn = kendendreturn mn
end
mytable = setmetatable({1, 2, 3}, {__call = function(mytable, newtable)local sum = 0for i = 1, table_maxn(mytable) dosum = sum + mytable[i]endfor i = 1, table_maxn(newtable) do sum = sum + newtable[i]endreturn sumend
})newtable = {4, 5, 6}
print(mytable(newtable)) -- 輸出21
相當于一個元表本身就是一個函數了。
__tostring
用于改變元素的輸出方式,代碼實例:
mytable = setmetatable({10, 20, 30}, {__tostring = function(mytable)local sum = 0for k, v in pairs(mytable) dosum = sum + vendreturn sumend
})print(mytable) -- 輸出60
xlua框架、新建一個module1
的模塊,命名為model1.lua
module1 = {}
module1.constant = "This is constant"function module1.func1()print("public function")
endlocal function func2()print("This is a private function")
endfunction module1.func3()func2()
endreturn module1
新建main.lua
文件,內容如下:
local m = require("./module1")print(module1.constant) -- 報名調用
m.func1() -- 變量調用
module1.func3()
如果是加載C語言的動態鏈接庫,可以直接寫成:
local path = "/usr/local/lua/lib/mylua.so"
local f = loadlib(path, "luaopen_socket")
Lua中,一個類使用table表示的,同時還需要借助元表的技術,給出代碼實例:
Rectangle = {width = 0, height = 0}function Rectangle:new (o, width, height)o = o or {}setmetatable(o, self) -- 通過元表的方式,來確定新對象,也可以進行引用操作self.__index = selfself.width = width or 0self.height = height or 0return o
endfunction Rectangle: area ()return self.width * self.height
endrect = Rectangle:new(nil, 10, 20) -- 新建對象
print(rect:area()) -- 200rect1 = Rectangle:new(rect1, 20, 30) -- 傳遞對象的引用,同時改變對應的值
print(rect:area()) -- 600
print(rect1:area()) -- 600
print(rect.width) -- 20
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态