Lua实现面向对象方法大概整理了一些,分为以下两种方法:
官方做法:
实现类:
local Class= { value=0 } function Class:new(o) o=o or {}; setmetatable(o,self); self.__index=self; return o; end function Class:showmsg() print(self.value); end local test = Class:new(); test:showmsg();接着上面实现继承
local A = Class:new(); function A:new(o) local o = o or {}; setmetatable(o,self); self.__index=self; return o; end function A:showmsg( ) print (self.value); print("zhishi 测试啊啊 ") end local s = A:new({value=100}); s:showmsg();结果:
0 100 zhishi 测试啊啊一种更优雅的实现方式:
class.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下面看下使用:
定义一个类:
test=class() -- 定义一个基类 base_type function test:ctor(x) -- 定义 base_type 的构造函数 print("test ctor") self.x=x end function test:print_x() -- 定义一个成员函数 test:print_x print(self.x) end function test:hello() -- 定义另一个成员函数 test:hello print("hello test") end --调用方法 test.new(1); test:print_x(); test:hello();继承的实现:
base=class() -- 定义一个基类 base_type function base:ctor(x) -- 定义 base_type 的构造函数 print("base ctor") self.x=x end function base:print_x() -- 定义一个成员函数 base:print_x print(self.x) end function base:hello() -- 定义另一个成员函数 base:hello print("hello base") end --子类实现 child=class(base); function child:ctor() print("child ctor"); end function child:hello() print("hello child") end --调用 local a=child.new(21); a:print_x(); a:hello();两种方式各有优缺点,看自己了,不明白的地方留言交流。。。