-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLuaStateMachine.cs
More file actions
93 lines (79 loc) · 2.28 KB
/
LuaStateMachine.cs
File metadata and controls
93 lines (79 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using LuaInterface;
public class LuaStateMachine<T> where T : class {
private LuaTable mCurrentState = null;
private LuaTable mGlobalState = null;
private LuaTable mPreviousState = null;
// Reference to the Owner of the statemachine
private T mOwner;
/// <summary>
/// Constructor
/// </summary>
/// <param name="owner">Owner.</param>
public LuaStateMachine(T owner) {
mOwner = owner;
}
/// <summary>
/// Changes the current state to a new one
/// </summary>
/// <param name="newState">The new state</param>
public void ChangeState(LuaTable newState) {
if (mCurrentState != null)
((LuaFunction)mCurrentState["Exit"]).Call(mOwner);
mPreviousState = mCurrentState;
mCurrentState = newState;
((LuaFunction)mCurrentState["Enter"]).Call(mOwner);
}
/// <summary>
/// Changes the current global state to a new one
/// </summary>
/// <param name="newState">New state.</param>
public void ChangeGlobalState(LuaTable newState) {
if (mGlobalState != null)
((LuaFunction)mGlobalState["Exit"]).Call(mOwner);
mGlobalState = newState;
((LuaFunction)mGlobalState["Enter"]).Call(mOwner);
}
/// <summary>
/// Reverts the state of the to previous.
/// </summary>
public void RevertToPreviousState() {
if (mPreviousState != null)
ChangeState(mPreviousState);
}
/// <summary>
/// Update this instance.
/// </summary>
public void Update() {
if (mGlobalState != null)
((LuaFunction)mGlobalState["Execute"]).Call(mOwner);
if (mCurrentState != null)
((LuaFunction)mCurrentState["Execute"]).Call(mOwner);
}
/// <summary>
/// Handles the message.
/// </summary>
/// <returns><c>true</c>, if message was handled, <c>false</c> otherwise.</returns>
/// <param name="message">Message.</param>
public bool HandleMessage(Telegram message) {
// current state
if (mCurrentState != null) {
if ((bool)((LuaFunction)mCurrentState["OnMessage"]).Call(mOwner, message)[0]) {
return true;
}
}
// global state
if (mGlobalState != null) {
if ((bool)((LuaFunction)mGlobalState["OnMessage"]).Call(mOwner, message)[0]) {
return true;
}
}
return false;
}
/// <summary>
/// Gets the name of the current state.
/// </summary>
/// <returns>The current state name.</returns>
public string GetCurrentStateName() {
return mCurrentState.ToString();
}
}