函数 String() 接收一个字符串 string,将其封装到一个表({value = s or ''})中,并将元表 mt 赋值给这个表。函数 mt.__add() 是一个元方法,它将字符串 b 添加到在 a.value 中找到的字符串后面 b 次。这行代码 print((s + ' There ' + ' World!').value ) 调用这个元方法两次。
__index 是另外一个事件。__index 的元方法每当表中不存在键值时就会被调用。下面是一个例子,它记住 (memoize) 函数的值:
-- code courtesy of Rici Lake, [email protected] function Memoize(func, t) return setmetatable( t or {}, {__index = function(t, k) local v = func(k); t[k] = v; return v; end &nb 页码:[1] [2] [3] [4] [5] [6] [7] 第1页、共7页 |