lua metatables中操作__index
lua metatables中操作__index
andrew810810 发表于8个月前
lua metatables中操作__index
  • 发表于 8个月前
  • 阅读 2
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 十分钟定制你的第一个小程序>>>   

reference:

http://www.lua.org/manual/5.3/manual.html

__indexThe indexing access table[key]. This event happens when table is not a table or when key is not present in table. The metamethod is looked up in table.

Despite the name, the metamethod for this event can be either a function or a table. If it is a function, it is called with table and key as arguments, and the result of the call (adjusted to one value) is the result of the operation. If it is a table, the final result is the result of indexing this table with key. (This indexing is regular, not raw, and therefore can trigger another metamethod.)

 

__index这个重载,主要是重载了find key的操作,这操作可以让Lua变得有点面向对象的感觉。 所谓__index,说得明确一点,如果我们有两个对象a和b,我们想让b作为a的prototype只需要:

setmetatable(a, {__index = b})

 

metamethod 为function

示例:

Window_Prototype = {x=0, y=0, width=100, height=100}
MyWin = {title="Hello"}
Window = {}
Window.__index = function(table, key)
  return Window_Prototype[key]
end
setmetatable(MyWin,Window)
print(MyWin.title, MyWin.width)

执行结果:

Hello	100

metamethod 为table

Window_Prototype = {x=0, y=0, width=100, height=100}
MyWin = {title="Hello"}
Window = {}
Window.__index = Window_Prototype
setmetatable(MyWin,Window)

print(MyWin.title, MyWin.width)

执行结果:

Hello	100

metamethod 为table简洁的书写方式:

Window_Prototype = {x=0, y=0, width=100, height=100}
MyWin = {title="Hello"}
setmetatable(MyWin, {__index = Window_Prototype})

print(MyWin.title, MyWin.width)

 

标签: Lua
共有 人打赏支持
粉丝 4
博文 127
码字总数 117648
×
andrew810810
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: