元表的学习
为表添加操作符
直接看栗子:
function table_maxn(t)
local mn = 0
for k, v in pairs(t) do
if mn < k then
mn = k
end
end
return mn
end
-- 两表相加操作
mytable = setmetatable({ 1, 2, 3 }, {
__add = function(mytable, newtable)
for i = 1, table_maxn(newtable) do
table.insert(mytable, table_maxn(mytable)+1,newtable[i])
end
return mytable
end
})
secondtable = {4,5,6}
mytable = mytable + secondtable
for k,v in ipairs(mytable) do
print(k,v)
end
本文主要探讨了Lua中的元表概念,如何为表添加操作符,并通过实例代码展示了元表的使用,帮助读者理解这一核心特性。

1263

被折叠的 条评论
为什么被折叠?



