Skip to content

Commit

Permalink
feat: semaphore based state syncing
Browse files Browse the repository at this point in the history
  • Loading branch information
Manason authored Dec 29, 2024
2 parents 34345f5 + b59d743 commit 2129eaf
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 0 deletions.
41 changes: 41 additions & 0 deletions client.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
local config = require 'config.client'

---@type table<string, integer>
local states = {}

---Sets a boolean state. Runs its onSet function if the state is not previously set and the onSet function exists in config
---@param name string
---@return boolean firstSetter true if the state had not previously been set
local function setState(name)
if not states[name] then
if config.states[name]?.onSet then
config.states[name].onSet()
end
states[name] = 1
return true
else
states[name] += 1
return false
end
end

---Releases a boolean state. Runs its onRelease function if this is the last call to release the state and the release function exists in config.
---@param name string
---@param force? boolean if true, releases the state regardless of the number of locks on it
---@return boolean lastReleaser true if the state is fully released after this function
local function releaseState(name, force)
if not states[name] then return false end
if states[name] <= 1 or force then
states[name] = nil
if config.states[name]?.onRelease() then
config.states[name].onRelease()
end
return true
else
states[name] -= 1
return false
end
end

exports('SetState', setState)
exports('ReleaseState', releaseState)
4 changes: 4 additions & 0 deletions config/client.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
return {
---@type table<string, State>
states = {}
}
18 changes: 18 additions & 0 deletions fxmanifest.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
fx_version 'cerulean'
game 'gta5'

name 'qbx_playerstates'
description 'Manage the state of the player'
repository 'https://github.com/Qbox-project/qbx_playerstates'
version '0.0.0'

client_scripts {
'client.lua',
}

files {
'config/client.lua',
}

lua54 'yes'
use_experimental_fxv2_oal 'yes'
5 changes: 5 additions & 0 deletions types.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---@meta

---@class State
---@field onSet? function
---@field onRelease? function

0 comments on commit 2129eaf

Please sign in to comment.