forked from trashpanda027/StateMachine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStateMachine.lua
More file actions
41 lines (32 loc) · 1.4 KB
/
Copy pathStateMachine.lua
File metadata and controls
41 lines (32 loc) · 1.4 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
-- Some Constants for Function
local StarterPlayer = game:GetService("StarterPlayer")
local utils = require(script.Utils)
local signal = require(script.goodSignal) --require the "good signal" module that we previously created (goodSignal.lua)
local StateMachine = {}
StateMachine.__index = StateMachine
function StateMachine.newState(states)
local newStateMachine = {}
setmetatable(newStateMachine, StateMachine)
newStateMachine.stateChanged = signal.new() --replacing instances with signal class; works the same, more optimazed
newStateMachine.error = signal.new() --replacing instances with signal class; works the same, more optimazed
newStateMachine.stateables = states
newStateMachine.state = Instance.new("StringValue")
newStateMachine.state.Value = newStateMachine.stateables[1]
return newStateMachine
end
function StateMachine:setState(stateToChange: string)
if stateToChange == self.state.Value then
return warn(`State is already set as {self.state.Value}`)
end
if utils.tableContains(self.stateables, stateToChange) ~= true then
self.error:Fire(`Tried to set state to a non-state value {stateToChange} not in \{{table.concat(self.stateables, ", ")}\} State Change Failed`)
return
end
local lastState = self.state.Value
self.state.Value = stateToChange
self.stateChanged:Fire(lastState, stateToChange)
end
function StateMachine:getCurrentState()
return self.state.Value
end
return StateMachine