Developer Preview

Natives reference

Every built-in function for Sims, lots, households, sync and more – 199 natives in 17 namespaces on one page.

199 natives

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.

How to read a native · types · globals

Every native has a signature, a side and an example. In Lua every native is a global function – the namespaces only group them in these docs.

  • The signature starts with the return type (void means nothing), then the name and every parameter with its type. Copy call copies a ready-to-paste call.
  • Client natives exist only in client scripts, Server natives only in server scripts, Shared natives in both.
  • Natives that change the shared world are server-only. That's what keeps every player's game identical – see Best practices.
  • Restricted natives only work after the server owner allows your resource: add_ace resource.my_resource neighborly.restricted allow.
  • The hash next to each name (0x…) is a stable id derived from the name. Search for it, or use it when reporting a problem.

Types

TypeLua typeMeaning
PlayerintA player's server id. Same as source on the server. -1 means everyone where noted.
SimstringA Sim id, as a string because Sim ids are 64-bit numbers. Your own Sims have the same id on the server and every client, so you can send it in events.
ZoneIdstringA lot, identified by its zone id (a string).
HouseholdIdstringA household id (a string).
ObjectstringAn object on the lot the player is on (a string id).
vector3tableA position: vector3(x, y, z). Supports +, -, * by a number, .x .y .z and #v for its length – #(a - b) is the distance between two points.
EventHandletableWhat AddEventHandler returns. Only useful for RemoveEventHandler.
{ state }tableWhat Player, Lot and Entity return: an object whose state field is a state bag.
tabletableA Lua table. The description says what's inside.
anyanyAny value that can be sent over the network.
...anyanyAny number of values.
type?A question mark means the parameter is optional, or the return value can be nil.

Globals and helpers

NameSideWhat it is
sourceServerIn network event, command and player event handlers: the player who caused it. Copy it into a local before you Wait.
GlobalStateSharedThe server-wide state bag. Server writes replicate to every client.
LocalPlayerClientThe local player. LocalPlayer.state is your own player state bag – the only bag a client may write.
exportsSharedCall other resources' exports with exports.name:fn(), create your own with exports('fn', fn).
exports.neighborlySharedThe built-in helpers: notify, menus, context menus, dialogs and progress bars on the client, the database db() on the server.
promise / Citizen.AwaitSharedpromise.new(), p:resolve(v) and Citizen.Await(p) for values that arrive later.
jsonSharedjson.encode(value) and json.decode(text).
vector3Sharedvector3(x, y, z) positions with math and # for length.

Player

21 natives · Open Player page

Players are the people connected to your server, identified by their server id (Player). A player controls one Sim at a time – their character.

GetPlayers

ServerPlayer
table GetPlayers()

Returns every player currently connected to the server.

The list is a fresh table every call, ordered by server id. Players who are still on the loading screen (inside playerJoining) are not included yet. For a list that clients can read too, publish it in GlobalState – see the scoreboard example.

Parameters

This native takes no parameters.

Returns

table List of server ids of all connected players.

Example

for _, player in ipairs(GetPlayers()) do
    print(player, GetPlayerName(player))
end

GetNumPlayers

ServerPlayer
int GetNumPlayers()

Returns how many players are connected right now.

Cheaper than #GetPlayers() when you only need the count. Clients can't call it – publish the number in GlobalState if a UI needs it.

Parameters

This native takes no parameters.

Returns

int Number of connected players.

Example

if GetNumPlayers() >= 20 then
    GlobalState.busyHour = true
end

PlayerId

ClientPlayer
Player PlayerId()

Returns the server id of the player running this client script. It is the same id the server sees as source.

Server ids are handed out when a player connects and are reused after they leave, so never save them. Use GetPlayerAccountId on the server for anything persistent.

Parameters

This native takes no parameters.

Returns

Player The local player's server id.

Example

RegisterCommand('myid', function()
    local me = PlayerId()
    AddChatMessage('You', ('Your server id is %d – share it to receive money.'):format(me))
end, false)

GetPlayerName

SharedPlayer
string GetPlayerName(Player player)

Returns a player's username. Returning nil makes it a handy check whether a player is still online.

On a client it works for every connected player, not just the local one. Names are chosen by players – always show them with textContent in NUI, never as HTML.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

string The player's Neighborly username, or nil if they aren't connected.

Example

AddEventHandler('characterSelected', function()
    local src = source
    SendChatMessage(-1, 'Neighborly', GetPlayerName(src) .. ' moved into the neighborhood.', { 61, 220, 151 })
end)

GetPlayerIdentifiers

ServerPlayer
table GetPlayerIdentifiers(Player player)

Returns all identifiers of a player: neighborly: (their Neighborly account), account: (their account on this server) and ip:.

Identifiers are strings in the form type:value. For saved data use GetPlayerAccountId; the ip: identifier can change.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

table List of identifier strings.

Example

for _, id in ipairs(GetPlayerIdentifiers(source)) do
    print(id)
end

GetPlayerIdentifierByType

ServerPlayer
string? GetPlayerIdentifierByType(Player player, string idType)

Returns one identifier of the given type.

Returns the full identifier including its prefix, like discord:1234567890. For saving data prefer GetPlayerAccountId, which every player has.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.
idTypestring'neighborly', 'account' or 'ip'.

Returns

string? The full identifier, or nil.

Example

AddEventHandler('playerJoining', function(name, deferrals)
    local src = source
    local id = GetPlayerIdentifierByType(src, 'neighborly')
    if Config.Banned[id] then
        deferrals.done('You are banned from this café.')
    end
end)

GetPlayerAccountId

ServerPlayer
string GetPlayerAccountId(Player player)

Returns the player's Neighborly account id without the prefix. It never changes, which makes it the best key for saved data.

This is the id to use for every key in the database or KVP. It stays the same across sessions, characters, name changes and servers.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

string The permanent Neighborly account id.

Example

local db = exports.neighborly:db()

AddEventHandler('characterSelected', function()
    local src = source
    local key = 'profile:' .. GetPlayerAccountId(src)
    local profile = db:get(key) or { visits = 0, firstSeen = os.time() }
    profile.visits = profile.visits + 1
    profile.lastName = GetPlayerName(src)
    db:set(key, profile)
end)

GetPlayerEndpoint

ServerPlayer
string GetPlayerEndpoint(Player player)

Returns the player's IP address. Handle it with care and never show it to other players.

Only use it for moderation and logging. Never send it to clients or store it longer than you need to.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

string IP address of the player.

Example

AddEventHandler('playerJoining', function(name)
    local src = source
    print(('%s is connecting from %s'):format(name, GetPlayerEndpoint(src)))
end)

GetPlayerPing

ServerPlayer
int GetPlayerPing(Player player)

Returns the player's current ping.

Updated every few seconds. High ping makes TriggerServerCallback take longer, so keep UIs responsive while waiting.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

int Round-trip time in milliseconds.

Example

RegisterCommand('ping', function(source)
    TriggerClientEvent('neighborly:notify', source, { text = ('Your ping: %d ms'):format(GetPlayerPing(source)) })
end, false)

GetPlayerPlaytime

ServerPlayer
int GetPlayerPlaytime(Player player)

Returns how long the player has played on this server in total, across all sessions.

Counts every session on this server, so it is a fair way to unlock things for regulars or to skip tutorials for veterans.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

int Total seconds played on this server.

Example

if GetPlayerPlaytime(source) < 3600 then
    TriggerClientEvent('rtx_tutorial:start', source)
end

GetPlayerCharacter

SharedPlayer
Sim? GetPlayerCharacter(Player player)

Returns the Sim a player is currently playing.

Returns nil while the player is on the character picker or loading. Event handlers that run early (playerJoining, the first seconds after joining) should check for nil. characterSelected fires as soon as a Sim is available.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

Sim? The Sim the player controls, or nil before they picked a character.

Example

local sim = GetPlayerCharacter(source)
if sim then
    AddSimBuff(sim, 'warm_welcome', 120)
end

GetPlayerFromSim

SharedPlayer
Player? GetPlayerFromSim(Sim sim)

Finds the player who is playing a Sim right now.

The usual way to turn a Sim id into a player you can send events to. Townies, offline household members and NPCs return nil.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

Player? The controlling player, or nil for townies and offline Sims.

Example

local player = GetPlayerFromSim(targetSim)
if player then
    TriggerClientEvent('neighborly:notify', player, { text = 'Someone waved at you!' })
end

GetPlayerLot

SharedPlayer
ZoneId? GetPlayerLot(Player player)

Returns the lot a player is currently on.

On the server this is the most reliable proximity check: before you let two players interact, make sure they are on the same lot. While a Sim travels between lots it returns nil.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

ZoneId? The lot the player's Sim is on, or nil while travelling.

Example

if GetPlayerLot(source) ~= Config.CafeLot then
    return
end

IsPlayerAdmin

ServerPlayer
boolean IsPlayerAdmin(Player player)

Checks whether a player is a server admin (made admin with op or the first player on a new server). For finer control use IsPlayerAceAllowed.

A quick yes/no for admin tools. For roles like moderator, police or café manager use IsPlayerAceAllowed with your own ace names – server owners can then grant them however they like.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

boolean true for server admins.

Example

RegisterNetEvent('rtx_admin:openPanel', function()
    if IsPlayerAdmin(source) then
        TriggerClientEvent('rtx_admin:panel', source)
    end
end)

IsPlayerAceAllowed

ServerPlayer
boolean IsPlayerAceAllowed(Player player, string ace)

Checks an ACE permission. See Permissions.

Aces are hierarchical: allowing rtx_cafe also allows rtx_cafe.manage. Checks are cheap, so check on every server event instead of caching the result.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.
acestringThe permission, for example 'command.kick'.

Returns

boolean Whether the player has the permission.

Example

if IsPlayerAceAllowed(source, 'rtx_cafe.manage') then
    TriggerClientEvent('rtx_cafe:openManager', source)
end

DropPlayer

ServerPlayer
void DropPlayer(Player player, string reason)

Disconnects a player with a reason.

The player sees the reason on a friendly disconnect screen. playerDropped fires right after, so your cleanup code runs as usual.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.
reasonstringShown to the player.

Returns

Nothing (void).

Example

RegisterCommand('afkcheck', function()
    for _, player in ipairs(GetPlayers()) do
        if Player(player).state.afkMinutes and Player(player).state.afkMinutes > 30 then
            DropPlayer(player, 'You were away for more than 30 minutes.')
        end
    end
end, true)

GetMaxPlayers

SharedPlayer
int GetMaxPlayers()

Returns how many players can be connected at the same time.

Set by the server owner in server.json. Combine it with GetNumPlayers on the server to reserve slots for staff or supporters in playerJoining.

Parameters

This native takes no parameters.

Returns

int The maxPlayers value from server.json.

Example

AddEventHandler('playerJoining', function(name, deferrals)
    local src = source
    if GetNumPlayers() >= GetMaxPlayers() - 2 and not IsPlayerAceAllowed(src, 'queue.priority') then
        deferrals.done('The neighborhood is full right now. Try again in a few minutes!')
    end
end)

GetActivePlayers

ClientPlayer
table GetActivePlayers()

Returns every connected player, including yourself.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

This native takes no parameters.

Returns

table Server ids of everyone connected.

Example

for _, player in ipairs(GetActivePlayers()) do
    print(player, GetPlayerName(player), GetPlayerLot(player))
end

GetPlayerServerId

ClientPlayer
Player GetPlayerServerId(Player? player)

Returns a player's server id. Player ids on clients already are server ids, so this mostly exists for code ported from FiveM.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
playerPlayer?A player id, or nothing for yourself.

Returns

Player The server id.

Example

local me = GetPlayerServerId(PlayerId())

DoesPlayerExist

ServerPlayer
boolean DoesPlayerExist(Player player)

Checks whether a server id belongs to a connected player.

Server only. To show the result in a client UI, return it from a server callback or publish it in a state bag.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

boolean Whether that player is connected.

Example

RegisterCommand('slap', function(source, args)
    local target = tonumber(args[1])
    if not target or not DoesPlayerExist(target) then
        return print('No such player')
    end
    TriggerClientEvent('rtx_fun:slap', target)
end, true)

GetPlayerFromAccountId

ServerPlayer
Player? GetPlayerFromAccountId(string accountId)

Finds the server id of a player by their permanent account id.

Server only. To show the result in a client UI, return it from a server callback or publish it in a state bag.

Parameters

ParameterTypeDescription
accountIdstringAccount id from GetPlayerAccountId.

Returns

Player? Their server id, or nil if they are offline.

Example

local db = exports.neighborly:db()

CreateThread(function()
    while true do
        Wait(60000)
        for _, row in ipairs(db:find('reminder:')) do
            local player = GetPlayerFromAccountId(row.value.account)
            if player then
                TriggerClientEvent('neighborly:notify', player, { text = row.value.text })
                db:delete(row.key)
            end
        end
    end
end)

Sim

24 natives · Open Sim page

Read and change Sims: names, ages, needs, moods, buffs, skills, careers, outfits and interactions. A Sim id is a string. On the server, Sim natives are answered by the game of the player who owns that Sim, so they work for every connected player's Sims and wait for the answer – call them from a thread, an event handler or a command. On a client, they read and change Sims of your own household; for other players' Sims on your lot the client can read the name, age, gender, position and current interaction.

GetActiveSim

ClientSim
Sim? GetActiveSim()

Returns the Sim the local player controls. Same as GetPlayerCharacter(PlayerId()).

