kenlistian

勤学多思

  IT博客 :: 首页 :: 新随笔 ::  :: 聚合  :: 管理 ::
  412 随笔 :: 0 文章 :: 23 评论 :: 0 Trackbacks

Lua中的元表( metatable)概念

元表 是一个(普通的)Lua 表,它将标准操作映射成自定义的函数。类似于操作符重定义。
元表的键值称为事件;值(换而言之就是函数)称为元方法

 setmetatable()getmetatable() 分别对对象的元表进行修改和查询。每个表和 userdada 对象都可以具有自己的元表。其他的则没有元表之一说。
引入元表的好处,其实就像是c++中的sturct,在定义了数据类型后,还可以附加一些对数据的操作。

在lua中某个表需要对其元表做相应的增添 add 方法;方法:

mt = {}
function String(string)
  --对{value = s or ''}增添mt元表
  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 ' + ' World!').value )
result :

Hello There World!
函数 mt.__add() 是一个元方法,它将字符串 b 添加到在 a.value 中找到的字符串后面 b 次。这行代码 print((s + ' There ' + ' World!').value ) 调用这个元方法两次。

__index 是另外一个事件。__index 的元方法是当表中不存在键值时就会被调用。

那么下面的代码应该是看得懂的:

-- catch "undefined" global variables

local f=function (t,i)
  error("undefined global variable `"..i.."'",2)
end
setmetatable(getfenv(),{__index=f})

-- an example
a=1
c=3
print(a,b,c) -- `b' is undefined

posted on 2007-04-25 12:18 kenlistian 阅读(1004) 评论(0)  编辑 收藏 引用
只有注册用户登录后才能发表评论。