I recently made my own implementation of state machine, called Pushdown automata. But my problem is that i don’t really know how i should “bite” states and how to make them as i want.
The main goal is to add them to the stack where states are held until all of them dont finish their work. I want to kept activated only the top one state in stack, and when that top one finish their work it should be popped out of the stack and next one that was under that previous state should go as a top one and be activated, and repeat that process until all states are not finished
function Add_State(Data, StateName: string, State)
if Data._states[StateName] then return end
Data._states[StateName] = State
end
function Remove_State(Data, StateName)
if not Data._states[StateName] then return end
local old = Data._states[StateName]
Data._states[StateName] = nil
return old
end
function Push(Data, StateName)
if not Data._states[StateName] then
return end
for _, state in ipairs(Data._stack) do
if state.Name == StateName then
return
end
end
Data._stack[#Data._stack + 1] = {
Name = StateName,
State = Data._states[StateName]
}
--Put state ON
end
function Pop(Data)
assert(#Data._stack > 0, "Stack is empty!")
local old = Data._stack[#Data._stack]
Data._stack[#Data._stack] = nil
return old
end
function Peek(Data)
return Data._stack[#Data._stack]
end
----<< Constructor >>----
function Create_StateMachine()
local data = {
_states = {},
_stack = {}
}
return {
--- State methods ---
AddState = function(_, StateName, State)
Add_State(data, StateName, State)
end,
RemoveState = function(_, StateName)
Remove_State(data, StateName)
end,
--- State Machine Methods
Push = function(_, StateName)
Push(data, StateName)
end,
Pop = function(_)
return Pop(data)
end,
Peek = function(_)
return Peek(data)
end
}
end
return {
Create = Create_StateMachine
}