asp如何做網(wǎng)站四川seo技術(shù)培訓
示例代碼
?《programming in lua》里有一個案例很詳細,就是寫一個集合類的table,其負責篩選出table中不重復的元素并組合成一個新的table。本人按照自己的方式默寫了一次,結(jié)果發(fā)現(xiàn)大差不差,代碼如下:
Set = {} --集合--創(chuàng)建一個新集合
function Set.new(t)local set = {}for k,v in ipairs(t) doset[v] = trueendreturn set
end--集合并運算
function Set.union(a,b)local res = Set.new({})for k,v in pairs(a) dores[k] = trueendfor k,v in pairs(b) dores[k] = trueendreturn res
end--集合交運算
function Set.intersection(a,b)local res = Set.new({})for k,v in pairs(a) doif b[k] thenres[k] = trueendendreturn res
end--集合轉(zhuǎn)成字符串
function Set.tostring(set)local res = "{"local temp = ""for k,v in pairs(set) dores=res..temp..ktemp = ","endres=res.."}"return res
endlocal set = Set.new({1,3,4,5,6,3,4,5})
local set2 = Set.new({3,5,7})
local intersectSet = Set.intersection(set,set2)
local unionSet = Set.union(set,set2)
print(Set.tostring(intersectSet)) --{3,5}
print(Set.tostring(unionSet)) --{1,3,4,5,6,7}
算術(shù)運算metamethod
將上面每個函數(shù)都改寫成metamethod的形式,相當于是運算符直接重載,而非顯式調(diào)用函數(shù)名,可以達到同樣的目的。賦值加法運算和乘法運算如下:
setmetatable(Set,{__add = Set.union,__mul = Set.intersection,
})--創(chuàng)建一個新集合
function Set.new(t)local set = {}setmetatable(set,getmetatable(Set))for k,v in ipairs(t) doset[v] = trueendreturn set
end
關(guān)系運算metamethod
常見的關(guān)系運算即等于、小于、大于、大于等于、小于等于,只需要等于、小于、小于等于中的其中兩個關(guān)系,即可推算出其他所有關(guān)系。如果是a大于b則是b小于等于a的運算;如果是a大于等于b則是b小于a的運算。在lua中給了三個關(guān)系運算metamethods:__eq(等于),__lt(小于),和__le(小于 等于)給關(guān)系運算符賦予特殊的含義。
于是為上面集合覆寫關(guān)系運算:
--小于等于
__le = function(a,b)for k,v in pairs(a) doif not b[k] thenreturn falseendendreturn true
end,
--等于
__eq = function(a,b)return a <= b and b <= a
end,
--小于
__lt = function(a,b)return a <= b and a ~= b
end
測試代碼如下:
local a = Set.new({1,3,4,5,6})
local b = Set.new({3,5})
print(a==b)--false
print(a<=b)--false
print(a>=b)--true
print(a<b)--false
print(a>b)--true
tostring
類似tostring函數(shù)也是有相應的metamethod供我們選擇的,比如上方的tostring函數(shù),可以設置metatable的元方法__tostring,這樣的話就直接print(set)即可了:
setmetatable(Set,{__add = Set.union,__mul = Set.intersection,__tostring = Set.tostring
})
print(intersectSet) --{3,5}
print(unionSet) --{1,3,4,5,6,7}