Simple State Module

A simple to use state module .

--> Types
export type State = {
	new : (DefaultValue : any, Locked : boolean?) -> (),
	Set : (State, Value : any, Force : boolean?) -> (),
	Get : (State) -> any,
	Listen : (State, callBack : (value : any) -> ()) -> () -> (),
	Lock : (State, Locked : boolean) -> (),
}

--> Class
local State = {}
State.__index = State

--> Constructor
function State.new(DefaultValue : any, Locked : boolean?) : State
	local self = setmetatable({}, State)
	
	self._Value = DefaultValue
	self._Locked = Locked or false
	
	self._Listeners = {}
	
	return self
end

--> Methods
function State:Set(Value : any, Force : boolean?)
	self = self :: State
	
	if (self._Value ~= Value and self._Locked == false) or (Force ~= nil and Force == true) then
		self._Value = Value
		self:_Fire(self._Value)
	end
end

function State:Get() : any
	self = self :: State
	return self._Value :: any
end

function State:Lock(Locked : boolean)
	self = self :: State
	
	self._Locked = Locked or false
end

function State:Listen(callBack : (value : any) -> ()) : () -> ()
	self = self :: State
	
	table.insert(self._Listeners, callBack)
	
	local index = table.find(self._Listeners, callBack)
	
	return function()
		table.remove(self._Listeners, index)
	end
end

function State:_Fire(value : any)
	self = self :: State
	
	for _, callBack in pairs(self._Listeners) do
		if typeof(callBack) == 'function' then
			callBack(value)
		end
	end
end

--> return
return State

Documentation:

  • Creating a new state
    local NewState = State.new(DefaultValue : any, Locked : boolean?)
    DefaultValue : any given value
    Locked : boolean (optional, defaults to false)
  • Set
    NewState:Set(Value : any, Force : boolean?)
    Value : any given value
    Force : boolean (optional, defaults to false). Bypassed Locked & same value
  • Get
    NewState:Get()
    – Returns the current Value
  • Lock
    NewState:Lock(Locked : boolean)
    Locked : boolean
  • Listen
    NewState:Listen(callBack : (Value : any) -> ()) : () -> ()
    callBack : Function (Value : any)
    Returns : Function()

Example:

local ReplicatedStorage = game:GetService('ReplicatedStorage')
local State = require(ReplicatedStorage.State)

local UserInputService = game:GetService('UserInputService')
local ButtonDown = State.new(false)

local Key = Enum.KeyCode.E

local function KeyListener(IsDown : boolean)
	print('Key Is ', if IsDown == true then 'Down' else 'Up')
end

local Listener = ButtonDown:Listen(KeyListener)

UserInputService.InputBegan:Connect(function(input : InputObject, gameProcessedEvent : boolean)
	if gameProcessedEvent == true then
		return
	end
	
	if input.KeyCode == Key then
		ButtonDown:Set(true)
	end
end)

UserInputService.InputEnded:Connect(function(input : InputObject, gameProcessedEvent : boolean)
	if input.KeyCode == Key then
		ButtonDown:Set(false)
	end
end)

task.wait(10)

Listener() --> Stop listening with KeyListener()
3 Likes