Developer Preview

Events

How scripts talk to each other – locally and over the network.

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.

Events are how scripts talk to each other – inside one resource, between resources, and across the network between players and the server. An event is simply a name plus any number of arguments.

Listening to events

AddEventHandler(name, handler) listens for events triggered on the same side. It returns a handle you can pass to RemoveEventHandler later.

AddEventHandler('dayChanged', function(day, weekday)
    print(('Day %d has started, it is %s'):format(day, weekday))
end)

Events coming from the other side of the network are ignored unless you register them with RegisterNetEvent. This is a safety feature: cheaters can send any network event they like, so only events you explicitly open are accepted. RegisterNetEvent(name, handler) registers and listens in one call:

server.luaLUA
RegisterNetEvent('rtx_cafe:serve', function(customerSim)
    local src = source
    print(('%s served a customer'):format(GetPlayerName(src)))
end)

Triggering events

FunctionSideSends to
TriggerEvent(name, ...)SharedHandlers on the same side – your own resource and every other resource.
TriggerServerEvent(name, ...)ClientThe server. Inside the handler, source is the player who sent it.
TriggerClientEvent(name, target, ...)ServerOne player (their server id) or everyone with -1.
server.luaLUA
TriggerClientEvent('rtx_cafe:orderReady', source, 'Latte')
TriggerClientEvent('rtx_cafe:announce', -1, 'The café is now open!')

for _, player in ipairs(GetPlayersOnLot(zoneId)) do
    TriggerClientEvent('rtx_cafe:music', player, 'jazz')
end

Arguments can be strings, numbers, booleans, nil, vector3 and tables of those. Functions can't be sent over the network. Keep payloads small – send ids rather than whole data sets, and stay well below 64 KB per event.

Events are fire-and-forget. When the client needs an answer – a balance, a price, whether a purchase worked – use a server callback instead of pairing two events. For facts that players who join later must see, use a state bag.

The source variable

In server handlers of network events and player events, the global source holds the id of the player who caused the event. It is only correct until your handler first waits (Wait, Citizen.Await, database calls that yield), because another event may run in the meantime. Always copy it into a local first:

server.luaLUA
RegisterNetEvent('rtx_bank:withdraw', function(amount)
    local src = source
    if type(amount) ~= 'number' or amount <= 0 or amount > 50000 then
        return
    end
    Wait(250)
    if TakeMoney(src, amount, 'ATM withdrawal') then
        TriggerClientEvent('neighborly:notify', src, { text = 'Here is your cash.', type = 'success' })
    end
end)

Cancelling events

Some events can be cancelled. Call CancelEvent() in any handler; whoever triggered the event can check WasEventCanceled() right after TriggerEvent returns. Built-in events marked as cancellable below are stopped in the game too.

server.luaLUA
AddEventHandler('chatMessage', function(author, text)
    if text:lower():find('free simoleons') then
        CancelEvent()
        TriggerClientEvent('neighborly:notify', source, { text = 'Please don\'t spam.', type = 'error' })
    end
end)

AddEventHandler('buildModeEntered', function(zoneId)
    if GetLotType(zoneId) == 'community' and not IsPlayerAdmin(source) then
        CancelEvent()
    end
end)

Your own events can use the same pattern, which lets other resources veto an action:

server.luaLUA
TriggerEvent('rtx_cafe:beforeOpen', zoneId)
if WasEventCanceled() then
    return
end
GlobalState.cafeOpen = true

Naming

Always prefix event names with your resource name: rtx_cafe:serve, not serve. Every resource shares the same event space, and a generic name will collide with someone else's sooner or later.

Built-in events

Neighborly fires these events for you. Shared events fire on both sides; on the server, source is the player involved.

EventSideParametersWhen
playerConnectingServername, setKickReason, deferralsA player is connecting (FiveM style). source is their id. Call setKickReason(text) and CancelEvent() to refuse them, or use deferrals like in playerJoining.
playerJoiningServername, deferralsA player is connecting. source is their id. Call deferrals.defer() to make them wait, deferrals.update(text) to show a message on the loading screen and deferrals.done() to let them in or deferrals.done(reason) to refuse them. If a resource defers and never calls done – for example because it crashed – the player is let in after 30 seconds, so a broken script can never lock everyone out.
playerDroppedServerreasonA player left or lost connection. source is still valid inside the handler.
playerSpawnedClientsimThe local player's Sim has loaded into the world for the first time this session.
characterSelectedSharedsim, characterIdThe player picked or created a character. On the server, source is the player.
lotEnteredSharedzoneIdA player's Sim arrived on a lot. On the client it fires for the local player only; on the server for everyone, with source set.
lotLeftSharedzoneIdA player's Sim left a lot.
buildModeEnteredClientzoneIdThe local player opened Build/Buy mode.
buildModeExitedClientzoneIdThe local player closed Build/Buy mode.
chatMessageServersource, author, textSomeone sent a chat message that isn't a command. Call CancelEvent() to stop it from being shown.
dayChangedSharedday, weekdayMidnight in the game world. day counts up from 1, weekday is 'monday'…'sunday'.
billCreatedServerbillA resource created a bill. source is the player who owes it.
billPaidServerbillA bill was paid. source is the player who paid it.
onResourceStartSharedresourceNameAny resource started. Compare with GetCurrentResourceName() to react to your own.
onResourceStopSharedresourceNameAny resource is stopping. Clean up here – remove objects you created, close UIs.
onServerResourceStartServerresourceNameA resource finished starting on the server, after its scripts ran.
onClientResourceStartClientresourceNameA resource finished starting on this player's PC.

Cancellable on the server: chatMessage (with CancelEvent()) and playerConnecting / playerJoining (through deferrals.done(reason)).

Example: a waiting room with deferrals

Deferrals let you check something before a player is allowed in – a whitelist in your own database, for example. The loading screen shows your messages while you check.

server.luaLUA
AddEventHandler('playerJoining', function(name, deferrals)
    local src = source
    local account = GetPlayerIdentifierByType(src, 'neighborly')
    deferrals.defer()
    Wait(0)
    deferrals.update(('Hi %s, checking your residency papers...'):format(name))

    local db = exports.neighborly:db()
    local resident = db:get('residents:' .. account)

    if resident and not resident.banned then
        deferrals.done()
    else
        deferrals.done('You are not a resident yet. Apply on our Discord!')
    end
end)

Example: a welcome on the first lot

client.luaLUA
local welcomed = false

AddEventHandler('lotEntered', function(zoneId)
    if welcomed then
        return
    end
    welcomed = true
    exports.neighborly:notify({
        title = 'Welcome to ' .. (GetLotName(zoneId) or 'the neighborhood'),
        text = 'Type /help in chat to see what you can do here.',
        icon = 'home'
    })
end)