Created
August 11, 2017 17:15
-
-
Save defp/6356e5ae51bdbfc3d0d3e42538e11228 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local a = { | |
field1 = 1 | |
} | |
local b = { | |
field2 = 2 | |
} | |
-- 声明表a b | |
-- 设置 a 的元表是 b | |
setmetatable(a, b) | |
print(a.field1) -- 1 | |
print(a.field2) -- nil, field2是 表b的,a现在并不会查找元表b,元表中未定义__index方法 | |
b.__index = b -- 设置b的__index 为 b | |
print(a.field2) -- 2 打印2,因为设置__index为b,a中没有field2,从__index设置的表b查找 | |
-- __index 也可以设置成函数,当被它调用时,会把被访问的表和索引作为参数传入 | |
b.__index = function(t, key) | |
print(key) -- 打印访问的key | |
return t.field1 -- 写死返回field1 | |
end | |
-- 结果 | |
-- field2 | |
-- 1 | |
-- __index 为函数,访问key是field2,访问的表是a,返回filed1,值为1 | |
print(a.field2) | |
-- 结果 | |
-- field3 | |
-- 1 | |
print(a.field3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment