1. 程式人生 > >【Lua學習筆記】 Lua中實現面向物件,轉自雲風的部落格

【Lua學習筆記】 Lua中實現面向物件,轉自雲風的部落格

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
			setmetatable(obj,{ __index=_class[class_type] })
			return obj
		end
	local vtbl={}
	_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
--現在,我們來看看怎麼使用:
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

--以上是基本的 class 定義的語法,完全相容 lua 的程式設計習慣。我增加了一個叫做 ctor 的詞,作為建構函式的名字。
--下面看看怎樣繼承:
test=class(base_type)	-- 定義一個類 test 繼承於 base_type
 
function test:ctor()	-- 定義 test 的建構函式
	print("test ctor")
end
 
function test:hello()	-- 過載 base_type:hello 為 test:hello
	print("hello test")
end

--現在可以試一下了:
a=test.new(1)	-- 輸出兩行,base_type ctor 和 test ctor 。這個物件被正確的構造了。
a:print_x()	-- 輸出 1 ,這個是基類 base_type 中的成員函式。
a:hello()	-- 輸出 hello test ,這個函式被過載了。