local tab = {} print(tab.key)
BaseClass = { base = 1, } DerivedClass = { derived = 2, } setmetatable(DerivedClass, BaseClass) print(DerivedClass.base)
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)
原文地址:http://blog.csdn.net/xufeng0991/article/details/43608713