Lua中表和Metatables之间的差异
Corona中表和元表之间有什么区别? metatables有哪些类型?我如何以及在何处使用它们?使用表和元表的主要目的是什么?
解决方法
Lua(Corona所基于的语言)将metatable用于不同的目的.
手册中的相关条目是Section 2.8. metatable只是一个像其他任何表一样的表,但是在另一个表上设置为metatable(我将进一步称之为基表,以区分两个表). metatable可以包含任何内容,但特殊键(以双下划线开头)是有趣的.在此表中设置为此键的值将在特殊情况下调用.哪个场合取决于哪??个键.最有趣的是: > __index:只要查找基表中的键但不存在,就会使用它.这可以包含表,其中将查找键,或者一个函数,它将传递原始表和键.这可以用于实现表上的方法(OOP样式),重定向,通过案例,设置默认值等 使用__index&时需要了解一件小事. co.:在这些方法中,你应该使用rawget和rawset以防止每次再调用metamethod,从而导致循环. t={1,2,3} -- basetable mt={} -- metatable mt.__index=function(t,k) print("__index event from "..tostring(t).." key "..k) return "currently unavailable" end mt.__newindex=function(t,k,v) print("__newindex event from "..tostring(t).." key: "..k.." value: "..v) if type(k)=="string" then rawset(t,v:reverse()) else rawset(t,v) end end mt.__call=function(t,...) print("call to table "..tostring(t).." with arguments: ".. table.concat({...},',')) print("All elements of the table:") for k,v in pairs(t) do print(k,v) end end setmetatable(t,mt) t[4]="foo" -- this will run the __newindex method print(t[5]) -- this will run the __index method t("foo","bar") -- Multiple fall through example: t={} mt={} mt2={} setmetatable(t,mt) -- metatable on base table setmetatable(mt,mt2) -- second layer of metatable mt.__index=function(t,k) print('key '..k..' not found in '..namelookup[t]) return getmetatable(t)[k] end -- tries looking nonexistant indexes up in mt. mt2.__index=mt.__index -- function was written portably,reuse it. t[1]='A' mt[2]='B' mt2[3]='C' namelookup={[t]="t",[mt]="mt",[mt2]="mt2"} print(t[1],t[2],t[3],t[4]) 现在这些只是愚蠢的例子,你可以做更复杂的事情.看看这些例子,看看Programming in Lua的相关章节,并进行实验.并尽量不要混淆;) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |