> For the complete documentation index, see [llms.txt](https://corex-zombies.gitbook.io/corex-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://corex-zombies.gitbook.io/corex-docs/build/players.md).

# Player data and lifecycle

Read native player tables, initialize safely, and leave state changes with their owner.

`corex-core` owns loaded players, native cash/bank accounts, metadata, lifecycle state and synchronization. Other resources use these APIs instead of maintaining another copy. This reference describes the September 2026 compatibility update's source behavior, not certification of live persistence.

## Configuration and startup <a href="#configuration-and-startup" id="configuration-and-startup"></a>

Edit `resources/[corex]/corex-core/config.lua`. Main settings: `Config.Debug`, `Config.AllowMultiSession`, `Config.PlayerStates`, `Config.DefaultPlayerState`, `Config.CallbackTimeout`, `Config.MaxMoney`, `Config.OverrideWorldSettings` and `Config.Database`.

Start real `oxmysql` first. Use `resources/[corex]/corex-core/sql/corex_framework.sql` and the [installation](/corex-docs/start-here/installation.md)/[database](/corex-docs/start-here/database.md) instructions. A configuration change does not repair schemas or convert another framework's player records; back up and migrate separately.

## Read a loaded player <a href="#read-a-loaded-player" id="read-a-loaded-player"></a>

Native player data is a Lua table. In a dependent **server script**:

```lua
local function describePlayer(src)
    local player = exports['corex-core']:GetPlayer(src)
    if not player then return nil end
    return {
        name = player.name,
        cash = player.money.cash,
        state = exports['corex-core']:GetPlayerState(src),
    }
end
```

`GetPlayer` may return `nil` while loading or after disconnect. `src` is a temporary server connection ID; `player.identifier` is persistent. Never store a source as a permanent account key, and do not call loaded-player APIs during `playerConnecting`.

## Read-only profiles and presence <a href="#read-only-profiles-and-presence" id="read-only-profiles-and-presence"></a>

Server-only `ReadPlayerProfile(identifier, callback)` reads a persistent native identifier without loading or creating a player. Its immediate boolean reports whether the callback was accepted; the callback receives the result, potentially before the call returns:

* Success: `{ok = true, value = {identifier, name, presence}}`.
* Failure: `{ok = false, error = {code, message}}`.

`presence` is a copied array of `{source, sessionToken}` pairs. The profile contains no balances, metadata, inventory, mutable player table or functions. Lookup itself performs no save, schema migration, journal write or lifecycle event. Current live/pending identity data takes precedence where applicable; recovered snapshots are compared with stored revisions.

Errors distinguish `not_found` from `storage_unavailable`, and include `invalid_identifier`, `invalid_profile`, `recovery_blocked`, `stopping` and `read_timeout`. An identifier must be a nonempty string of at most 128 bytes without control characters. An unavailable/corrupt read is not permission to create an empty profile.

`GetPlayerPresence(identifier)` synchronously returns the current copied session pairs, or an empty array when none are current or the identifier is invalid. Recheck the original source **and** token after yielding and before sending private results; a reused source is a different session. Tokens are temporary, resource-lifetime values, not persistent citizen IDs or authorization credentials.

## Initialize once per session, including late starts <a href="#observe-loading" id="observe-loading"></a>

`corex:server:playerReady(source, player)` means native data is loaded—not that character placement, appearance, inventory and UI are all ready.

```lua
AddEventHandler('corex:server:playerReady', function(src, player)
    if not player then return end
    -- Initialize this resource's per-session state.
    -- Make initialization safe to repeat; do not grant repeatable login rewards.
end)

for src, player in pairs(exports['corex-core']:GetPlayers()) do
    -- Also initialize already-loaded players when this resource starts.
end
```

A past event is not replayed automatically to a late subscriber. Use [events and replicated state](/corex-docs/build/events-and-state.md) for the initial-snapshot pattern.

## Useful server exports <a href="#useful-server-exports" id="useful-server-exports"></a>

The [native core export table](/corex-docs/reference/exports.md#corex-core) is the canonical signature reference for player lookups, balances, metadata, nearby players and vehicle catalogs. Choose the lookup that matches your identifier: a persistent identifier is not a current server source.

`BroadcastNearby(coords, radius, eventName, ...)` starts with **coordinates**, not a player source. The client also exposes `GetCoreObject()`, `IsReady()` and the shared vehicle catalog readers; its readiness concerns local load state.

## Read fields; use functions to change them <a href="#read-fields-use-functions-to-change-them" id="read-fields-use-functions-to-change-them"></a>

Never assign `player.money.cash` or nested metadata directly. Call the owner so validation, replication, change events and dirty tracking run:

```lua
-- Trusted server logic, after authorizing this reward.
local ok = exports['corex-core']:AddMoney(src, 'cash', 25)
if not ok then return end
```

Other mutations include `RemoveMoney(src, account, amount)`, `SetMetaData(src, key, value)` and `SavePlayer(src, force)`. Validate requests and check results. A successful memory mutation is not acknowledgement of its later SQL write.

## Native versus compatibility views <a href="#native-versus-compatibility-views" id="native-versus-compatibility-views"></a>

Native code uses `exports['corex-core']:GetPlayer(src)`; QB code normally uses `QBCore.Functions.GetPlayer(src)` and `Player.PlayerData`; ESX uses `xPlayer`; Qbox uses its exports. These are different public shapes over shared owners, not independent accounts. Keep each script on its intended API.

## Lifecycle and cleanup <a href="#lifecycle-and-cleanup" id="lifecycle-and-cleanup"></a>

Use `SetPlayerState(src, state)`/`GetPlayerState(src)`. Configured states include `loading`, `active`, `dead` and `spectating`; let the owning spawn/death flow manage transitions. Iterate `GetPlayersByState` with `pairs`, not `ipairs`.

Clean your own caches through FiveM's `playerDropped`. Cross-resource handler order does not guarantee native `GetPlayer(source)` still exists at that point. Do not invent a CoreX-specific drop event.

## Troubleshooting <a href="#troubleshooting" id="troubleshooting"></a>

**Lookup is nil:** check the server ID and loaded-player milestone.

**Money/metadata display is stale:** compare server exports with the client HUD/facade. Do not compensate with a second local balance adjustment.

**Changes disappear on reconnect:** inspect SQL and migration errors before save intervals; preserve recovery files/backups. Repeated restarts are not a save strategy.

**Invalid lifecycle state:** use the installed `Config.PlayerStates`, not an unadapted spelling from another framework.

Source checked: `server/main.lua`, `server/players.lua`, `server/state.lua`, `server/utils.lua`, `client/main.lua` and `fxmanifest.lua`. A complete read-only command is in [your first resource](/corex-docs/build/first-resource.md).
