现在的位置: 首页 > 综合 > 正文

Lua面向对象设计中添加super

2013年07月05日 ⁄ 综合 ⁄ 共 1994字 ⁄ 字号 评论关闭

云风的lua oo 实现方法 http://blog.codingnow.com/2006/06/oo_lua.html

无法在子类的函数中使用super:xxx 调用父类的函数。

1.直接用父类调用

base_type=class()        -- 定义一个基类 base_type
function base_type:ctor(x)    -- 定义 base_type 的构造函数
    print("base_type ctor")
    self.x=x
end
function base_type:print_x()    -- 定义一个成员函数 base_type:print_x
    print(self.x)
end
function base_type:hello()    -- 定义另一个成员函数 base_type:hello
    print("hello base_type")
end

test=class(base_type)    -- 定义一个类 test 继承于 base_type
function test:ctor()    -- 定义 test 的构造函数
    print("test ctor")
end
function test:hello()    -- 重载 base_type:hello 为 test:hello
    base_type.hello(self)
    print("hello test")
end

test1=class(base_type)    -- 定义一个类 test 继承于 base_type

local test1obj = test1.new()
test1obj:hello()

2.

local _class={}

function class(super)
	local class_type={}
	class_type.ctor=false
	class_type.super=super
	class_type.new=function(...)
			local obj={}
			do
				local create
				create = function(c,...)
					if c.super then
						create(c.super,...)
					end
					if c.ctor then
						c.ctor(obj,...)
					end
				end

				create(class_type,...)
			end
			--obj.super = _class[super]--1
			setmetatable(obj,{ __index=_class[class_type] })
			return obj
		end
	local vtbl={}
        vtbl.super = _class[super]--2
        _class[class_type]=vtbl

	setmetatable(class_type,{__newindex=
		function(t,k,v)
			vtbl[k]=v
		end
	})

	if super then
		setmetatable(vtbl,{__index=
			function(t,k)
				local ret=_class[super][k]
				vtbl[k]=ret
				return ret
			end
		})
	end

	return class_type
end

目前我只想到在new函数中插一句obj.super = _class[super]

后来又想到可以把super放vtbl中,vtbl.super = _class[super]。这样占用空间少点,不用每个对象设置super。不过改变了一个既定规则,就是vtbl中都是函数。

使用方法:self.super.xxx(self,....)。不能采用self.super:xxx()。

function test:hello()	-- 重载 base_type:hello 为 test:hello
	self.super.hello(self)
	print("hello test")
end

假如test1 继承 test ,test 继承base_type。test1没定义hello,调用test1obj:hello()。

_class[test1]  =  vbtl,  这个vbtl.super  是_class[test]

但是结果却不如愿,因为这里self是test1的对象,test1没定义hello。

于是test1的vbtl去super 找,于是slef.super是test,而不是我们所期望的base_type。

test:hello()里面套了test:hello(),就形成无限循环崩掉了。

3.

super不应该从属于对象,而应该是类。所以self.super应该改成test.super。

test.super其实就是class_type.super,已经被占用了。只能另外用class_type.superclass了。

class()定义中加入  class_type.superclass = _class[super]

调用时为  test.superclass.hello(self)

抱歉!评论已关闭.