State & callbacks natives
Move data between the server and clients: callbacks that return an answer, and state bags that replicate on their own.
Developer Preview. Scripting is live on Neighborly servers – everything on these pages works today. The API is young, so tell us what you need next on Discord.
Move data between the server and clients: callbacks that return an answer, and state bags that replicate on their own. Read Client ↔ server data to choose the right tool.
Open in the natives browser Search all 199 natives at once.
RegisterServerCallback
void RegisterServerCallback(string name, function handler)Answers questions from clients. A client calls TriggerServerCallback and waits for what your handler returns.
The handler runs as its own thread, so it may Wait, use the database or even ask the player something with TriggerClientCallback. Whatever it returns is sent back – several values are fine. If it raises an error, the client receives nothing and the error is printed in the server console.
Treat every argument like the arguments of a net event: check types and ranges, and decide on the server. A popular pattern is returning ok, resultOrError.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | Callback name, prefixed with your resource name, like 'rtx_bank:getAccount'. |
handler | function | function(source, ...) – return any number of values; they are sent back to the client that asked. |
Returns
Nothing (void).
Example
local db = exports.neighborly:db()
RegisterServerCallback('rtx_bank:getAccount', function(source)
local account = db:get('bank:' .. GetPlayerAccountId(source)) or { savings = 0 }
return GetBalance(source), account.savings
end)
RegisterServerCallback('rtx_bank:deposit', function(source, amount)
if type(amount) ~= 'number' or amount < 1 or amount > 100000 then
return false, 'Invalid amount'
end
amount = math.floor(amount)
if not TakeMoney(source, amount, 'Savings deposit') then
return false, 'Not enough simoleons'
end
local account = db:update('bank:' .. GetPlayerAccountId(source), function(acc)
acc = acc or { savings = 0 }
acc.savings = acc.savings + amount
return acc
end)
return true, account.savings
end)TriggerServerCallback
...any TriggerServerCallback(string name, any ...)Asks the server a question and waits for the answer. Call it inside a thread – event handlers, commands, NUI callbacks and CreateThread all are.
The calling thread waits until the server answers – usually one round trip, a few dozen milliseconds. After 30 seconds without an answer (or when no handler with that name exists), it returns nothing and logs a warning to the launcher log, so always handle nil.
Calling it at the top level of a file raises an error. The Server callbacks guide shows the full round trip, including NUI pages.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | Callback name, prefixed with your resource name, like 'rtx_bank:getAccount'. |
... | any | Arguments for the server handler. The server must validate them. |
Returns
...any Whatever the server handler returned, or nothing (nil) after the timeout.
Example
RegisterCommand('balance', function()
local cash, savings = TriggerServerCallback('rtx_bank:getAccount')
if not cash then
return exports.neighborly:notify({ text = 'The bank is not answering.', type = 'error' })
end
exports.neighborly:notify({
title = 'Simoleon Savings',
text = ('Cash %s · Savings %s'):format(FormatMoney(cash), FormatMoney(savings))
})
end, false)RegisterClientCallback
void RegisterClientCallback(string name, function handler)Answers questions the server asks this player with TriggerClientCallback.
Only the server can call it, for this player. The handler may wait – for a dialog, a progress bar or a NUI answer.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | Callback name, prefixed with your resource name, like 'rtx_bank:getAccount'. |
handler | function | function(...) – return values go back to the server. It may wait, for example for a dialog. |
Returns
Nothing (void).
Example
RegisterClientCallback('rtx_trade:confirm', function(fromName, item, price)
local answer = exports.neighborly:alertDialog({
header = 'Trade offer',
content = ('%s offers you %s for %s.'):format(fromName, item, FormatMoney(price)),
confirmLabel = 'Accept',
cancelLabel = 'Decline'
})
return answer == 'confirm'
end)TriggerClientCallback
...any TriggerClientCallback(string name, Player player, any ...)Asks one player's client a question and waits for the answer. Treat the answer like any other client input – it can be faked.
Waits up to 30 seconds, or until the player leaves, then returns nothing. The answer comes from a PC you don't control: use it for choices and local information (did they accept, where is their camera), never for facts like money or ownership.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | Callback name, prefixed with your resource name, like 'rtx_bank:getAccount'. |
player | Player | The player to ask. |
... | any | Arguments for the client handler. |
Returns
...any The client's return values, or nothing (nil) after the timeout or when the player left.
Example
RegisterNetEvent('rtx_trade:offer', function(target, item, price)
local src = source
if type(target) ~= 'number' or target == src or not GetPlayerName(target) then
return
end
if type(item) ~= 'string' or #item > 40 or type(price) ~= 'number' or price < 1 then
return
end
price = math.floor(price)
local accepted = TriggerClientCallback('rtx_trade:confirm', target, GetPlayerName(src), item, price)
if accepted == true and TransferMoney(target, src, price, 'Trade: ' .. item) then
TriggerClientEvent('neighborly:notify', src, { text = 'Trade accepted!', type = 'success' })
else
TriggerClientEvent('neighborly:notify', src, { text = 'No deal this time.' })
end
end)Player
{ state } Player(Player player)Returns a player's state bag holder. Player(id).state is the bag named player:<id>.
On the server, Player(id).state is the authoritative bag. The only client that may change it is that player, through LocalPlayer.state:set(key, value, true). On a client you can read any connected player's replicated values, and LocalPlayer.state is a shortcut for your own bag. Values set with replicated = false stay on the server.
Parameters
| Parameter | Type | Description |
|---|---|---|
player | Player | Server id of the player. |
Returns
{ state } An object whose state field is the state bag. Read keys like a table, write with :set(key, value, replicated).
Example
RegisterNetEvent('rtx_jobs:toggleDuty', function()
local src = source
local state = Player(src).state
if state.job ~= 'police' then
return
end
state:set('onDuty', not state.onDuty, true)
end)Lot
{ state } Lot(ZoneId zoneId)Returns a lot's state bag holder. Lot(zoneId).state is the bag named lot:<zoneId>.
Replicated lot values are sent to every client, so a map UI can show them for lots far away. Players who join later receive the current values before their client scripts start.
Parameters
| Parameter | Type | Description |
|---|---|---|
zoneId | ZoneId | Zone id of the lot. |
Returns
{ state } An object whose state field is the state bag. Read keys like a table, write with :set(key, value, replicated).
Example
RegisterCommand('partymode', function(source)
local zoneId = GetPlayerLot(source)
if not zoneId or GetLotOwner(zoneId) ~= GetPlayerHousehold(source) then
return TriggerClientEvent('neighborly:notify', source, { text = 'Only the owners can start a party here.' })
end
Lot(zoneId).state:set('party', not Lot(zoneId).state.party, true)
end, false)Entity
{ state } Entity(Sim|Object entity)Returns the state bag holder of a Sim or object. Entity(id).state is the bag named entity:<id>.
Entity bags work for Sims and objects. Players may write the bags of their own Sims (with replicated = true); everything else is written by the server.
Parameters
| Parameter | Type | Description |
|---|---|---|
entity | Sim|Object | A Sim or object id. |
Returns
{ state } An object whose state field is the state bag. Read keys like a table, write with :set(key, value, replicated).
Example
RegisterNetEvent('rtx_cafe:brewed', function()
local src = source
local sim = GetPlayerCharacter(src)
if not sim or not Player(src).state.onDuty then
return
end
local cups = (Entity(sim).state.cupsToday or 0) + 1
Entity(sim).state:set('cupsToday', cups, true)
end)GetStateBagValue
any GetStateBagValue(string bagName, string key)Reads one key from a state bag by its name – handy inside change handlers, where you get the bag name.
Works on every bag the current side can see. GetStateBagValue('global', 'cafeOpen') is the same as GlobalState.cafeOpen.
Parameters
| Parameter | Type | Description |
|---|---|---|
bagName | string | Bag name: 'global', 'player:12', 'lot:4821' or 'entity:90031'. |
key | string | The key. |
Returns
any The value, or nil.
Example
AddStateBagChangeHandler('onDuty', nil, function(bagName, key, value)
local player = GetPlayerFromStateBagName(bagName)
if player and value then
local job = GetStateBagValue(bagName, 'job') or 'staff'
print(('%s started a shift as %s'):format(GetPlayerName(player), job))
end
end)SetStateBagValue
void SetStateBagValue(string bagName, string key, any value, boolean replicated)Writes one key of a state bag by its name. The same as :set on GlobalState, Player(id).state, Lot(id).state or Entity(id).state.
Only the server can replicate. A client may set values on any bag, but they stay on that PC and are overwritten by the next change from the server – useful for local UI flags, never trusted by the server.
Tables are copied when you set them. Changing a field of a table you read from a bag does nothing – change the table and set the whole key again.
Parameters
| Parameter | Type | Description |
|---|---|---|
bagName | string | Bag name: 'global', 'player:12', 'lot:4821' or 'entity:90031'. |
key | string | The key. |
value | any | New value, or nil to remove the key. |
replicated | boolean | true to send it to clients. On a client the value always stays local. |
Returns
Nothing (void).
Example
RegisterCommand('setstate', function(source, args)
local bagName, key, value = args[1], args[2], args[3]
if not bagName or not key then
return print('Usage: setstate <bag> <key> <json value>')
end
SetStateBagValue(bagName, key, json.decode(value or 'null'), true)
print(('%s.%s = %s'):format(bagName, key, value or 'nil'))
end, true)GetStateBagKeys
table GetStateBagKeys(string bagName)Lists every key of a state bag. On a client you only see replicated keys and your own local ones.
Handy for debugging: dump a bag in the console to see exactly what your resources stored.
Parameters
| Parameter | Type | Description |
|---|---|---|
bagName | string | Bag name: 'global', 'player:12', 'lot:4821' or 'entity:90031'. |
Returns
table List of keys in the bag that this side can see.
Example
RegisterCommand('dumpstate', function(source, args)
local bagName = args[1] or 'global'
for _, key in ipairs(GetStateBagKeys(bagName)) do
print(key, json.encode(GetStateBagValue(bagName, key)))
end
end, true)AddStateBagChangeHandler
int AddStateBagChangeHandler(string? key, string? bagFilter, function handler)Calls your handler whenever a state bag key changes on this side.
Fires on the side where the change arrives: on the server when server code sets a value, on clients when a replicated change arrives. It does not fire for values that already existed when the player joined or entered the lot – read the current value once (on start or in lotEntered) and then listen for changes.
The value is already stored when your handler runs, so GetStateBagValue returns the new value. Keep handlers short – they run for every matching change.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string? | Key to watch, or nil for every key. |
bagFilter | string? | Bag name to watch, or nil for every bag. |
handler | function | function(bagName, key, value, reserved, replicated) – runs after the value changed. |
Returns
int A cookie for RemoveStateBagChangeHandler.
Example
AddStateBagChangeHandler('party', nil, function(bagName, key, value)
local zoneId = GetLotFromStateBagName(bagName)
if zoneId and zoneId == GetCurrentLot() then
PlaySoundFrontend(value and 'ui_party_start' or 'ui_party_end', 0.7)
ShowToast(value and 'Party time!' or 'The party is over.', 2000)
end
end)RemoveStateBagChangeHandler
void RemoveStateBagChangeHandler(int cookie)Stops a state bag change handler.
Change handlers are removed automatically when your resource stops.
Parameters
| Parameter | Type | Description |
|---|---|---|
cookie | int | What AddStateBagChangeHandler returned. |
Returns
Nothing (void).
Example
local cookie
RegisterCommand('cafealerts', function()
if cookie then
RemoveStateBagChangeHandler(cookie)
cookie = nil
return exports.neighborly:notify({ text = 'Café alerts off.' })
end
cookie = AddStateBagChangeHandler('cafeOpen', 'global', function(_, _, open)
exports.neighborly:notify({ text = open and 'Bluejay Café is open!' or 'Bluejay Café closed.', icon = 'coffee' })
end)
exports.neighborly:notify({ text = 'Café alerts on.' })
end, false)GetPlayerFromStateBagName
Player? GetPlayerFromStateBagName(string bagName)Turns a bag name like 'player:12' back into a player id.
Use it inside change handlers registered with a nil bag filter, which run for every player's bag.
Parameters
| Parameter | Type | Description |
|---|---|---|
bagName | string | Bag name: 'global', 'player:12', 'lot:4821' or 'entity:90031'. |
Returns
Player? The player, or nil if the bag isn't a player bag.
Example
AddStateBagChangeHandler('job', nil, function(bagName, key, value)
if GetPlayerFromStateBagName(bagName) == PlayerId() then
exports.neighborly:notify({ text = 'Your job is now ' .. tostring(value or 'unemployed') .. '.' })
end
end)GetLotFromStateBagName
ZoneId? GetLotFromStateBagName(string bagName)Turns a bag name like 'lot:4821' back into a zone id.
Use it inside change handlers registered with a nil bag filter, which run for every lot's bag.
Parameters
| Parameter | Type | Description |
|---|---|---|
bagName | string | Bag name: 'global', 'player:12', 'lot:4821' or 'entity:90031'. |
Returns
ZoneId? The lot, or nil if the bag isn't a lot bag.
Example
AddStateBagChangeHandler('doorbellSound', nil, function(bagName, key, value)
local zoneId = GetLotFromStateBagName(bagName)
local home = GetHouseholdHome(GetPlayerHousehold(PlayerId()))
if zoneId and zoneId == home then
exports.neighborly:notify({ text = 'Your doorbell now plays: ' .. tostring(value), icon = 'bell' })
end
end)GetEntityFromStateBagName
Sim|Object? GetEntityFromStateBagName(string bagName)Turns a bag name like 'entity:90031' back into a Sim or object id.
The entity may already be gone when the handler runs after a deletion – check with DoesObjectExist or DoesSimExist.
Parameters
| Parameter | Type | Description |
|---|---|---|
bagName | string | Bag name: 'global', 'player:12', 'lot:4821' or 'entity:90031'. |
Returns
Sim|Object? The Sim or object, or nil if the bag isn't an entity bag.
Example
AddStateBagChangeHandler('cupsToday', nil, function(bagName, key, value)
local machine = GetEntityFromStateBagName(bagName)
if machine and DoesObjectExist(machine) and (value or 0) >= 50 then
print(('Espresso machine %d needs cleaning after %d cups'):format(machine, value))
end
end)