Examples
Practical gameplay patterns for PlayerState. Start with Quick start if you have not called PlayerState.Init yet.
IMPORTANT
Clients can only read data. All writes belong on the server.
Currency System
lua
-- ServerStorage.CurrencyService
local CurrencyService = {}
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local PlayerState = require(ReplicatedStorage.Libraries.PlayerState.PlayerStateServer)
function CurrencyService.GetCoins(player: Player): number
return PlayerState.Get(player, "Coins") or 0
end
function CurrencyService.AddCoins(player: Player, amount: number): boolean
if amount <= 0 then return false end
local currentCoins = CurrencyService.GetCoins(player)
PlayerState.Set(player, "Coins", currentCoins + amount)
return true
end
function CurrencyService.SpendCoins(player: Player, amount: number): boolean
local currentCoins = CurrencyService.GetCoins(player)
if currentCoins < amount then
return false
end
PlayerState.Set(player, "Coins", currentCoins - amount)
return true
end
return CurrencyServicelua
-- Enhanced version with proper validation
local CurrencyService = {}
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local PlayerState = require(ReplicatedStorage.Libraries.PlayerState.PlayerStateServer)
local MAX_COINS = 999999999
local MIN_TRANSACTION = 1
function CurrencyService.AddCoins(player: Player, amount: number): boolean
-- Validate inputs
if not player or typeof(amount) ~= "number" then
return false
end
if amount < MIN_TRANSACTION or amount > MAX_COINS then
warn(`[Currency] Invalid amount: {amount}`)
return false
end
local currentCoins = PlayerState.Get(player, "Coins") or 0
local newTotal = currentCoins + amount
if newTotal > MAX_COINS then
warn(`[Currency] Would exceed max coins for {player.Name}`)
return false
end
PlayerState.Set(player, "Coins", newTotal)
print(`[Currency] Added {amount} coins to {player.Name}`)
return true
end
return CurrencyServiceAdvanced Currency Features
lua
-- ServerStorage.AdvancedCurrencyService
local CurrencyService = {}
-- Multiple currency support
function CurrencyService.AddCurrency(player: Player, currencyType: string, amount: number)
local path = `Currencies.{currencyType}`
local current = PlayerState.GetPath(player, path) or 0
PlayerState.SetPath(player, path, current + amount)
end
-- Transaction logging
function CurrencyService.LogTransaction(player: Player, type: string, amount: number)
local transaction = {
Type = type,
Amount = amount,
Timestamp = os.time()
}
PlayerState.AddToArray(player, "TransactionHistory", transaction)
end
return CurrencyService