Cache it in a local and refresh it in playerSpawned and characterSelected instead of calling it every frame.

Parameters

This native takes no parameters.

Returns

Sim? The local player's Sim.

Example

RegisterCommand('whoami', function()
    local sim = GetActiveSim()
    if not sim then
        return ShowToast('Pick a character first.')
    end
    local first, last = GetSimName(sim)
    local mood = GetSimMood(sim)
    ShowNotification(('You are %s %s and you feel %s.'):format(first, last, mood), { sim = sim })
end, false)

DoesSimExist

SharedSim
boolean DoesSimExist(Sim sim)

Checks a Sim id. Always validate Sim ids coming from clients.

Sim ids sent by clients can be made up. Check them with DoesSimExist before you pass them to any server native.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

boolean Whether the id belongs to a Sim in the neighborhood.

Example

RegisterNetEvent('rtx_social:compliment', function(target)
    local src = source
    if type(target) ~= 'string' or not DoesSimExist(target) then
        return
    end
    local player = GetPlayerFromSim(target)
    if player and GetPlayerLot(player) == GetPlayerLot(src) then
        TriggerClientEvent('neighborly:notify', player, { text = GetPlayerName(src) .. ' likes your style!' })
    end
end)

GetSimName

SharedSim
string, string GetSimName(Sim sim)

Returns a Sim's first and last name.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

string, string First name and last name.

Example

AddEventHandler('playerSpawned', function(sim)
    local first, last = GetSimName(sim)
    ShowNotification(('Welcome home, %s %s!'):format(first, last), { title = 'Neighborly', sim = sim })
end)

GetSimAge

SharedSim
string GetSimAge(Sim sim)

Returns a Sim's life stage.

Use it to keep adult-only features away from children and teens – check on the server, not only in your client UI.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

string 'infant', 'toddler', 'child', 'teen', 'young_adult', 'adult' or 'elder'.

Example

local age = GetSimAge(GetPlayerCharacter(source))
if age == 'child' or age == 'teen' then
    return
end

GetSimGender

SharedSim
string GetSimGender(Sim sim)

Returns the gender set in Create a Sim.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

