lua __call元方法


function table_max_index(t)
        local max_index = 0
        for k, v in pairs(t) do
                if max_index < k then
                        max_index = k
                end
        end
        return max_index
end

mytable = setmetatable({10}, {
__call = function(mytable, newtable)
                sum = 0
                for i = 1, table_max_index(mytable) do
                        sum = sum + mytable[i]
                end

                for i = 1, table_max_index(newtable) do
                        sum = sum + newtable[i]
                end
                return sum
        end
})

newtable = {10, 20, 30}
print(mytable(newtable))

對兩個表里的所有元素求和。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM