Adding state machine code to repository.

This commit is contained in:
emb
2015-11-18 23:06:40 -06:00
parent c7ed391e87
commit d1b8fcb0d9
4 changed files with 108 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
#include "LuaEvent.h"
void LuaEvent::registerCallback(std::string type, std::string functionName, std::string complete)
{
callbacks_[type] = functionName;
completeCallbacks_[type] = complete;
}
void LuaEvent::trigger(lua_State *l, std::string type)
{
lua_getglobal(l, callbacks_[type].c_str());
lua_call(l, 0, 0);
}
bool LuaEvent::isComplete(lua_State *l, std::string type)
{
bool retval = true;
lua_getglobal(l, callbacks_[type].c_str());
if(lua_pcall(l, 0, 1, 0) == 0)
{
if(!lua_isnil(l, 1))
{
if(!lua_toboolean(l, 1))
{
retval = false;
}
}
lua_pop(l, 1);
}
return retval;
// arguments
//lua_pushnumber(l, x);
//lua_pushnumber(l, y);
// call the function with 2 arguments, return 1 result
//lua_call(L, 2, 1);
//sum = (int)lua_tointeger(L, -1);
//lua_pop(L, 1);
}

View File

@@ -0,0 +1,14 @@
#pragma once
#include "Lua.h"
#include <string>
#include <map>
class LuaEvent {
public:
void registerCallback(std::string type, std::string functionName, std::string complete);
void trigger(lua_State *l, std::string type);
bool isComplete(lua_State *l, std::string type);
private:
std::map<std::string, std::string> callbacks_;
std::map<std::string, std::string> completeCallbacks_;
};

View File

@@ -0,0 +1,30 @@
#include "StateMachine.h"
StateMachine::StateMachine(lua_State *l, LuaEvent *e)
: luaState_(l)
, luaEvent_(e)
, state_(ON_INIT_ENTER)
{
}
void StateMachine::update(float dt)
{
switch(state_) {
case ON_INIT_ENTER:
luaEvent_->trigger(luaState_, "onInitEnter");
state_ = ON_INIT_ENTER_WAIT;
break;
case ON_INIT_ENTER_WAIT:
if(luaEvent_->isComplete(luaState_, "onInitEnter")) {
state_ = ON_INIT_EXIT;
}
break;
case ON_INIT_EXIT:
luaEvent_->trigger(luaState_, "onInitExit");
state_ = ON_INIT_EXIT_WAIT;
break;
}
}

View File

@@ -0,0 +1,23 @@
#pragma once
#include "Lua/Lua.h"
#include "Lua/LuaEvent.h"
class StateMachine
{
public:
StateMachine(lua_State *l, LuaEvent *e);
void initialize();
void update(float dt);
private:
lua_State *luaState_;
LuaEvent *luaEvent_;
enum {
ON_INIT_ENTER,
ON_INIT_ENTER_WAIT,
ON_INIT_EXIT,
ON_INIT_EXIT_WAIT,
} state_;
};