Lua 元表的创建和使用
示例
一个元表定义了一组改变lua对象行为的操作。一个元表只是一个普通的表,它以一种特殊的方式使用。
local meta = { } -- create a table for use as metatable
-- a metatable can change the behaviour of many things
-- here we modify the 'tostring' operation:
-- this fields should be a function with one argument.
-- it gets called with the respective object and should return a string
meta.__tostring = function (object)
return string.format("{ %d, %d }", object.x, object.y)
end
-- create an object
local point = { x = 13, y = -2 }
-- set the metatable
setmetatable(point, meta)
-- since 'print' calls 'tostring', we can use it directly:
print(point) -- prints '{ 13, -2 }'
热门推荐
10 幽默的伴郎祝福语简短
11 收到乔迁礼物祝福语简短
12 新娘妈妈祝福语简短的
13 关于孩子毕业祝福语简短
14 托班调皮祝福语简短
15 明天早上祝福语简短的话
16 结婚祝福语嫂子的话简短
17 送媳妇首饰祝福语简短
18 小升初考试后祝福语简短