供的函数。元表的键值称为事件;值(换而言之就是函数)称为元方法。
函数 setmetatable() 和 getmetatable() 分别对对象的元表进行修改和查询。每个表和 userdada 对象都可以具有自己的元表。
例如,添加操作对应的事件是 __add。我们可以推断这段代码所做的事情么?
-- Overload the add operation -- to do string concatenation -- mt = {}
function String(string) return setmetatable({value = string or ''}, mt) end
-- The first operand is a String table -- The second operand is a string -- .. is the Lua concatenate operator -- function mt.__add(a, b) return String(a.value..b) end
s = String('Hello') print((s + ' There 页码:[1] [2] [3] [4] [5] [6] [7] 第6页、共7页 |