string 'male' or 'female' (the Sim's frame).

Example

local function greeting(sim)
    if GetSimGender(sim) == 'female' then
        return Config.Greetings.female
    end
    return Config.Greetings.male
end

RegisterNetEvent('rtx_cafe:hello', function()
    local src = source
    local sim = GetPlayerCharacter(src)
    if sim then
        TriggerClientEvent('neighborly:notify', src, { text = greeting(sim) })
    end
end)

GetSimPosition

SharedSim
vector3 GetSimPosition(Sim sim)

Returns where a Sim is standing.

Use #(a - b) to get the distance between two positions. On the server, distance checks are your main defence against players interacting with things across the map.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

vector3 World position.

Example

local distance = #(GetSimPosition(sim) - Config.Counter)
if distance > 3.0 then
    return
end

GetSimNeed

SharedSim
number GetSimNeed(Sim sim, string need)

Returns one need of a Sim. On a client it only works for Sims of your own household.

On the server the value comes from the owner's game, so it is always current. Townies and Sims of players who are offline can't be read.

Parameters

ParameterTypeDescription
simSimThe Sim.
needstring'hunger', 'energy', 'bladder', 'hygiene', 'social' or 'fun'.

Returns

number From -100 (empty) to 100 (full).

Example

CreateThread(function()
    local warned = false
    while true do
        local energy = GetSimNeed(GetActiveSim(), 'energy')
        if energy < -50 and not warned then
            exports.neighborly:notify({ text = 'You look exhausted. Time for bed?', type = 'warning' })
            warned = true
        elseif energy > 0 then
            warned = false
        end
        Wait(10000)
    end
end)

SetSimNeed

SharedSim
number SetSimNeed(Sim sim, string need, number value)

Sets one need of a Sim. The server asks the owner's game to change it; on a client it only works for your own household.

Values outside -100 to 100 are clamped. The change happens in the owner's game and shows up in their need panel straight away.

Parameters

ParameterTypeDescription
simSimThe Sim.
needstring'hunger', 'energy', 'bladder', 'hygiene', 'social' or 'fun'.
valuenumberFrom -100 to 100.

Returns

number The new value.

Example

RegisterNetEvent('rtx_food:eat', function(itemId)
    local src = source
    local item = Config.Food[itemId]
    local sim = GetPlayerCharacter(src)
    if not item or not sim or IsSimBusy(sim) then
        return
    end
    if not TakeMoney(src, item.price, 'Food: ' .. item.label) then
        return
    end
    SetSimNeed(sim, 'hunger', math.min(GetSimNeed(sim, 'hunger') + item.hunger, 100))
end)

GetSimMood

SharedSim
string, int GetSimMood(Sim sim)

Returns a Sim's current emotion and how strong it is.

The mood is calculated from the Sim's moodlets, so change it with AddSimBuff and RemoveSimBuff rather than directly.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

string, int Mood ('happy', 'confident', 'energized', 'flirty', 'focused', 'inspired', 'playful', 'fine', 'bored', 'dazed', 'embarrassed', 'sad', 'tense', 'angry', 'uncomfortable', 'scared') and intensity 1–3.

Example

local mood, intensity = GetSimMood(sim)
if mood == 'angry' and intensity >= 2 then
    CancelSimInteractions(sim)
end

AddSimBuff

SharedSim
boolean AddSimBuff(Sim sim, string buff)

Adds a moodlet (buff) to a Sim. On a client it only works for your own household.

Use the buff's tuning name. Adding a buff the Sim already has refreshes it. Unknown names raise an error you can catch with pcall.

Parameters

ParameterTypeDescription
simSimThe Sim.
buffstringBuff tuning name, for example 'buff_Energized_Caffeinated'.

Returns

boolean true if the buff was added.

Example

RegisterNetEvent('rtx_spa:finishMassage', function()
    local src = source
    local sim = GetPlayerCharacter(src)
    if not sim or GetPlayerLot(src) ~= Config.SpaLot then
        return
    end
    if AddSimBuff(sim, 'relaxed_massage', 240) then
        TriggerClientEvent('neighborly:notify', src, { text = 'You feel wonderfully relaxed.', type = 'success' })
    end
end)

RemoveSimBuff

SharedSim
void RemoveSimBuff(Sim sim, string buff)

Removes a moodlet from a Sim. On a client it only works for your own household.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
simSimThe Sim.
buffstringThe buff to remove.

Returns

Nothing (void).

Example

RegisterNetEvent('rtx_spa:towel', function()
    local src = source
    local sim = GetPlayerCharacter(src)
    if sim and HasSimBuff(sim, 'uncomfortable_wet') then
        RemoveSimBuff(sim, 'uncomfortable_wet')
        AddSimBuff(sim, 'cozy', 60)
    end
end)

HasSimBuff

SharedSim
boolean HasSimBuff(Sim sim, string buff)

Checks for a moodlet.

Cheaper than looping over GetSimBuffs when you only care about one moodlet.

Parameters

ParameterTypeDescription
simSimThe Sim.
buffstringThe buff.

Returns

boolean Whether the Sim has it.

Example

if HasSimBuff(sim, 'caffeinated') then
    exports.neighborly:notify({ text = 'Maybe no more coffee today.' })
end

GetSimBuffs

SharedSim
table GetSimBuffs(Sim sim)

Returns all moodlets of a Sim.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

table List of { name, mood } for every visible buff.

Example

for _, buff in ipairs(GetSimBuffs(sim)) do
    print(buff.name, buff.mood, buff.minutesLeft)
end

GetSimSkillLevel

SharedSim
int GetSimSkillLevel(Sim sim, string skill)

Reads a skill level.

Skills use decimals for progress inside a level, so 3.5 means halfway to level 4. Compare with math.floor when you only need the level.

Parameters

ParameterTypeDescription
simSimThe Sim.
skillstringSkill name such as 'cooking', 'charisma', 'mixology', 'painting'.

Returns

int Level, 0 when the Sim hasn't started the skill.

Example

if GetSimSkillLevel(GetPlayerCharacter(source), 'cooking') < 3 then
    TriggerClientEvent('neighborly:notify', source, { text = 'You need cooking level 3 to work here.', type = 'error' })
    return
end

SetSimSkillLevel

SharedSim
int SetSimSkillLevel(Sim sim, string skill, number level)

Sets a skill level. On a client it only works for your own household.

Levels are clamped to the skill's maximum (usually 10, 5 for toddler and child skills). Raising a skill this way does not trigger level-up notifications; send your own with ShowNotification if you want one.

Parameters

ParameterTypeDescription
simSimThe Sim.
skillstringSkill name.
levelnumberNew level, up to the skill's maximum.

Returns

int The new level.

Example

RegisterNetEvent('rtx_cafe:practice', function()
    local src = source
    local sim = GetPlayerCharacter(src)
    if not sim or not Player(src).state.onDuty or IsSimBusy(sim) then
        return
    end
    local level = GetSimSkillLevel(sim, 'mixology')
    SetSimSkillLevel(sim, 'mixology', math.min(level + 0.25, 10))
    if math.floor(level + 0.25) > math.floor(level) then
        TriggerClientEvent('neighborly:notify', src, { text = 'Your mixology skill went up!', type = 'success' })
    end
end)

GetSimTraits

SharedSim
table GetSimTraits(Sim sim)

Returns a Sim's traits, including aspiration bonus traits.

Trait names are tuning names such as 'cheerful', 'foodie' or 'hot_headed'. Traits from packs only appear when the server requires that pack.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

table List of trait names.

Example

for _, trait in ipairs(GetSimTraits(sim)) do
    if trait == 'foodie' then
        AddSimBuff(sim, 'delicious_food', 60)
    end
end

GetSimCareer

SharedSim
string?, int GetSimCareer(Sim sim)

Returns the Sim's career.

Career names are tuning names like 'culinary' or 'painter'. Combine with Player(id).state.job when your own jobs and game careers should work together.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

string?, int Career name like 'culinary' and level, or nil without a career.

Example

local career, level = GetSimCareer(sim)
if career == 'culinary' and level >= 4 then
    Player(source).state:set('canCook', true, true)
end

PushSimInteraction

SharedSim
boolean PushSimInteraction(Sim sim, string interaction, Sim|Object? target)

Adds an interaction to the Sim's queue, as if the player had clicked it. Only works for Sims of the player's own household – on the server the owner's game runs it.

The interaction goes through the game's normal rules – if the target is in use or the Sim can't reach it, it fails like a player's click would. A partial name like 'sit' is matched against the interactions the target offers; use the full tuning name when you need one exact interaction.

Parameters

ParameterTypeDescription
simSimThe Sim.
interactionstringInteraction tuning name, or part of one: 'sit' picks the shortest matching interaction the target offers.
targetSim|Object?What to interact with. Leave it out for interactions on the Sim itself.

Returns

boolean true if the interaction was queued.

Example

RegisterNetEvent('rtx_cinema:takeSeat', function(seat)
    local src = source
    local sim = GetPlayerCharacter(src)
    if type(seat) ~= 'string' or not sim then
        return
    end
    if not PushSimInteraction(sim, 'sit', seat) then
        TriggerClientEvent('neighborly:notify', src, { text = 'That seat is taken.' })
    end
end)

CancelSimInteractions

SharedSim
boolean CancelSimInteractions(Sim sim)

Cancels everything in a Sim's interaction queue except the posture (standing or sitting).

Use it before a cutscene or a teleport, so the Sim doesn't walk back to whatever they were doing.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

boolean true if something was cancelled.

Example

RegisterCommand('freeze', function(source, args)
    local target = tonumber(args[1])
    local sim = target and GetPlayerCharacter(target)
    if not sim then
        return print('Usage: freeze <player id>')
    end
    CancelSimInteractions(sim)
    Player(target).state:set('frozen', true, true)
end, true)

IsSimBusy

SharedSim
boolean IsSimBusy(Sim sim)

Checks whether a Sim is doing something.

Useful before pushing interactions or teleporting – interrupting a Sim mid-interaction can look odd for everyone watching.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

boolean true while the Sim runs any interaction.

Example

if IsSimBusy(sim) then
    return exports.neighborly:notify({ text = 'Finish what you are doing first.' })
end

GetSimCurrentInteraction

SharedSim
string? GetSimCurrentInteraction(Sim sim)

Returns what the Sim is doing right now.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

string? Name of the running interaction.

Example

if GetSimCurrentInteraction(sim) == 'sleep' then
    print('Shh, they are sleeping')
end

GetSimOutfit

SharedSim
string, int GetSimOutfit(Sim sim)

Returns which outfit a Sim is wearing.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

string, int Outfit category ('everyday', 'formal', 'athletic', 'sleep', 'party', 'swimwear', 'hot_weather', 'cold_weather', 'career') and index.

Example

RegisterNetEvent('rtx_cafe:clockIn', function()
    local src = source
    local category = GetSimOutfit(GetPlayerCharacter(src))
    if category ~= 'career' then
        return TriggerClientEvent('neighborly:notify', src, { text = 'Put on your work uniform first.' })
    end
    Player(src).state:set('onDuty', true, true)
end)

GetSimHousehold

SharedSim
HouseholdId? GetSimHousehold(Sim sim)

Returns the household a Sim belongs to.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

HouseholdId? The Sim's household.

Example

RegisterNetEvent('rtx_social:visitCard', function(target)
    local src = source
    local sim = type(target) == 'number' and DoesSimExist(target) and target
    local householdId = sim and GetSimHousehold(sim)
    if not householdId then
        return
    end
    local home = GetHouseholdHome(householdId)
    TriggerClientEvent('neighborly:notify', src, {
        title = 'The ' .. GetHouseholdName(householdId) .. ' household',
        text = home and ('They live at ' .. GetLotName(home)) or 'They are looking for a home.'
    })
end)

GetSimNeeds

SharedSim
table GetSimNeeds(Sim sim)

Returns all needs of a Sim in one call – cheaper than calling GetSimNeed six times.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
simSimThe Sim.

Returns

table { hunger, energy, bladder, hygiene, social, fun, ... } from -100 to 100.

Example

RegisterServerCallback('rtx_hud:needs', function(source)
    return GetSimNeeds(GetPlayerCharacter(source))
end)

Household

10 natives · Open Household page

Households are the families and roommate groups that live together and share funds and a home. Household natives on the server talk to the game of the player who plays that household.

GetHousehold

SharedHousehold
table? GetHousehold(HouseholdId householdId)

Returns a summary of a household.

A snapshot table – changing it changes nothing. Use the household setters for changes.

Parameters

ParameterTypeDescription
householdIdHouseholdIdThe household.

Returns

table? { id, name, funds, members, home }.

Example

RegisterCommand('family', function(source)
    local household = GetHousehold(GetPlayerHousehold(source))
    if not household then
        return
    end
    TriggerClientEvent('neighborly:notify', source, {
        title = 'The ' .. household.name .. ' household',
        text = ('%d members · %s'):format(#household.members, FormatMoney(household.funds))
    })
end, false)

GetPlayerHousehold

SharedHousehold
HouseholdId? GetPlayerHousehold(Player player)

Returns the household a player is playing.

Households own lots and money in the game. Many ownership checks boil down to GetLotOwner(zoneId) == GetPlayerHousehold(player).

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

HouseholdId? The household of the player's current character.

Example

RegisterNetEvent('rtx_realty:appraise', function()
    local src = source
    local householdId = GetPlayerHousehold(src)
    local home = householdId and GetHouseholdHome(householdId)
    if not home then
        return TriggerClientEvent('neighborly:notify', src, { text = 'You do not own a home.' })
    end
    TriggerClientEvent('neighborly:notify', src, {
        text = ('%s is worth %s.'):format(GetLotName(home), FormatMoney(GetLotValue(home) or 0))
    })
end)

GetHouseholdName

SharedHousehold
string GetHouseholdName(HouseholdId householdId)

Returns the household name.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
householdIdHouseholdIdThe household.

Returns

string Family name.

Example

AddEventHandler('householdMovedIn', function(householdId, zoneId)
    SendChatMessage(-1, 'Welcome Wagon', ('The %s family just moved into %s!'):format(GetHouseholdName(householdId), GetLotName(zoneId)), { 61, 220, 151 })
end)

GetHouseholdMembers

SharedHousehold
table GetHouseholdMembers(HouseholdId householdId)

Returns all Sims in a household, including roommates.

Includes members who are offline or played by nobody. Use GetPlayerFromSim to find the ones that are online right now.

Parameters

ParameterTypeDescription
householdIdHouseholdIdThe household.

Returns

table List of Sims.

Example

for _, sim in ipairs(GetHouseholdMembers(householdId)) do
    print(GetSimName(sim))
end

IsSimInHousehold

SharedHousehold
boolean IsSimInHousehold(Sim sim, HouseholdId householdId)

Checks household membership.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
simSimThe Sim.
householdIdHouseholdIdThe household.

Returns

boolean Whether the Sim belongs to it.

Example

if not IsSimInHousehold(GetPlayerCharacter(source), GetLotOwner(zoneId)) then
    return
end

GetHouseholdFunds

SharedHousehold
int GetHouseholdFunds(HouseholdId householdId)

Returns how much money a household has.

For most money features use the economy natives (GetBalance, TakeMoney …) – they act on the same funds but keep a transaction log.

Parameters

ParameterTypeDescription
householdIdHouseholdIdThe household.

Returns

int Household funds in simoleons.

Example

RegisterCommand('funds', function()
    local householdId = GetPlayerHousehold(PlayerId())
    if householdId then
        SendNUIMessage({ action = 'balance', value = FormatMoney(GetHouseholdFunds(householdId)) })
    end
end, false)

SetHouseholdFunds

ServerHousehold
void SetHouseholdFunds(HouseholdId householdId, int amount)

Sets household funds directly. Prefer AddHouseholdFunds or the economy natives, which keep a transaction log.

Writes the funds directly without a transaction log entry. Prefer AddHouseholdFunds, RemoveHouseholdFunds or the economy natives in gameplay code; keep this one for admin tools.

Parameters

ParameterTypeDescription
householdIdHouseholdIdThe household.
amountintNew amount, 0 or more.

Returns

Nothing (void).

Example

RegisterCommand('setfunds', function(source, args)
    local target, amount = tonumber(args[1]), tonumber(args[2])
    local householdId = target and GetPlayerHousehold(target)
    if not householdId or not amount or amount < 0 then
        return print('Usage: setfunds <player id> <amount>')
    end
    SetHouseholdFunds(householdId, math.floor(amount))
    print(('%s now has %s'):format(GetHouseholdName(householdId), FormatMoney(GetHouseholdFunds(householdId))))
end, true)

AddHouseholdFunds

ServerHousehold
int AddHouseholdFunds(HouseholdId householdId, int amount, string reason)

Adds money to a household.

Logged in the household's transaction history with your reason. Returns the new funds.

Parameters

ParameterTypeDescription
householdIdHouseholdIdThe household.
amountintAmount to add.
reasonstringShown in the transaction history.

Returns

int New funds.

Example

AddEventHandler('dayChanged', function(day, weekday)
    if weekday ~= 'friday' then
        return
    end
    for _, player in ipairs(GetPlayers()) do
        local householdId = GetPlayerHousehold(player)
        if householdId then
            AddHouseholdFunds(householdId, 150, 'Weekly neighborhood bonus')
        end
    end
end)

RemoveHouseholdFunds

ServerHousehold
boolean RemoveHouseholdFunds(HouseholdId householdId, int amount, string reason)

Takes money from a household if it has enough.

Checks and removes in one step, so funds can never go below zero.

Parameters

ParameterTypeDescription
householdIdHouseholdIdThe household.
amountintAmount to remove.
reasonstringShown in the transaction history.

Returns

boolean false if the household can't afford it – nothing is taken then.

Example

if not RemoveHouseholdFunds(householdId, 1200, 'Property tax') then
    print('Not enough money for the tax')
end

GetHouseholdHome

SharedHousehold
ZoneId? GetHouseholdHome(HouseholdId householdId)

Returns where a household lives.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
householdIdHouseholdIdThe household.

Returns

ZoneId? Home lot, or nil if homeless.

Example

local home = GetHouseholdHome(GetPlayerHousehold(source))
if home then
    TravelToLot(source, home)
end

Lot

13 natives · Open Lot page

Lots are the homes, venues and community spaces of a world, identified by their ZoneId (a string). The server knows every lot and who owns it; clients know the lots of the server they are connected to.

GetCurrentLot

ClientLot
ZoneId? GetCurrentLot()

Returns the lot the local player is on.

Changes only when the player travels. Instead of polling it, listen to lotEntered and lotLeft and keep the value in a local.

Parameters

This native takes no parameters.

Returns

ZoneId? Lot the local player is on.

Example

RegisterCommand('where', function()
    local zoneId = GetCurrentLot()
    if not zoneId then
        return ShowToast('You are travelling.')
    end
    ShowToast(('%s · %s'):format(GetLotName(zoneId), GetWorldName(GetLotWorld(zoneId))), 3000)
end, false)

GetLotName

SharedLot
string GetLotName(ZoneId zoneId)

Returns a lot's name.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
zoneIdZoneIdZone id of the lot.

Returns

string The lot's name.

Example

AddEventHandler('lotEntered', function(zoneId)
    exports.neighborly:notify({ text = 'Welcome to ' .. GetLotName(zoneId), icon = 'house', duration = 3000 })
end)

GetLotOwner

ServerLot
HouseholdId? GetLotOwner(ZoneId zoneId)

Returns the household that owns a lot.

Use GetLotOwnerPlayer when you want to send an event to the owner – it returns their server id while they are online.

Parameters

ParameterTypeDescription
zoneIdZoneIdZone id of the lot.

Returns

HouseholdId? Household that owns the lot.

Example

RegisterNetEvent('rtx_doorbell:ring', function(zoneId)
    local src = source
    if GetLotOwner(zoneId) == GetPlayerHousehold(src) then
        return TriggerClientEvent('neighborly:notify', src, { text = 'This is your own home.' })
    end
    local owner = GetLotOwnerPlayer(zoneId)
    if owner then
        TriggerClientEvent('rtx_doorbell:ding', owner, GetPlayerName(src))
    end
end)

GetLotType

SharedLot
string GetLotType(ZoneId zoneId)

Returns the lot type.

Rental lots need For Rent (EP15) on the server. Community lots have no owner household.

Parameters

ParameterTypeDescription
zoneIdZoneIdZone id of the lot.

Returns

string 'residential', 'community' or 'other'.

Example

if GetLotType(zoneId) ~= 'residential' then
    return
end

GetLotValue

SharedLot
int GetLotValue(ZoneId zoneId)

Returns what the lot is worth.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
zoneIdZoneIdZone id of the lot.

Returns

int Value in simoleons including furniture.

Example

RegisterCommand('appraise', function()
    local zoneId = GetCurrentLot()
    if not zoneId then
        return
    end
    ShowNotification(('%s is worth %s.'):format(GetLotName(zoneId), FormatMoney(GetLotValue(zoneId))), {
        title = 'Home appraisal',
        icon = 'house'
    })
end, false)

IsLotPublic

SharedLot
boolean IsLotPublic(ZoneId zoneId)

Checks whether a lot is open to all players.

Public lots can be visited by anyone without an invitation. Residential lots belong to a household.

Parameters

ParameterTypeDescription
zoneIdZoneIdZone id of the lot.

Returns

boolean true if anyone may visit.

Example

if not IsLotPublic(zoneId) then
    exports.neighborly:notify({ text = 'This is a private home.', type = 'warning' })
end

GetLotWorld

SharedLot
string GetLotWorld(ZoneId zoneId)

Returns the world a lot is in.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
zoneIdZoneIdZone id of the lot.

Returns

string World id.

Example

RegisterNetEvent('rtx_taxi:quote', function(zoneId)
    local src = source
    local from = GetPlayerLot(src)
    if type(zoneId) ~= 'string' or not from or not GetLotName(zoneId) then
        return
    end
    local price = GetLotWorld(zoneId) == GetLotWorld(from) and 25 or 60
    TriggerClientEvent('neighborly:notify', src, {
        text = ('A ride to %s in %s costs %s.'):format(GetLotName(zoneId), GetLotWorld(zoneId), FormatMoney(price))
    })
end)

GetLotsInWorld

SharedLot
table GetLotsInWorld(string world)

Returns every lot in a world.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
worldstringWorld id, see GetWorlds.

Returns

table List of zone ids.

Example

for _, zoneId in ipairs(GetLotsInWorld('willow_creek')) do
    if GetLotOwner(zoneId) == nil and GetLotType(zoneId) == 'residential' then
        print('For sale:', GetLotName(zoneId))
    end
end

GetSimsOnLot

ClientLot
table GetSimsOnLot(ZoneId? zoneId)

Returns every Sim on the lot the local player is on.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
zoneIdZoneId?Must be the lot you are on. Leave it out for the current lot.

Returns

table List of Sims, including townies. Other players' Sims are returned with their real ids.

Example

CreateThread(function()
    while true do
        local zoneId = GetCurrentLot()
        if zoneId then
            SendNUIMessage({ action = 'crowd', count = #GetSimsOnLot(zoneId) })
        end
        Wait(5000)
    end
end)

GetPlayersOnLot

ServerLot
table GetPlayersOnLot(ZoneId zoneId)

Returns the players whose Sims are on a lot.

The fastest way to send something to “everyone here” – loop over it and trigger a client event for each player.

Parameters

ParameterTypeDescription
zoneIdZoneIdZone id of the lot.

Returns

table List of server ids.

Example

for _, player in ipairs(GetPlayersOnLot(zoneId)) do
    TriggerClientEvent('neighborly:notify', player, { text = 'Last call!' })
end

TravelToLot

SharedLot
boolean TravelToLot(Player player, ZoneId zoneId)

Sends a player's Sim to another lot with the normal travel loading screen. On a client, call it with just the zone id to travel yourself.

Respects locks and privacy: returns false when the player isn't allowed on that lot.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.
zoneIdZoneIdZone id of the lot.

Returns

boolean false if the lot doesn't exist.

Example

RegisterNetEvent('rtx_taxi:go', function(zoneId)
    local src = source
    if IsLotPublic(zoneId) and TakeMoney(src, 20, 'Taxi') then
        TravelToLot(src, zoneId)
    end
end)

GetLotOwnerPlayer

ServerLot
Player? GetLotOwnerPlayer(ZoneId zoneId)

Returns the player who owns a lot, if they are connected.

Server only. To show the result in a client UI, return it from a server callback or publish it in a state bag.

Parameters

ParameterTypeDescription
zoneIdZoneIdZone id of the lot.

Returns

Player? Server id of the owner while they are online.

Example

RegisterNetEvent('rtx_doorbell:ring', function(zoneId)
    local owner = GetLotOwnerPlayer(zoneId)
    if owner then
        TriggerClientEvent('rtx_doorbell:ding', owner, GetPlayerName(source))
    end
end)

GetLotOwnerAccount

ServerLot
string? GetLotOwnerAccount(ZoneId zoneId)

Returns the account id of a lot's owner, even when they are offline.

Server only. To show the result in a client UI, return it from a server callback or publish it in a state bag.

Parameters

ParameterTypeDescription
zoneIdZoneIdZone id of the lot.

Returns

string? Account id of the owner.

Example

local db = exports.neighborly:db()

RegisterNetEvent('rtx_mail:send', function(zoneId, text)
    local owner = GetLotOwnerAccount(zoneId)
    if owner and type(text) == 'string' then
        db:set('mail:' .. owner .. ':' .. os.time(), { from = GetPlayerName(source), text = text:sub(1, 200) })
    end
end)

Object

13 natives · Open Object page

Objects are everything placed on a lot – fridges, beds, espresso machines, doors. Objects are identified by their tuning name (find it with GetObjectDefinition on one placed in the world) or definition id. Object natives run on the client, against the lot the player is on. Objects created with CreateObject are local to that player and temporary: they are never saved and disappear when the lot unloads or the resource stops. To show something to everyone on a lot, send a client event to everyone there and let each client create it.

CreateObject

ClientObject
Object CreateObject(string|int definition, vector3 coords, number? heading)

Creates a temporary object for the local player on the current lot. It is never saved, only this player sees it, and it is removed when the resource stops or the lot unloads. Objects from packs the server doesn't use are refused.

Script objects are perfect for props, decorations and effects. Track the ids you create and delete them in onResourceStop – Neighborly also removes them for you when the resource stops.

Parameters

ParameterTypeDescription
definitionstring|intObject tuning name or definition id.
coordsvector3Where to put it.
headingnumber?Rotation in degrees.

Returns

Object The new object.

Example

local balloon

RegisterNetEvent('rtx_party:balloon', function(coords)
    if balloon then
        DeleteObject(balloon)
    end
    balloon = CreateObject(Config.BalloonObject, coords, 90.0)
end)

DeleteObject

ClientObject
boolean DeleteObject(Object object)

Removes an object that this player's scripts created with CreateObject. Furniture placed in Build mode can't be deleted by scripts.

The object disappears for every player and its entity state bag is removed. Deleting objects players built themselves should always need their permission.

Parameters

ParameterTypeDescription
objectObjectThe object.

Returns

boolean true if it was removed.

Example

local spawned = {}

RegisterCommand('confetti', function()
    local pos = GetSimPosition(GetActiveSim())
    spawned[#spawned + 1] = CreateObject(Config.PropObject, pos + vector3(1.0, 0.0, 0.0))
end, false)

RegisterCommand('cleanup', function()
    for _, object in ipairs(spawned) do
        DeleteObject(object)
    end
    spawned = {}
end, false)

DoesObjectExist

ClientObject
boolean DoesObjectExist(Object object)

Checks whether an object with that id is on the lot you are on.

Object ids only make sense on the lot the player is on. To tell the server about an object, send its position or definition – the server can't look objects up.

Parameters

ParameterTypeDescription
objectObjectThe object.

Returns

boolean Whether the id belongs to an object.

Example

RegisterNetEvent('rtx_notes:show', function(object, text)
    if type(object) ~= 'string' or not DoesObjectExist(object) then
        return
    end
    ShowHelpText(text, 5000)
end)

GetObjectsOnLot

ClientObject
table GetObjectsOnLot(ZoneId? zoneId, string|int? definition)

Returns objects on a lot, optionally filtered.

Works for lots the side has loaded: on a client that is the current lot. Filtering by definition is much faster than filtering the full list in Lua.

Parameters

ParameterTypeDescription
zoneIdZoneId?Must be the lot you are on, or nil.
definitionstring|int?Only objects of this tuning name or definition id.

Returns

table List of objects.

Example

RegisterCommand('fridges', function()
    local fridges = GetObjectsOnLot(nil, Config.FridgeObject)
    exports.neighborly:notify({ text = ('%d fridges on this lot.'):format(#fridges) })
end, false)

GetClosestObject

ClientObject
Object? GetClosestObject(vector3 coords, string|int? definition, number? radius)

Finds the nearest object.

Searches the lot the coordinates are on. Keep the radius small; on a client it only sees the current lot.

Parameters

ParameterTypeDescription
coordsvector3Search center.
definitionstring|int?Only this definition.
radiusnumber?Max distance, default 5.0.

Returns

Object? Closest match.

Example

RegisterCommand('register', function()
    local register = GetClosestObject(GetSimPosition(GetActiveSim()), 'object_register_cafe', 3.0)
    if not register then
        return ShowToast('Walk up to the cash register first.')
    end
    exports.neighborly:showContext('cafe_register')
end, false)

GetObjectDefinition

ClientObject
string GetObjectDefinition(Object object)

Returns what kind of object it is.

The tuning name of the object's catalog entry, for example 'object_fridge_basic'. It is the same on every machine, so it is safe to compare in client and server code.

Parameters

ParameterTypeDescription
objectObjectThe object.

Returns

string Tuning name of the object.

Example

if GetObjectDefinition(object) ~= 'object_coffeeMaker_espresso' then
    return
end

GetObjectPack

ClientObject
string GetObjectPack(Object object)

Returns the pack an object comes from.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
objectObjectThe object.

Returns

string Pack code like 'EP01', 'BG' for the base game.

Example

RegisterCommand('whatpack', function()
    local object = GetClosestObject(GetSimPosition(GetActiveSim()), nil, 2.0)
    if object then
        local pack = GetObjectPack(object)
        ShowToast(('%s comes from %s'):format(GetObjectDefinition(object), GetPackName(pack) or pack))
    end
end, false)

GetObjectLot

ClientObject
ZoneId? GetObjectLot(Object object)

Returns the lot an object is on – the current lot if the object exists, otherwise nil.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
objectObjectThe object.

Returns

ZoneId? Lot the object is on.

Example

local function isHere(object)
    return GetObjectLot(object) == GetCurrentLot()
end

GetObjectPosition

ClientObject
vector3, number GetObjectPosition(Object object)

Returns where an object is.

Object ids are only meaningful on the lot they belong to. Send positions to the server, not object ids, when other players need to know where something is.

Parameters

ParameterTypeDescription
objectObjectThe object.

Returns

vector3, number Position and heading in degrees.

Example

RegisterCommand('bell', function()
    local bell = GetClosestObject(GetSimPosition(GetActiveSim()), Config.BellObject, 3.0)
    if not bell then
        return ShowToast('Walk up to the bell first.')
    end
    local coords = GetObjectPosition(bell)
    TriggerServerEvent('rtx_cafe:ringBell', coords)
end, false)

SetObjectPosition

ClientObject
boolean SetObjectPosition(Object object, vector3 coords, number? heading)

Moves an object that this player's scripts created with CreateObject.

Moves the object for everyone, without placement checks – make sure the spot is free and on the same lot.

Parameters

ParameterTypeDescription
objectObjectThe object.
coordsvector3New position.
headingnumber?Rotation in degrees. Leave it out to keep the current one.

Returns

boolean true when it moved.

Example

local sign = CreateObject(Config.SignObject, Config.SignCoords)

RegisterCommand('movesign', function()
    SetObjectPosition(sign, GetSimPosition(GetActiveSim()) + vector3(0.0, 0.0, 1.5), 180.0)
end, false)

IsObjectInUse

ClientObject
boolean, Sim? IsObjectInUse(Object object)

Checks whether a Sim is using an object.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
objectObjectThe object.

Returns

boolean, Sim? Whether it's in use and by which Sim.

Example

local inUse, user = IsObjectInUse(object)
if inUse then
    print(GetSimName(user) .. ' is using it')
end

GetObjectUsers

ClientObject
table GetObjectUsers(Object object)

Returns all Sims using an object (sofas and tables can have several).

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
objectObjectThe object.

Returns

table List of Sims.

Example

RegisterCommand('sofa', function()
    local sofa = GetClosestObject(GetSimPosition(GetActiveSim()), nil, 3.0)
    if not sofa then
        return
    end
    for _, sim in ipairs(GetObjectUsers(sofa)) do
        local first = GetSimName(sim)
        AddChatMessage('Sofa', first .. ' is sitting here')
    end
end, false)

GetObjectPrice

ClientObject
int GetObjectPrice(Object object)

Returns an object's current value in simoleons.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
objectObjectThe object.

Returns

int Current value in simoleons.

Example

RegisterCommand('appraise', function()
    local object = GetClosestObject(GetSimPosition(GetActiveSim()), nil, 2.0)
    if object then
        ShowToast(GetObjectDefinition(object) .. ' is worth ' .. FormatMoney(GetObjectPrice(object)))
    end
end, false)

World

9 natives · Open World page

The shared clock, calendar, seasons, worlds and sounds. Neighborly servers run in real time, so every player sees the same hour.

GetGameTime

SharedWorld
int, int GetGameTime()

Returns the time on the neighborhood clock. It is the same for every player.

The neighborhood clock is shared: every player sees the same time. It moves according to the server's game speed, not real time. For cooldowns use GetGameTimer.

Parameters

This native takes no parameters.

Returns

int, int Hour (0–23) and minute.

Example

CreateThread(function()
    while true do
        local hour, minute = GetGameTime()
        GlobalState.cafeOpen = hour >= 7 and hour < 22
        Wait(10000)
    end
end)

SetGameTime

ServerWorld
void SetGameTime(int hour, int? minute)

Sets the neighborhood clock for everyone.

Changes the clock for every player at once. Jumping forward does not fast-forward needs – it only moves the clock.

Parameters

ParameterTypeDescription
hourint0–23.
minuteint?0–59.

Returns

Nothing (void).

Example

RegisterCommand('time', function(source, args)
    local hour, minute = tonumber(args[1]), tonumber(args[2]) or 0
    if not hour or hour < 0 or hour > 23 then
        return print('Usage: time <hour> [minute]')
    end
    SetGameTime(hour, minute)
    SendChatMessage(-1, 'World', ('The clock was set to %02d:%02d.'):format(hour, minute))
end, true)

GetGameDay

SharedWorld
int, string GetGameDay()

Returns the current day.

Days count up from the server's first start, so they work for weekly events. Listen to dayChanged instead of polling.

Parameters

This native takes no parameters.

Returns

int, string Day number and weekday name.

Example

local day, weekday = GetGameDay()
if weekday == 'saturday' then
    GlobalState.marketDay = true
end

GetGameSpeed

SharedWorld
int GetGameSpeed()

Returns the game speed. It exists for compatibility; time never runs faster or pauses on a server.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

This native takes no parameters.

Returns

int Always 1 – Neighborly servers run in real time.

Example

CreateThread(function()
    while true do
        SendNUIMessage({ action = 'speed', paused = GetGameSpeed() == 0 })
        Wait(1000)
    end
end)

GetSeason

ClientWorld
string? GetSeason()

Returns the current season in the player's game.

Seasons run in each player's own game, so ask on the client.

Parameters

This native takes no parameters.

Returns

string? 'spring', 'summer', 'fall', 'winter', or nil without Seasons (EP05).

Example

AddEventHandler('lotEntered', function()
    local season = GetSeason()
    SendNUIMessage({ action = 'menu', items = Config.Menus[season or 'summer'] })
end)

GetWorlds

SharedWorld
table GetWorlds()

Returns the worlds players can live in, depending on the server's packs.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

This native takes no parameters.

Returns

table List of world names, like 'Willow Creek'.

Example

for _, world in ipairs(GetWorlds()) do
    print(world, GetWorldName(world))
end

GetWorldName

SharedWorld
string GetWorldName(string world)

Returns a world's display name.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
worldstringWorld id like 'willow_creek'.

Returns

string Display name like 'Willow Creek'.

Example

RegisterCommand('worlds', function()
    for _, world in ipairs(GetWorlds()) do
        AddChatMessage('Worlds', ('%s – %d lots'):format(GetWorldName(world), #GetLotsInWorld(world)))
    end
end, false)

GetCurrentWorld

ClientWorld
string? GetCurrentWorld()

Returns the world the local player is in.

World ids look like 'willow_creek'; turn them into names with GetWorldName.

Parameters

This native takes no parameters.

Returns

string? Name of the world the local player is in.

Example

if GetCurrentWorld() == 'newcrest' then
    exports.neighborly:notify({ text = 'Welcome to Newcrest!' })
end

PlaySoundFrontend

ClientWorld
void PlaySoundFrontend(string sound, number? volume)

Plays a sound only the local player hears.

Only the local player hears it – ideal for UI clicks and personal alerts.

Parameters

ParameterTypeDescription
soundstringGame UI sound name or nui:// path.
volumenumber?0.0–1.0.

Returns

Nothing (void).

Example

RegisterNetEvent('rtx_cafe:tipReceived', function(amount)
    PlaySoundFrontend('ui_cash_register', 0.8)
    ShowToast('+' .. FormatMoney(amount) .. ' tip', 2000)
end)

UI

8 natives · Open UI page

Game-style notifications, dialogs, subtitles, markers and the HUD on the local player's screen.

ShowNotification

ClientUI
void ShowNotification(string text, table? options)

Posts a real Sims 4 notification that stays in the notification history.

Unlike the Neighborly notify toast, these notifications stay in the game's notification wall. Pass sim to show a portrait.

Parameters

ParameterTypeDescription
textstringMessage.
optionstable?{ title, sim, icon, buttons } – sim shows that Sim's portrait.

Returns

Nothing (void).

Example

ShowNotification('Your landlord says hi and reminds you about the rent.', {
    title = 'Message from your landlord',
    icon = 'letter'
})

ShowToast

ClientUI
void ShowToast(string text, int? duration)

Shows a short line in the middle of the screen that fades away.

Toasts don't stack – a new one replaces the old one. For messages players should be able to read later, use ShowNotification.

Parameters

ParameterTypeDescription
textstringMessage.
durationint?Milliseconds, default 3000.

Returns

Nothing (void).

Example

RegisterNUICallback('saveSettings', function(data, cb)
    SetResourceKvp('settings', data)
    ShowToast('Settings saved', 1500)
    cb({ ok = true })
end)

ShowDialog

ClientUI
string ShowDialog(table options)

Shows a Sims 4 style dialog and waits for the answer. Call it in a thread.

The calling thread waits until the player answers. For forms with several fields use exports.neighborly:inputDialog.

Parameters

ParameterTypeDescription
optionstable{ title, text, okLabel, cancelLabel, sim }.

Returns

string 'ok' or 'cancel'.

Example

local answer = ShowDialog({
    title = 'Job offer',
    text = 'Bluejay Café wants to hire you as a barista. Accept?',
    okLabel = 'Accept',
    cancelLabel = 'Decline'
})
if answer == 'ok' then
    TriggerServerEvent('rtx_cafe:acceptJob')
end

ShowSubtitle

ClientUI
void ShowSubtitle(string text, int? duration)

Shows a subtitle at the bottom of the screen, like a line of dialogue.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
textstringSubtitle text.
durationint?Milliseconds, default 4000.

Returns

Nothing (void).

Example

RegisterNetEvent('rtx_cafe:orderTaken', function(baristaName, drink)
    ShowSubtitle(('%s: One %s, coming right up!'):format(baristaName, drink), 4000)
end)

ShowHelpText

ClientUI
void ShowHelpText(string text, int? duration)

Shows a help box in the top left corner.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
textstringHelp text. ~F10~ renders a key icon.
durationint?Milliseconds, default 5000.

Returns

Nothing (void).

Example

AddEventHandler('playerSpawned', function()
    if not GetResourceKvp('seenPhoneHint') then
        ShowHelpText('Press ~F10~ to open your phone.', 8000)
        SetResourceKvp('seenPhoneHint', true)
    end
end)

ShowPhoneMessage

ClientUI
void ShowPhoneMessage(string from, string text, string? icon)

Makes the Sim's phone buzz with a text message.

Shows up like a text from another Sim, with the phone buzz. Good for job offers, deliveries and doorbells.

Parameters

ParameterTypeDescription
fromstringSender name.
textstringMessage.
iconstring?Contact icon.

Returns

Nothing (void).

Example

RegisterNetEvent('rtx_phone:sms', function(from, text)
    ShowPhoneMessage(from, text, 'chat')
end)

SetHudVisible

ClientUI
void SetHudVisible(boolean visible)

Shows or hides the game HUD – useful for screenshots and cutscenes.

Hides the game HUD only – NUI pages and Neighborly notifications stay. Remember to show it again.

Parameters

ParameterTypeDescription
visiblebooleanShow or hide.

Returns

Nothing (void).

Example

RegisterCommand('photomode', function()
    local hide = IsHudVisible()
    SetHudVisible(not hide)
    SetChatVisible(not hide)
    ShowToast(hide and 'Photo mode on' or 'Photo mode off', 1200)
end, false)

Camera

5 natives · Open Camera page

Read and move the local player's camera.

GetCameraPosition

ClientCamera
vector3 GetCameraPosition()

Returns where the camera is.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

This native takes no parameters.

Returns

vector3 Camera position.

Example

RegisterCommand('campos', function()
    local pos = GetCameraPosition()
    local text = ('vector3(%.2f, %.2f, %.2f)'):format(pos.x, pos.y, pos.z)
    AddChatMessage('Camera', text)
    print(text)
end, false)

GetCameraTarget

ClientCamera
vector3 GetCameraTarget()

Returns the camera's focus point.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

This native takes no parameters.

Returns

vector3 Point the camera looks at.

Example

RegisterCommand('markspot', function()
    TriggerServerEvent('rtx_events:markSpot', GetCameraTarget())
end, false)

FocusCameraOnSim

ClientCamera
void FocusCameraOnSim(Sim sim, boolean? instant)

Moves the camera to a Sim.

With instant the camera jumps; otherwise it glides like when clicking a Sim's portrait.

Parameters

ParameterTypeDescription
simSimThe Sim.
instantboolean?Jump instead of gliding.

Returns

Nothing (void).

Example

RegisterNetEvent('rtx_wedding:vows', function(brideSim, groomSim)
    FocusCameraOnSim(brideSim)
    Wait(5000)
    FocusCameraOnSim(groomSim)
end)

FocusCameraOnLot

ClientCamera
void FocusCameraOnLot(ZoneId zoneId)

Moves the camera to show a whole lot.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
zoneIdZoneIdZone id of the lot.

Returns

Nothing (void).

Example

RegisterNetEvent('rtx_realty:showLot', function(zoneId)
    FocusCameraOnLot(zoneId)
    ShowNotification(('%s – %s'):format(GetLotName(zoneId), FormatMoney(GetLotValue(zoneId))), { title = 'For sale' })
end)

FocusCameraOnCoords

ClientCamera
void FocusCameraOnCoords(vector3 coords, number? zoom)

Moves the camera to a point.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
coordsvector3Point to look at.
zoomnumber?0.0 (close) to 1.0 (far).

Returns

Nothing (void).

Example

RegisterNetEvent('rtx_stage:spotlight', function()
    FocusCameraOnCoords(Config.StageCoords, 25.0)
    ShowSubtitle('The show is about to begin!', 6000)
end)

Chat

7 natives · Open Chat page

Send messages to the F7 chat and manage suggestions.

SendChatMessage

ServerChat
void SendChatMessage(Player target, string author, string text, table? color)

Sends a chat message to one player or everyone.

Pass -1 to send to everyone. For messages only players on one lot should see, loop over GetPlayersOnLot.

Parameters

ParameterTypeDescription
targetPlayerServer id or -1 for everyone.
authorstringName shown in front.
textstringMessage.
colortable?{ r, g, b }.

Returns

Nothing (void).

Example

AddEventHandler('dayChanged', function(day, weekday)
    if weekday == 'friday' then
        SendChatMessage(-1, 'Bluejay Café', 'Happy hour tonight: all drinks half price!', { 255, 179, 138 })
    end
end)

AddChatMessage

ClientChat
void AddChatMessage(string author, string text, table? color)

Adds a message to the local chat only.

Only the local player sees it. To reach other players, ask the server to use SendChatMessage.

Parameters

ParameterTypeDescription
authorstringName shown in front.
textstringMessage.
colortable?{ r, g, b }.

Returns

Nothing (void).

Example

AddEventHandler('playerSpawned', function()
    AddChatMessage('Tip', 'Use /dice to roll for everyone on your lot.', { 91, 192, 248 })
end)

AddChatSuggestion

ClientChat
void AddChatSuggestion(string name, string help, table? params)

Adds a chat suggestion. Same as the chat:addSuggestion event.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
namestringCommand with slash.
helpstringDescription.
paramstable?List of { name, help }.

Returns

Nothing (void).

Example

AddChatSuggestion('/dice', 'Roll a die for everyone on your lot', {
    { name = 'sides', help = 'Number of sides, 2 to 100 (default 6)' }
})

AddChatSuggestion('/tip', 'Tip another player', {
    { name = 'player', help = 'Their server id' },
    { name = 'amount', help = 'Simoleons, 1 to 500' }
})

RemoveChatSuggestion

ClientChat
void RemoveChatSuggestion(string name)

Removes a chat suggestion.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
namestringCommand with slash.

Returns

Nothing (void).

Example

AddEventHandler('onResourceStop', function(name)
    if name == GetCurrentResourceName() then
        RemoveChatSuggestion('/dice')
        RemoveChatSuggestion('/tip')
    end
end)

SetChatVisible

ClientChat
void SetChatVisible(boolean visible)

Hides or shows the chat window.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
visiblebooleanShow or hide.

Returns

Nothing (void).

Example

RegisterNetEvent('rtx_cinema:movieStarted', function()
    SetChatVisible(false)
    SetHudVisible(false)
end)

RegisterNetEvent('rtx_cinema:movieEnded', function()
    SetChatVisible(true)
    SetHudVisible(true)
end)

IsChatOpen

ClientChat
boolean IsChatOpen()

Checks whether the chat input is open – useful to ignore key presses while typing.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

This native takes no parameters.

Returns

boolean Whether the player is typing in chat.

Example

if IsChatOpen() then
    return
end

Economy

10 natives · Open Economy page

Money with a paper trail: payments, transfers, bills and transaction history. All amounts are whole simoleons.

GetBalance

ServerEconomy
int GetBalance(Player player)

Returns how much money a player has.

The balance is the player's household funds, read from their game. Read it right before you decide – never trust a balance a client sends you.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

int Funds of the player's household.

Example

RegisterNetEvent('rtx_shop:checkout', function(itemId)
    local src = source
    local item = Config.Items[itemId]
    if not item then
        return
    end
    if GetBalance(src) < item.price then
        return TriggerClientEvent('neighborly:notify', src, {
            text = ('You need %s more.'):format(FormatMoney(item.price - GetBalance(src))),
            type = 'warning'
        })
    end
    TakeMoney(src, item.price, 'Shop: ' .. item.label)
end)

GiveMoney

ServerEconomy
boolean GiveMoney(Player player, int amount, string reason)

Gives a player money, logged in their transaction history.

Every call is written to the player's transaction history with your reason. Amounts are whole simoleons; decimals are rounded down.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.
amountintPositive amount.
reasonstringShown in the history.

Returns

boolean true on success.

Example

RegisterNetEvent('rtx_cafe:finishShift', function()
    local src = source
    local state = Player(src).state
    if not state.onDuty then
        return
    end
    local earned = math.min((state.servedThisShift or 0) * Config.PayPerDrink, Config.MaxShiftPay)
    state:set('onDuty', false, true)
    state:set('servedThisShift', 0, true)
    if earned > 0 then
        GiveMoney(src, earned, 'Café shift')
    end
end)

TakeMoney

ServerEconomy
boolean TakeMoney(Player player, int amount, string reason)

Takes money if the player has enough.

Checks and takes in one step, so two events can't spend the same simoleons twice. Always use the return value instead of checking GetBalance first.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.
amountintPositive amount.
reasonstringShown in the history.

Returns

boolean false if they can't afford it.

Example

if not TakeMoney(source, 12, 'Latte') then
    TriggerClientEvent('neighborly:notify', source, { text = 'Not enough simoleons.', type = 'error' })
end

TransferMoney

ServerEconomy
boolean TransferMoney(Player from, Player to, int amount, string reason)

Moves money between two players in one safe step.

Atomic: either both sides change or nothing happens. Both players get a history entry with your reason.

Parameters

ParameterTypeDescription
fromPlayerPayer.
toPlayerReceiver.
amountintAmount.
reasonstringShown to both.

Returns

boolean false if the payer can't afford it.

Example

RegisterNetEvent('rtx_cafe:tip', function(target, amount)
    local src = source
    if type(target) ~= 'number' or type(amount) ~= 'number' or target == src or not GetPlayerName(target) then
        return
    end
    amount = math.floor(amount)
    if amount < 1 or amount > 500 or GetPlayerLot(target) ~= GetPlayerLot(src) then
        return
    end
    if TransferMoney(src, target, amount, 'Tip') then
        TriggerClientEvent('rtx_cafe:tipReceived', target, amount)
    end
end)

CreateBill

ServerEconomy
int CreateBill(Player player, table bill)

Creates a bill for a player. Bills are kept by the server; show them in your own UI (see the phone example) and pay them with PayBill. Fires billCreated with the bill on the server.

Bills survive restarts. A bill with a payee pays that player when it is paid.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.
billtable{ label, amount, dueDays, payee } – payee is an optional player who gets the money.

Returns

int Bill id.

Example

RegisterNetEvent('rtx_cafe:openTab', function(customer, amount)
    local src = source
    if not Player(src).state.onDuty or type(customer) ~= 'number' or not GetPlayerName(customer) then
        return
    end
    if type(amount) ~= 'number' or amount < 1 or amount > 500 then
        return
    end
    local billId = CreateBill(customer, { label = 'Bluejay Café tab', amount = math.floor(amount), dueDays = 2, payee = src })
    print(('Bill %d sent to %s'):format(billId, GetPlayerName(customer)))
end)

GetBills

ServerEconomy
table GetBills(Player player)

Returns a player's open bills.

Only open bills. Paid and cancelled bills are gone from this list; payments show up in GetTransactions.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

table List of { id, label, amount, due, payee, from }. due is a Unix time or nil, payee the payee's server id while they are online, from the resource that created it.

Example

for _, bill in ipairs(GetBills(source)) do
    print(bill.id, bill.label, bill.amount)
end

PayBill

ServerEconomy
boolean PayBill(int billId)

Pays a bill from the debtor's funds and, if it has a payee, gives the money to them – if the payee is offline they get it the next time they play. Fires billPaid. The debtor must be connected.

Takes the money from the debtor and, if the bill has a payee, gives it to them – in one safe step.

Parameters

ParameterTypeDescription
billIdintBill id.

Returns

boolean false if not enough funds.

Example

RegisterNetEvent('rtx_phone:payBill', function(billId)
    local src = source
    for _, bill in ipairs(GetBills(src)) do
        if bill.id == billId then
            local ok = PayBill(billId)
            TriggerClientEvent('neighborly:notify', src, {
                text = ok and 'Bill paid.' or 'Not enough simoleons for this bill.',
                type = ok and 'success' or 'error'
            })
            return
        end
    end
end)

CancelBill

ServerEconomy
boolean CancelBill(int billId)

Cancels an open bill.

Server only: the change happens on the server and Neighborly syncs it to every player who can see it. Validate anything that came from a client before you call it.

Parameters

ParameterTypeDescription
billIdintBill id.

Returns

boolean true if an open bill was cancelled.

Example

RegisterCommand('forgivebills', function(source, args)
    local target = tonumber(args[1])
    if not target or not GetPlayerName(target) then
        return print('Usage: forgivebills <player id>')
    end
    for _, bill in ipairs(GetBills(target)) do
        CancelBill(bill.id)
    end
    TriggerClientEvent('neighborly:notify', target, { text = 'Your bills were forgiven!', type = 'success' })
end, true)

GetTransactions

ServerEconomy
table GetTransactions(Player player, int? limit)

Returns a player's transaction history.

Includes every change made through GiveMoney, TakeMoney, TransferMoney and PayBill, with your reason texts. The server keeps the last 250 entries per player.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.
limitint?How many, newest first. Default 20.

Returns

table List of { amount, reason, time }, newest first. Negative amounts are payments.

Example

for _, t in ipairs(GetTransactions(source, 5)) do
    print(os.date('%H:%M', t.time), t.amount, t.reason)
end

FormatMoney

SharedEconomy
string FormatMoney(int amount)

Formats an amount as simoleons.

Uses the simoleon sign and thousands separators: FormatMoney(1250) returns §1,250.

Parameters

ParameterTypeDescription
amountintAmount.

Returns

string Formatted like §1,250.

Example

RegisterCommand('wallet', function(source)
    TriggerClientEvent('neighborly:notify', source, {
        title = 'Wallet',
        text = 'You have ' .. FormatMoney(GetBalance(source)) .. '.',
        icon = 'money'
    })
end, false)

Packs

6 natives · Open Packs page

Find out which packs the server requires and which ones players own.

IsPackInstalled

ClientPacks
boolean IsPackInstalled(string pack)

Checks whether the local player has a pack installed, even if the server doesn't require it.

A pack the player owns but the server doesn't require can't be used for shared gameplay – other players may not have it. Use it for local extras only.

Parameters

ParameterTypeDescription
packstringPack code like 'EP01'.

Returns

boolean Whether the local player owns it.

Example

if IsPackInstalled('SP13') then
    print('You have Laundry Day')
end

GetRequiredPacks

SharedPacks
table GetRequiredPacks()

Returns the packs every player on this server has.

Every player on the server owns all of these, so objects, worlds and interactions from them are safe to use.

Parameters

This native takes no parameters.

Returns

table Pack codes from requiredPacks.

Example

local seasons = false
for _, pack in ipairs(GetRequiredPacks()) do
    if pack == 'EP05' then
        seasons = true
    end
end

GetPlayerPacks

ServerPacks
table GetPlayerPacks(Player player)

Returns every pack a player owns.

Server only. To show the result in a client UI, return it from a server callback or publish it in a state bag.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.

Returns

table Pack codes the player owns.

Example

RegisterCommand('packs', function(source, args)
    local target = tonumber(args[1]) or source
    local names = {}
    for _, pack in ipairs(GetPlayerPacks(target)) do
        names[#names + 1] = GetPackName(pack)
    end
    print(('%s owns %d packs: %s'):format(GetPlayerName(target), #names, table.concat(names, ', ')))
end, true)

DoesPlayerHavePack

ServerPacks
boolean DoesPlayerHavePack(Player player, string pack)

Checks one pack for one player.

Server only. To show the result in a client UI, return it from a server callback or publish it in a state bag.

Parameters

ParameterTypeDescription
playerPlayerServer id of the player.
packstringPack code.

Returns

boolean Whether they own it.

Example

if DoesPlayerHavePack(source, 'EP04') then
    TriggerClientEvent('rtx_pets:unlock', source)
end

GetPackName

SharedPacks
string GetPackName(string pack)

Returns a pack's name, like 'Get to Work' for EP01.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
packstringPack code.

Returns

string Display name.

Example

AddEventHandler('onResourceStart', function(name)
    if name ~= GetCurrentResourceName() then
        return
    end
    local names = {}
    for _, pack in ipairs(GetRequiredPacks()) do
        names[#names + 1] = GetPackName(pack)
    end
    print('Packs on this server: ' .. table.concat(names, ', '))
end)

GetAllPacks

SharedPacks
table GetAllPacks()

Returns all pack codes Neighborly knows about.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

This native takes no parameters.

Returns

table Every known pack code.

Example

for _, pack in ipairs(GetAllPacks()) do
    print(pack, GetPackName(pack))
end

Events

10 natives · Open Events page

Send and receive events – inside a resource, between resources and across the network. The Events guide explains the ideas behind them.

AddEventHandler

SharedEvents
EventHandle AddEventHandler(string eventName, function handler)

Listens for an event triggered on the same side – by your resource, another resource or Neighborly itself.

Handlers run in the order they were added. A handler only hears events from its own side – to receive events from the network, register them with RegisterNetEvent. Copy source into a local before your first Wait.

Parameters

ParameterTypeDescription
eventNamestringEvent name. Prefix it with your resource name, like 'rtx_cafe:serve'.
handlerfunctionfunction(...) – receives the event's arguments. In server handlers of player events, source is the player.

Returns

EventHandle A handle for RemoveEventHandler.

Example

AddEventHandler('lotEntered', function(zoneId)
    if zoneId == Config.CafeLot then
        exports.neighborly:showTextUI('Welcome to Bluejay Café', { icon = 'coffee' })
    end
end)

AddEventHandler('lotLeft', function(zoneId)
    if zoneId == Config.CafeLot then
        exports.neighborly:hideTextUI()
    end
end)

RemoveEventHandler

SharedEvents
void RemoveEventHandler(EventHandle handle)

Stops a handler from receiving events.

Handlers are removed automatically when your resource stops, so you only need this for handlers that should stop earlier.

Parameters

ParameterTypeDescription
handleEventHandleWhat AddEventHandler or RegisterNetEvent returned.

Returns

Nothing (void).

Example

local handle

handle = AddEventHandler('playerSpawned', function()
    exports.neighborly:notify({ title = 'Welcome!', text = 'Press F10 to open your phone.' })
    RemoveEventHandler(handle)
end)

RegisterNetEvent

SharedEvents
EventHandle? RegisterNetEvent(string eventName, function? handler)

Allows an event to arrive from the other side of the network. Network events that were never registered are dropped.

This is the security gate of your resource: every registered net event is a door that anyone can knock on with any arguments. On the server, validate types, ranges, distance and permissions in every handler. On the client, register only the events the server really sends.

Need an answer back? Use RegisterServerCallback instead of pairing two events by hand.

Parameters

ParameterTypeDescription
eventNamestringEvent name. Prefix it with your resource name, like 'rtx_cafe:serve'.
handlerfunction?Optional handler – the same as calling AddEventHandler right after.

Returns

EventHandle? A handle when a handler was given.

Example

RegisterNetEvent('rtx_cafe:serve', function(customer)
    local src = source
    if type(customer) ~= 'number' or customer == src or not GetPlayerName(customer) then
        return
    end
    if GetPlayerLot(customer) ~= GetPlayerLot(src) then
        return
    end
    TriggerClientEvent('rtx_cafe:served', customer, GetPlayerName(src))
end)

TriggerEvent

SharedEvents
void TriggerEvent(string eventName, any ...)

Fires an event on the same side. Every handler of every resource runs before TriggerEvent returns.

Runs synchronously: when it returns, every handler has run (unless one of them waited). Use it to talk to other resources on the same side, or to let them veto actions with CancelEvent.

Parameters

ParameterTypeDescription
eventNamestringEvent name. Prefix it with your resource name, like 'rtx_cafe:serve'.
...anyAny number of arguments: strings, numbers, booleans, nil, vector3 and tables of those.

Returns

Nothing (void).

Example

local function openCafe()
    TriggerEvent('rtx_cafe:beforeOpen', Config.CafeLot)
    if WasEventCanceled() then
        print('Another resource kept the café closed')
        return false
    end
    GlobalState.cafeOpen = true
    TriggerEvent('rtx_cafe:opened', Config.CafeLot)
    return true
end

TriggerServerEvent

ClientEvents
void TriggerServerEvent(string eventName, any ...)

Sends an event from this player to the server. On the server, source is this player.

Fire-and-forget: it returns immediately and gives you no answer. Send ids rather than whole data sets and stay well below 64 KB per event. If you need a result, use TriggerServerCallback.

Parameters

ParameterTypeDescription
eventNamestringEvent name. Prefix it with your resource name, like 'rtx_cafe:serve'.
...anyAny number of arguments: strings, numbers, booleans, nil, vector3 and tables of those.

Returns

Nothing (void).

Example

RegisterCommand('tip', function(_, args)
    local target = tonumber(args[1])
    local amount = tonumber(args[2])
    if not target or not amount then
        return exports.neighborly:notify({ text = 'Usage: /tip <player id> <amount>', type = 'warning' })
    end
    TriggerServerEvent('rtx_cafe:tip', target, amount)
end, false)

TriggerClientEvent

ServerEvents
void TriggerClientEvent(string eventName, Player target, any ...)

Sends an event from the server to one player or to everyone.

Events only reach players who are connected right now. Anything a player who joins later must also know belongs in a state bag – see Client ↔ server data. Events to one player arrive in the order you send them, also relative to state bag changes.

Parameters

ParameterTypeDescription
eventNamestringEvent name. Prefix it with your resource name, like 'rtx_cafe:serve'.
targetPlayerOne player's server id, or -1 for everyone.
...anyAny number of arguments: strings, numbers, booleans, nil, vector3 and tables of those.

Returns

Nothing (void).

Example

RegisterCommand('announce', function(source, args)
    local text = table.concat(args, ' ')
    if text == '' then
        return
    end
    TriggerClientEvent('neighborly:notify', -1, {
        title = 'Announcement',
        text = text,
        icon = 'megaphone',
        duration = 10000
    })
end, true)

CancelEvent

SharedEvents
void CancelEvent()

Cancels the event that is being handled right now. Call it inside a handler.

Only built-in events marked as cancellable stop something in the game (chatMessage, buildModeEntered, simInteraction). For your own events it simply sets the flag that WasEventCanceled reads.

Parameters

This native takes no parameters.

Returns

Nothing (void).

Example

AddEventHandler('chatMessage', function(author, text)
    if #text > 300 then
        CancelEvent()
        TriggerClientEvent('neighborly:notify', source, { text = 'That message is too long.', type = 'warning' })
    end
end)

WasEventCanceled

SharedEvents
boolean WasEventCanceled()

Checks whether the event you just fired with TriggerEvent was cancelled.

Only meaningful right after TriggerEvent returns, before your code waits.

Parameters

This native takes no parameters.

Returns

boolean true if a handler called CancelEvent.

Example

RegisterNetEvent('rtx_cafe:openShop', function()
    local src = source
    TriggerEvent('rtx_cafe:beforeShop', src)
    if WasEventCanceled() then
        return TriggerClientEvent('neighborly:notify', src, { text = 'The shop is closed right now.' })
    end
    TriggerClientEvent('rtx_cafe:shop', src, Config.Drinks)
end)

TriggerLatentClientEvent

ServerEvents
void TriggerLatentClientEvent(string eventName, Player target, int bytesPerSecond, any ...)

Same as TriggerClientEvent. Neighborly batches and compresses events on its own, so the rate argument is ignored.

Server only. To show the result in a client UI, return it from a server callback or publish it in a state bag.

Parameters

ParameterTypeDescription
eventNamestringEvent name.
targetPlayerPlayer, or -1 for everyone.
bytesPerSecondintAccepted for FiveM compatibility.
...anyArguments.

Returns

Nothing (void).

Example

TriggerLatentClientEvent('rtx_maps:data', source, 50000, Config.BigMap)

TriggerLatentServerEvent

ClientEvents
void TriggerLatentServerEvent(string eventName, int bytesPerSecond, any ...)

Same as TriggerServerEvent; the rate argument is ignored.

Client only: it runs on the local player's PC and affects only their game. Other players don't see the result unless you tell the server.

Parameters

ParameterTypeDescription
eventNamestringEvent name.
bytesPerSecondintAccepted for FiveM compatibility.
...anyArguments.

Returns

Nothing (void).

Example

TriggerLatentServerEvent('rtx_photos:upload', 20000, photoData)

State & callbacks

15 natives · Open State & callbacks page

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.

RegisterServerCallback

ServerState & callbacks
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

ParameterTypeDescription
namestringCallback name, prefixed with your resource name, like 'rtx_bank:getAccount'.
handlerfunctionfunction(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

ClientState & callbacks
...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

ParameterTypeDescription
namestringCallback name, prefixed with your resource name, like 'rtx_bank:getAccount'.
...anyArguments 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

ClientState & callbacks
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

ParameterTypeDescription
namestringCallback name, prefixed with your resource name, like 'rtx_bank:getAccount'.
handlerfunctionfunction(...) – 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

ServerState & callbacks
...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

ParameterTypeDescription
namestringCallback name, prefixed with your resource name, like 'rtx_bank:getAccount'.
playerPlayerThe player to ask.
...anyArguments 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

SharedState & callbacks
{ 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

ParameterTypeDescription
playerPlayerServer 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

SharedState & callbacks
{ 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

ParameterTypeDescription
zoneIdZoneIdZone 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

SharedState & callbacks
{ 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

ParameterTypeDescription
entitySim|ObjectA 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

SharedState & callbacks
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

ParameterTypeDescription
bagNamestringBag name: 'global', 'player:12', 'lot:4821' or 'entity:90031'.
keystringThe 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

SharedState & callbacks
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

ParameterTypeDescription
bagNamestringBag name: 'global', 'player:12', 'lot:4821' or 'entity:90031'.
keystringThe key.
valueanyNew value, or nil to remove the key.
replicatedbooleantrue 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

SharedState & callbacks
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

ParameterTypeDescription
bagNamestringBag 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

SharedState & callbacks
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

ParameterTypeDescription
keystring?Key to watch, or nil for every key.
bagFilterstring?Bag name to watch, or nil for every bag.
handlerfunctionfunction(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

SharedState & callbacks
void RemoveStateBagChangeHandler(int cookie)

Stops a state bag change handler.

Change handlers are removed automatically when your resource stops.

Parameters

ParameterTypeDescription
cookieintWhat 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

SharedState & callbacks
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

ParameterTypeDescription
bagNamestringBag 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

SharedState & callbacks
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

ParameterTypeDescription
bagNamestringBag 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

SharedState & callbacks
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

ParameterTypeDescription
bagNamestringBag 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)

NUI

4 natives · Open NUI page

Talk to your HTML pages in the Neighborly overlay: send messages, give them focus and answer their callbacks. See the NUI guide.

SendNUIMessage

ClientNUI
void SendNUIMessage(table message)

Sends a message to this resource's NUI page. The page receives it as a message event.

The message is turned into JSON, so functions and userdata are dropped and vector3 becomes { x, y, z }. Messages are queued until the page has loaded, so it is safe to send them right after the resource starts.

Parameters

ParameterTypeDescription
messagetableAny table that can be turned into JSON.

Returns

Nothing (void).

Example

RegisterNetEvent('rtx_phone:newMessage', function(from, text)
    SendNUIMessage({ action = 'message', from = from, text = text, time = os.time() })
    PlaySoundFrontend('phone_buzz', 0.6)
end)

SetNuiFocus

ClientNUI
void SetNuiFocus(boolean hasFocus, boolean hasCursor)

Gives this resource's NUI page keyboard and mouse input, or hands it back to the game.

Forgetting to release focus is the most common NUI bug – players are stuck with a cursor. Release it when the page closes, and in onResourceStop.

Parameters

ParameterTypeDescription
hasFocusbooleanGive the page the keyboard.
hasCursorbooleanShow the mouse cursor and let the page receive clicks.

Returns

Nothing (void).

Example

local open = false

RegisterCommand('tablet', function()
    open = not open
    SetNuiFocus(open, open)
    SendNUIMessage({ action = open and 'show' or 'hide' })
end, false)

RegisterNUICallback('close', function(_, cb)
    open = false
    SetNuiFocus(false, false)
    SendNUIMessage({ action = 'hide' })
    cb({ ok = true })
end)

IsNuiFocused

ClientNUI
boolean IsNuiFocused()

Checks whether a NUI page currently has keyboard focus – useful to ignore key mappings while the player is typing in a UI.

True for any resource's page, not just yours – so your key bindings stay quiet while the player types in someone else's UI too.

Parameters

This native takes no parameters.

Returns

boolean true while any NUI page has focus.

Example

RegisterCommand('+radio', function()
    if IsNuiFocused() or IsChatOpen() then
        return
    end
    TriggerServerEvent('rtx_radio:talking', true)
end, false)

RegisterCommand('-radio', function()
    TriggerServerEvent('rtx_radio:talking', false)
end, false)

RegisterNUICallback

ClientNUI
void RegisterNUICallback(string name, function handler)

Handles a request from this resource's NUI page.

Runs as a thread, so you may wait – for example for TriggerServerCallback – before calling cb. The page's fetch stays pending until you do. NUI callbacks run on the player's PC: anything that costs money or changes the world must be decided by the server.

Parameters

ParameterTypeDescription
namestringCallback name – the page POSTs to https://<resource>/<name>.
handlerfunctionfunction(data, cb) – data is the decoded JSON body; call cb(response) exactly once.

Returns

Nothing (void).

Example

RegisterNUICallback('deposit', function(data, cb)
    local amount = tonumber(data.amount)
    if not amount then
        return cb({ ok = false, error = 'Enter an amount' })
    end
    local ok, result = TriggerServerCallback('rtx_bank:deposit', amount)
    cb({ ok = ok == true, savings = ok and result or nil, error = not ok and result or nil })
end)

Storage

15 natives · Open Storage page

Resource KVP – a small key/value store saved on disk, separately for every resource. For real server data use the database from the State & storage guide.

SetResourceKvp

SharedStorage
void SetResourceKvp(string key, any value)

Saves a value in this resource's KVP store – on the player's PC in client scripts (per server), in the server's data folder in server scripts.

Writes are saved to disk right away. KVP is perfect for small settings; for data that must survive a reinstall or be shared between servers, use the server database.

Parameters

ParameterTypeDescription
keystringThe key.
valueanyA string, number, boolean or table. Tables are stored as JSON.

Returns

Nothing (void).

Example

RegisterNUICallback('setTheme', function(data, cb)
    local theme = data.theme == 'dark' and 'dark' or 'light'
    SetResourceKvp('theme', theme)
    cb({ ok = true, theme = theme })
end)

GetResourceKvp

SharedStorage
any GetResourceKvp(string key)

Reads a value from this resource's KVP store.

Returns values with their original type – numbers stay numbers and tables come back as tables.

Parameters

ParameterTypeDescription
keystringThe key.

Returns

any The saved value, or nil.

Example

AddEventHandler('onClientResourceStart', function(name)
    if name == GetCurrentResourceName() then
        SendNUIMessage({ action = 'theme', theme = GetResourceKvp('theme') or 'light' })
    end
end)

DeleteResourceKvp

SharedStorage
void DeleteResourceKvp(string key)

Removes a key from this resource's KVP store.

Deleting a key that doesn't exist is fine and does nothing.

Parameters

ParameterTypeDescription
keystringThe key.

Returns

Nothing (void).

Example

RegisterCommand('resetphone', function()
    for _, key in ipairs(GetResourceKvpKeys('phone:')) do
        DeleteResourceKvp(key)
    end
    exports.neighborly:notify({ text = 'Phone settings reset.' })
end, false)

GetResourceKvpKeys

SharedStorage
table GetResourceKvpKeys(string prefix)

Lists the keys in this resource's KVP store.

Use prefixes like 'lot:' or 'player:' in your keys so you can list one kind of entry at a time.

Parameters

ParameterTypeDescription
prefixstringOnly keys starting with this text. '' for all.

Returns

table List of keys.

Example

AddEventHandler('onResourceStart', function(name)
    if name ~= GetCurrentResourceName() then
        return
    end
    for _, key in ipairs(GetResourceKvpKeys('sign:')) do
        local zoneId = key:sub(6)
        Lot(zoneId).state:set('sign', GetResourceKvp(key), true)
    end
end)

SetResourceKvpInt

SharedStorage
void SetResourceKvpInt(string key, int value)

Saves a whole number.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
keystringThe key.
valueintWhole number.

Returns

Nothing (void).

Example

SetResourceKvpInt('visits', GetResourceKvpInt('visits') + 1)

GetResourceKvpInt

SharedStorage
int GetResourceKvpInt(string key)

Reads a whole number saved with SetResourceKvpInt.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
keystringThe key.

Returns

int The number, or 0.

Example

print('This server started me', GetResourceKvpInt('boots'), 'times')

SetResourceKvpFloat

SharedStorage
void SetResourceKvpFloat(string key, number value)

Saves a number with decimals.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
keystringThe key.
valuenumberNumber.

Returns

Nothing (void).

Example

SetResourceKvpFloat('volume', 0.65)

GetResourceKvpFloat

SharedStorage
number GetResourceKvpFloat(string key)

Reads a number saved with SetResourceKvpFloat.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
keystringThe key.

Returns

number The number, or 0.0.

Example

local volume = GetResourceKvpFloat('volume')

GetResourceKvpString

SharedStorage
string? GetResourceKvpString(string key)

Reads a value as a string. Tables come back as JSON text.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
keystringThe key.

Returns

string? The value as text.

Example

local theme = GetResourceKvpString('theme') or 'light'

SetResourceKvpNoSync

SharedStorage
void SetResourceKvpNoSync(string key, any value)

Same as SetResourceKvp. Writes are always batched, so it exists for FiveM compatibility.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
keystringThe key.
valueanyValue.

Returns

Nothing (void).

Example

SetResourceKvpNoSync('lastSeen', os.time())

FlushResourceKvp

SharedStorage
void FlushResourceKvp()

Writes pending KVP changes to disk now. Neighborly flushes on its own within half a second and when the resource stops.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

This native takes no parameters.

Returns

Nothing (void).

Example

AddEventHandler('onResourceStop', function(name)
    if name == GetCurrentResourceName() then
        FlushResourceKvp()
    end
end)

StartFindKvp

SharedStorage
int StartFindKvp(string prefix)

Starts going through every key that begins with a prefix. Use FindKvp to step and EndFindKvp when done.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
prefixstringKey prefix.

Returns

int A search handle.

Example

local handle = StartFindKvp('score:')
local key = FindKvp(handle)
while key do
    print(key, GetResourceKvpInt(key))
    key = FindKvp(handle)
end
EndFindKvp(handle)

FindKvp

SharedStorage
string? FindKvp(int handle)

Returns the next key of a search.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
handleintHandle from StartFindKvp.

Returns

string? The next key, or nil at the end.

Example

local handle = StartFindKvp('note:')
local count = 0
while FindKvp(handle) do
    count = count + 1
end
EndFindKvp(handle)

EndFindKvp

SharedStorage
void EndFindKvp(int handle)

Ends a search and frees its handle.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
handleintHandle from StartFindKvp.

Returns

Nothing (void).

Example

EndFindKvp(handle)

Resource

12 natives · Open Resource page

Information about resources and their files.

GetCurrentResourceName

SharedResource
string GetCurrentResourceName()

Returns the resource the code runs in.

Use it instead of hard-coding your resource name, so the resource keeps working when a server owner renames the folder.

Parameters

This native takes no parameters.

Returns

string Name of this resource.

Example

AddEventHandler('onResourceStart', function(name)
    if name == GetCurrentResourceName() then
        print('Started!')
    end
end)

GetResourceState

SharedResource
string GetResourceState(string resource)

Returns a resource's state.

Check it before calling exports of optional integrations, so your resource keeps working when the other one isn't installed.

Parameters

ParameterTypeDescription
resourcestringResource name.

Returns

string 'started', 'starting', 'stopped', 'stopping', 'uninitialized' or 'missing'.

Example

if GetResourceState('rtx_bank') == 'started' then
    exports.rtx_bank:addSavings(source, 10, 'Bonus')
end

GetNumResources

SharedResource
int GetNumResources()

Returns how many resources exist.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

This native takes no parameters.

Returns

int Number of known resources.

Example

RegisterCommand('started', function()
    local started = 0
    for i = 0, GetNumResources() - 1 do
        if GetResourceState(GetResourceByFindIndex(i)) == 'started' then
            started = started + 1
        end
    end
    print(('%d of %d resources are running'):format(started, GetNumResources()))
end, true)

GetResourceByFindIndex

SharedResource
string GetResourceByFindIndex(int index)

Iterates over all resources.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
indexint0 to GetNumResources() - 1.

Returns

string Resource name.

Example

for i = 0, GetNumResources() - 1 do
    local name = GetResourceByFindIndex(i)
    print(name, GetResourceState(name))
end

GetResourceMetadata

SharedResource
string? GetResourceMetadata(string resource, string key, int index)

Reads a value from a resource's resource.toml.

Custom keys in resource.toml are allowed and ignored by Neighborly, so you can store things like a support link and read them here.

Parameters

ParameterTypeDescription
resourcestringResource name.
keystringManifest key.
indexintIndex for list keys, 0 for single values.

Returns

string? The value.

Example

AddEventHandler('onResourceStart', function(name)
    if name ~= GetCurrentResourceName() then
        return
    end
    local version = GetResourceMetadata(name, 'version', 0)
    local author = GetResourceMetadata(name, 'author', 0) or 'unknown'
    print(('%s %s by %s started'):format(name, version, author))
end)

LoadResourceFile

SharedResource
string? LoadResourceFile(string resource, string path)

Reads a file from a resource. On the client the file must be listed in files.

On a client, only files listed in files in the manifest are available. Server-only data belongs in files that aren't listed, so players never download them.

Parameters

ParameterTypeDescription
resourcestringResource name.
pathstringFile path inside the resource.

Returns

string? File contents.

Example

local recipes = {}

AddEventHandler('onResourceStart', function(name)
    if name ~= GetCurrentResourceName() then
        return
    end
    local raw = LoadResourceFile(name, 'data/recipes.json')
    recipes = raw and json.decode(raw) or {}
    print(('Loaded %d recipes'):format(#recipes))
end)

SaveResourceFile

ServerResource
boolean SaveResourceFile(string resource, string path, string data)

Writes a file into a resource folder.

Writes inside the resource folder. Don't use it for player data – the database is backed up, resource folders usually aren't, and updates may overwrite them.

Parameters

ParameterTypeDescription
resourcestringResource name.
pathstringFile path.
datastringContents.

Returns

boolean true on success.

Example

RegisterCommand('exportsales', function()
    local db = exports.neighborly:db()
    local report = db:find('sale:', function()
        return true
    end)
    if SaveResourceFile(GetCurrentResourceName(), 'data/sales.json', json.encode(report)) then
        print(('Saved %d sales to data/sales.json'):format(#report))
    end
end, true)

GetResourcePath

ServerResource
string GetResourcePath(string resource)

Returns where a resource lives on disk.

Server only. To show the result in a client UI, return it from a server callback or publish it in a state bag.

Parameters

ParameterTypeDescription
resourcestringResource name.

Returns

string Absolute folder path.

Example

RegisterCommand('wherecafe', function()
    print('rtx_cafe lives in ' .. GetResourcePath('rtx_cafe'))
end, true)

StartResource

Server RestrictedResource
boolean StartResource(string resource)

Starts a resource.

Starting resources can change a server completely, so only trusted resources should do it. The resource must exist in the resources folder – run refresh after adding new ones.

Restricted: the resource needs add_ace resource.<name> neighborly.restricted allow in the server permissions.

Parameters

ParameterTypeDescription
resourcestringResource name.

Returns

boolean true if it started.

Example

AddEventHandler('seasonChanged', function(season)
    if season == 'fall' and GetResourceState('rtx_halloween') == 'stopped' then
        StartResource('rtx_halloween')
    end
end)

StopResource

Server RestrictedResource
boolean StopResource(string resource)

Stops a resource.

Server only: the change happens on the server and Neighborly syncs it to every player who can see it. Validate anything that came from a client before you call it.

Restricted: the resource needs add_ace resource.<name> neighborly.restricted allow in the server permissions.

Parameters

ParameterTypeDescription
resourcestringResource name.

Returns

boolean true if it stopped.

Example

AddEventHandler('seasonChanged', function(season, previous)
    if previous == 'fall' and GetResourceState('rtx_halloween') == 'started' then
        StopResource('rtx_halloween')
    end
end)

GetNumResourceMetadata

SharedResource
int GetNumResourceMetadata(string resource, string key)

Counts the values of a manifest key, for example how many client_scripts a resource has.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
resourcestringResource name.
keystringManifest key.

Returns

int How many values the key has.

Example

for i = 0, GetNumResourceMetadata(GetCurrentResourceName(), 'author') - 1 do
    print('Author:', GetResourceMetadata(GetCurrentResourceName(), 'author', i))
end

Core

17 natives · Open Core page

Timers, convars, commands and other utilities.

GetGameTimer

SharedCore
int GetGameTimer()

A monotonic timer for cooldowns and measuring time.

Counts milliseconds since the server (or the client) started and never goes backwards – the right clock for cooldowns. It is different on every machine, so don't send it between client and server.

Parameters

This native takes no parameters.

Returns

int Milliseconds since start.

Example

local started = GetGameTimer()
Wait(1500)
print('Took', GetGameTimer() - started, 'ms')

IsServer

SharedCore
boolean IsServer()

Tells shared scripts which side they run on.

Handy in shared scripts and helper libraries that behave a little differently on each side.

Parameters

This native takes no parameters.

Returns

boolean true on the server.

Example

if IsServer() then
    print('Loaded on the server')
end

GetConvar

SharedCore
string GetConvar(string name, string default)

Reads a convar. On the server, convars come from convars and replicatedConvars in server.json or the set/setr console commands. Clients only see replicated convars.

Convars are set in convars in server.json. Keep secrets like webhooks in convars and read them only on the server.

Parameters

ParameterTypeDescription
namestringConvar name.
defaultstringValue if not set.

Returns

string The value.

Example

local webhook = GetConvar('rtx_cafe:webhook', '')

RegisterNetEvent('rtx_cafe:bigTip', function(amount)
    if webhook == '' then
        return
    end
    print(('Would post a §%d tip to the staff webhook'):format(amount))
end)

GetConvarInt

SharedCore
int GetConvarInt(string name, int default)

Reads a number convar.

Returns the default when the convar is missing or isn't a whole number.

Parameters

ParameterTypeDescription
namestringConvar name.
defaultintValue if not set.

Returns

int The value.

Example

local maxStaff = GetConvarInt('rtx_cafe:maxStaff', 4)

RegisterNetEvent('rtx_cafe:clockIn', function()
    local src = source
    local working = 0
    for _, player in ipairs(GetPlayers()) do
        if Player(player).state.onDuty then
            working = working + 1
        end
    end
    if working >= maxStaff then
        return TriggerClientEvent('neighborly:notify', src, { text = 'The café has enough staff right now.' })
    end
    Player(src).state:set('onDuty', true, true)
end)

SetConvar

ServerCore
void SetConvar(string name, string value)

Changes a convar until the server restarts.

The change lasts until the server restarts. Permanent values belong in convars in server.json.

Parameters

ParameterTypeDescription
namestringConvar name.
valuestringNew value.

Returns

Nothing (void).

Example

RegisterCommand('happyhour', function(source, args)
    local on = args[1] == 'on'
    SetConvar('rtx_cafe:happyHour', on and 'true' or 'false')
    GlobalState.happyHour = on
end, true)

ExecuteCommand

SharedCore
void ExecuteCommand(string command)

Runs a console command. The resource needs the matching ace, for example add_ace resource.rtx_admin command.say allow.

The resource needs the matching ace, for example add_ace resource.rtx_admin command.say allow. Commands run as the console.

Parameters

ParameterTypeDescription
commandstringConsole command line.

Returns

Nothing (void).

Example

AddEventHandler('dayChanged', function(day)
    if day % 7 == 0 then
        ExecuteCommand('say A new week begins in the neighborhood!')
    end
end)

CreateThread

SharedCore
void CreateThread(function fn)

Runs a function as a thread, so it can Wait without blocking anything else. Citizen.CreateThread is the same function.

The function starts right away and runs until its first Wait. Errors inside a thread are printed with file and line, and only stop that thread.

Parameters

ParameterTypeDescription
fnfunctionThe function to run as a thread.

Returns

Nothing (void).

Example

CreateThread(function()
    while true do
        GlobalState.playerCount = GetNumPlayers()
        Wait(5000)
    end
end)

Wait

SharedCore
void Wait(int ms)

Pauses the current thread and lets everything else run. Only works inside a thread.

Calling it outside a thread raises an error. On clients, Wait(0) loops run every frame – keep them short and only run them while needed.

Parameters

ParameterTypeDescription
msintMilliseconds. 0 waits exactly one frame on a client or one tick on the server.

Returns

Nothing (void).

Example

RegisterNetEvent('rtx_stage:countdown', function()
    for i = 3, 1, -1 do
        ShowToast(tostring(i), 900)
        PlaySoundFrontend('ui_tick', 0.6)
        Wait(1000)
    end
    ShowToast('Showtime!', 1500)
end)

SetTimeout

SharedCore
int SetTimeout(int ms, function fn)

Runs a function once after a delay, without blocking the code that set it.

The function runs as a new thread, so it can wait as well. Copy source into a local before setting the timer – it isn't valid any more when the timer fires.

Parameters

ParameterTypeDescription
msintDelay in milliseconds.
fnfunctionRuns once after the delay, as a new thread.

Returns

int A timer id for ClearTimeout.

Example

RegisterNetEvent('rtx_cafe:order', function()
    local src = source
    TriggerClientEvent('neighborly:notify', src, { text = 'Your order will be ready in a minute.' })
    SetTimeout(60000, function()
        if GetPlayerName(src) then
            TriggerClientEvent('neighborly:notify', src, { text = 'Your order is ready!', type = 'success' })
        end
    end)
end)

ClearTimeout

SharedCore
void ClearTimeout(int timerId)

Cancels a timer before it runs.

Clearing a timer that already ran or was cleared does nothing.

Parameters

ParameterTypeDescription
timerIdintWhat SetTimeout returned.

Returns

Nothing (void).

Example

local reminders = {}

RegisterNetEvent('rtx_cafe:clockIn', function()
    local src = source
    reminders[src] = SetTimeout(3600000, function()
        reminders[src] = nil
        TriggerClientEvent('neighborly:notify', src, { text = 'You have worked an hour. Time for a break!' })
    end)
end)

RegisterNetEvent('rtx_cafe:clockOut', function()
    local src = source
    if reminders[src] then
        ClearTimeout(reminders[src])
        reminders[src] = nil
    end
end)

RegisterCommand

SharedCore
void RegisterCommand(string name, function handler, boolean restricted)

Creates a chat and console command. See Commands & key mappings.

Server commands work in chat and the server console; client commands only on that player's PC, where restricted is ignored. Pair client commands with RegisterKeyMapping for key bindings.

Parameters

ParameterTypeDescription
namestringThe command without the slash. Lowercase, no spaces.
handlerfunctionfunction(source, args, raw) – source is the player (0 for the console), args the words after the command, raw the full line.
restrictedbooleanOnly players with the ace command.<name> may use it. Ignored for client commands.

Returns

Nothing (void).

Example

RegisterCommand('heal', function(source, args)
    local target = tonumber(args[1]) or source
    local sim = target ~= 0 and GetPlayerCharacter(target)
    if not sim then
        return print('Usage: heal <player id>')
    end
    for _, need in ipairs({ 'hunger', 'energy', 'bladder', 'hygiene', 'social', 'fun' }) do
        SetSimNeed(sim, need, 100)
    end
    TriggerClientEvent('neighborly:notify', target, { text = 'You feel brand new!', type = 'success' })
end, true)

RegisterKeyMapping

ClientCore
void RegisterKeyMapping(string command, string description, string device, string defaultKey)

Binds a client command to a key that players can change in their settings.

The player's chosen key is remembered per server. Pick a default that the game and Neighborly don't use (F10, F11, Home).

Parameters

ParameterTypeDescription
commandstringA client command. Start it with + to also get a - command on release.
descriptionstringShown in Settings → Key bindings → Resources.
devicestring'keyboard' or 'mouse'.
defaultKeystringDefault key, for example 'F10'. Players can rebind it.

Returns

Nothing (void).

Example

RegisterCommand('+scoreboard', function()
    TriggerEvent('nb_scoreboard:show', true)
end, false)

RegisterCommand('-scoreboard', function()
    TriggerEvent('nb_scoreboard:show', false)
end, false)

RegisterKeyMapping('+scoreboard', 'Show the player list (hold)', 'keyboard', 'HOME')

SetConvarReplicated

ServerCore
void SetConvarReplicated(string name, string value)

Sets a convar that clients can read with GetConvar too. Same as setr in the console.

Server only: the change happens on the server and Neighborly syncs it to every player who can see it. Validate anything that came from a client before you call it.

Parameters

ParameterTypeDescription
namestringConvar name.
valuestringNew value.

Returns

Nothing (void).

Example

SetConvarReplicated('rtx_cafe:open', 'true')

IsPrincipalAceAllowed

ServerCore
boolean IsPrincipalAceAllowed(string principal, string ace)

Checks a permission of a group or resource instead of a player.

Server only. To show the result in a client UI, return it from a server callback or publish it in a state bag.

Parameters

ParameterTypeDescription
principalstringFor example 'group.admin' or 'resource.rtx_cafe'.
acestringPermission name.

Returns

boolean Whether the principal has it.

Example

if not IsPrincipalAceAllowed('resource.' .. GetCurrentResourceName(), 'command.say') then
    print('Add this to server.json permissions: add_ace resource.' .. GetCurrentResourceName() .. ' command.say allow')
end

IsDuplicityVersion

SharedCore
boolean IsDuplicityVersion()

FiveM's way to ask whether code runs on the server. Handy in shared scripts.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

This native takes no parameters.

Returns

boolean true on the server.

Example

if IsDuplicityVersion() then
    RegisterNetEvent('rtx_cafe:order')
end

GetHashKey

SharedCore
int GetHashKey(string text)

Hashes a string. Also available as joaat.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
textstringAny text.

Returns

int Signed 32-bit Jenkins one-at-a-time hash, like FiveM.

Example

local key = GetHashKey('rtx_cafe:latte')

CreateThreadNow

SharedCore
void CreateThreadNow(function fn)

Starts a thread and runs it right away until its first Wait, instead of on the next tick.

Available in client and server scripts. On a client it reads the synced copy of the world, which can trail the server by a moment – make gameplay decisions on the server.

Parameters

ParameterTypeDescription
fnfunctionThread body.

Returns

Nothing (void).

Example

CreateThreadNow(function()
    print('runs before the next line')
    Wait(100)
    print('runs later')
end)
print('next line')