local tab = {}
print(tab.key)
BaseClass = {
base = 1,
}
DerivedClass = {
derived = 2,
}
setmetatable(DerivedClass, BaseClass)
print(DerivedClass.base)
已经设置了元表,还是找不到,这是为什么呢?往下看!
示例
BaseClass = {
base = 1,
}
BaseClass.__index = BaseClass
DerivedClass = {
derived = 2,
}
setmetatable(DerivedClass, BaseClass)
print(DerivedClass.base)
输出:
BaseClass = {
base = 1
}
BaseClass.__index = function(tab, key)
if key == "fun" then
return 1
else
return 0
end
end
DerivedClass = {
derived = 2,
}
setmetatable(DerivedClass, BaseClass)
print(DerivedClass.fun)
输出:
BaseClass = {
base = 1,
}
DerivedClass = setmetatable({derived = 2}, {__index = BaseClass})
print(DerivedClass.base)
-------------------------------------------------------------------------
BaseClass = {
base = 1,
}
DerivedClass = setmetatable({derived = 2}, {__index = function(tab, key)
if key == "fun" then
return 1
else
return 0
end
end})
print(DerivedClass.fun)
BaseClass = {
base = 1,
}
BaseClass.__index = BaseClass
NewElement = {}
BaseClass.__newindex = NewElement
DerivedClass = {
derived = 2,
}
setmetatable(DerivedClass, BaseClass)
DerivedClass.new = 1
print(BaseClass.new)
print(NewElement.new)
print(DerivedClass.new)
BaseClass = {}
BaseClass.__call = function (BaseClass, a, b)
return a + b;
end
DerivedClass = {
derived = 2,
}
setmetatable(DerivedClass, BaseClass)
print(DerivedClass(1, 2))
输出:
BaseClass = {}
BaseClass.__tostring = function (BaseClass)
local str = "-"
for k, v in pairs(BaseClass) do
str = str..">"..k..":"..v..""
end
return str
end
DerivedClass = {
className = "DerivedClass",
derived = 2,
}
setmetatable(DerivedClass, BaseClass)
print(DerivedClass)