Posted on 2012-05-07 13:58
點點滴滴 閱讀(426)
評論(0) 編輯 收藏 引用
class.lua實現了在Lua中創建類的模擬,非常方便。class.lua參考自http://lua-users.org/wiki/SimpleLuaClasses
4 |
function class(base, init) |
6 |
if not init and type(base) == 'function' then |
9 |
elseif type(base) == 'table' then |
11 |
for i,v in pairs(base) do |
22 |
mt.__call = function (class_tbl, ...) |
29 |
if class_tbl.init then |
30 |
class_tbl.init(obj,...) |
33 |
if base and base.init then |
40 |
c.is_a = function (self, klass) |
41 |
local m = getmetatable (self) |
43 |
if m == klass then return true end |
State基類,包含三個stub函數,enter()和exit()分別在進入和退出state時被執行,onUpdate()函數將會在state被激活時的每幀被執行。
5 |
function State:init( name ) |
12 |
function State:onUpdate() |
StateMachine類,該類集成了Moai的MOAIThread類。MOAIThread類似于Lua中的coroutine,但是在Moai中被yield的MOAIThread,會在game loop的每幀中被自動resume,見StateMachine:updateState函數,利用此特點,來實現每幀執行State:onUpdate函數。
5 |
function StateMachine:init() |
6 |
self.currentState = nil |
10 |
function StateMachine:run() |
11 |
if ( self.mainThread == nil ) |
13 |
self.mainThread = MOAIThread.new() |
14 |
self.mainThread:run( self.updateState, self ) |
18 |
function StateMachine:stop() |
19 |
if ( self.mainThread ) |
21 |
self.mainThread:stop() |
25 |
function StateMachine:setCurrentState( state ) |
26 |
if ( state and state:is_a( State ) ) |
28 |
if ( state == self.currentState ) |
30 |
print ( "WARNING @ StateMachine::setCurrentState - " .. |
31 |
"var state [" .. state.name .. "] is the same as current state" ) |
34 |
self.lastState = self.currentState |
35 |
self.currentState = state |
38 |
print ( "exiting state [" .. self.lastState.name .. "]" ) |
41 |
print ( "entering state [" .. self.currentState.name .. "]" ) |
42 |
self.currentState:enter() |
44 |
print ( "ERROR @ StateMachine::setCurrentState - " .. |
45 |
"var [state] is not a class type of State" ) |
49 |
function StateMachine:updateState() |
52 |
if ( self.currentState ~= nil ) |
54 |
self.currentState:onUpdate() |
如何利用State和StateMachine類的示例,首先定義兩個state。
SampleState.lua
3 |
State1 = class( State ) |
6 |
State.init( self, "State1" ) |
9 |
function State1:enter() |
13 |
function State1:exit() |
17 |
function State1:onUpdate() |
18 |
print ( self.name .. " is updated" ) |
20 |
print ( "self.i=" .. self.i ) |
24 |
SM:setCurrentState( state2 ) |
31 |
State2 = class( State ) |
33 |
function State2:init() |
34 |
State.init( self, "State2" ) |
37 |
function State2:onUpdate() |
38 |
print ( "State2 is updated" ) |
test.lua
8 |
SM:setCurrentState( state1 ) |