尝试使用__index实现 继承
我一开始的做法
首先先来看看__index的其中作用:
- 当__index指向一张表时,其作用是,当子表找不到特定键的时候,就会去该表的元表( metatable )的__index所指定的的表去找 -
- 当__index指向一个函数时,则会调用那个函数,子表和查找的键会作为参数传递给函数
内心OS:既然嘛,那简单,继承应该这么写 :D
local t5 = {a5 = "found in t5" }
local t4 = {a4 = "found in t4", __index = t5 }
local t3 = {a3 = "found in t3", __index = t4 }
local t2 = {a2 = "found in t2", __index = t3 }
local t1 = { a1 = "found in t1" }
-- 设置各自的元表
setmetatable(t3, t4)
setmetatable(t2, t3)
setmetatable(t1, t2)
print(t1.a1) --能找到,
print(t1.a2) --找不到,因为t1没有,去到t1的元表(t2)的__index表(t3)去找,并不查找t2本身
print(t1.a3) --能找到,t3就是t1的元表所指向的__index表
print(t1.a4) --找不到,t1没有,去元表t2的index(t3)找,t3也没有,
-- 那就去到t3的元表(t4)指定的index(t5)里找,还是没有
print(t1.a5) --能找到,t5的属性能够被访问到
结果嘛,就是如注释那样输出的是以下结果
found in t1
nil
found in t3
nil
found in t5
正确的做法
事实上,在Lua里继承不应该这么写,而是通常以以下的方式出现
利用一个类似“匿名表”的东西承担中间者
local t5 = { a5 = "found in a5" }
local t4 = { a4 = "found in t4" }
local t3 = { a3 = "found in t3" }
local t2 = { a2 = "found in t2" }
local t1 = { a1 = "found in t1" }
setmetatable(t4, {__index = t5})
setmetatable(t3, {__index = t4})
setmetatable(t2, {__index = t3})
setmetatable(t1, {__index = t2})
print(t1.a1) --
print(t1.a2) --
print(t1.a3) --
print(t1.a4) --
print(t1.a5) --
这个时候输出结果就是我预期的那样了
found in t1
found in t2
found in t3
found in t4
found in t5
在文章最后
嘿,谢谢你没让我的博客变成一片荒凉的沙漠,你的访问是我博客的绿洲。
本人目前是学生党nie,第一次写博客(日记?),学Lua也是因为Unity的热更新需要,顺手练练md,文章可能写的比较仓促,如果对文章有什么建议欢迎在评论区指出。 :)