Posted on 2012-05-07 13:58
点点滴滴 阅读(417)
评论(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 ) |