簡單的類別
功能包含
public function
private functionc
constructor
程式碼:
程式碼: main.lua
local dog = require "Dog" --引入類別
local BigDog = dog.New( "Apple" , 10 ) --創建物件
local SmallDog = dog.New( "Orange" , 4 )
BigDog:Bark()
BigDog:PrintAge()
SmallDog:Bark()
SmallDog:PrintAge()
local Object = {}
-------------------------------------------------
-- GLOBAL
-------------------------------------------------
function Object.New( name , ageInYears )-- constructor
local self =
{
name = name ,
age = ageInYears
}
-------------------------------------------------
-- PRIVATE FUNCTIONS
-------------------------------------------------
local function GetDogYears( realYears ) -- local; only visible in this module
return realYears * 7
end
-------------------------------------------------
-- PUBLIC FUNCTIONS
-------------------------------------------------
function self:Bark()
print( self.name .. " says \"woof!\"" )
end
function self:PrintAge()
print( self.name .. " is " .. GetDogYears( self.age ) .. " in dog years." )
end
return self
end
return Object
輸出結果:
1月 26 01:14:56.748: Apple says "woof!"
1月 26 01:14:56.748: Apple is 70 in dog years.
1月 26 01:14:56.748: Orange says "woof!"
1月 26 01:14:56.748: Orange is 28 in dog years.
沒有留言:
張貼留言