1. 程式人生 > >雲風大神部落格中的Lua實現面向物件

雲風大神部落格中的Lua實現面向物件

在 Lua 中實現面向物件

在 pil 中,lua 的作者推薦了一種方案來實現 OO,比較簡潔,但是我依然覺得有些繁瑣。

這裡給出一種更漂亮一點的解決方案:為了貼程式碼和修改方便,我把它貼在了 wiki 上。

Lua 中實現面向物件

在這個方案中,只定義了一個函式 class(super) ,用這個函式,我們就可以方便的在 lua 中定義類:

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(basetype) -- 定義一個類 test 繼承於 basetype

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 ,這個函式被過載了。

其實,實現多重繼承也並不複雜,這裡就不再展開了。更有意義的擴充套件可能是增加一個 dtor :)

ps. 這裡用了點小技巧,將 self 繫結到 closure 上,所以並不使用 a:hello 而是直接用 a.hello 呼叫成員函式。這個技巧並不非常有用,從效率角度上說,還是不用為好。