NX Creative

Exports

Public exports for integrating other resources with nx_computer.

On this page

These are the exports a server owner or third-party resource is expected to call against nx_computer. Every export uses the colon call form exports['nx_computer']:Fn(...) so that self is passed; a dot call shifts the arguments and breaks the table-def exports.

The four SDK registration exports (RegisterApp, UnregisterApp, RegisterSite, UnregisterSite) are summarized here and covered in depth in the SDK section.

Shared (client and server)#

RegisterApp, UnregisterApp, RegisterSite, and UnregisterSite are registered on both the client and the server. The call site changes the scope: a server call broadcasts the registration to every connected player and replays it to players who join later, while a client call registers only on that one client.

exports.nx_computer:RegisterAppshared

Publish a custom web app onto the laptop desktop, Start menu, taskbar, and Spotlight. Called on the server it broadcasts to all players and replays to late joiners. Called on a client it adds the app on that client only. Re-call with the same id to update the app live. Gated by Config.Apps.External.

Parameters

def table
App definition. See fields below.

Returns

boolean

The def table fields:

  • id (string, required): the raw identifier for the app. Re-registering the same id updates the existing app in place.
  • url (string, required): the app URL to load.
  • title (string, optional): the display name shown on the desktop and taskbar.
  • icon (string, optional): the icon reference.
  • accent (string, optional): the accent color.
  • width (number, optional): the window width.
  • height (number, optional): the window height.
Lua
CreateThread(function()    Wait(1500)    exports['nx_computer']:RegisterApp({        id = 'pizzaplanet',        url = 'https://apps.example.com/pizzaplanet',        title = 'Pizza Planet',        accent = '#e23b3b',        width = 1024,        height = 720,    })end)

See Custom apps for the full field reference.

exports.nx_computer:UnregisterAppshared

Remove a previously registered custom app by its id. Server and client scope match RegisterApp.

Parameters

id string
The raw id passed to RegisterApp.
Lua
exports['nx_computer']:UnregisterApp('pizzaplanet')
exports.nx_computer:RegisterSiteshared

Publish a built-in .lc directory site inside the laptop browser, for example pizzaplanet.lc. Called on the server it broadcasts to all players and replays to late joiners. Called on a client it registers on that client only. Re-call with the same slug to update live. Gated by Config.SiteBuilder.Directory.

Parameters

def table
Directory site definition. See fields below.

Returns

boolean

The def table fields:

  • slug (string, required): the site slug, resolved as slug.lc in the browser.
  • url (string, required): the site URL to load.
  • title (string, optional): the display title.
  • icon (string, optional): the icon reference.
  • accent (string, optional): the accent color.
  • description (string, optional): the short description shown in listings.
Lua
CreateThread(function()    Wait(1500)    exports['nx_computer']:RegisterSite({        slug = 'pizzaplanet',        url = 'https://apps.example.com/pizzaplanet-site',        title = 'Pizza Planet',        description = 'Order delivery across the city.',    })end)

See Directory sites for the full field reference.

exports.nx_computer:UnregisterSiteshared

Remove a registered directory site by slug and release the slug for player use. Server and client scope match RegisterSite.

Parameters

slug string
The slug passed to RegisterSite.
Lua
exports['nx_computer']:UnregisterSite('pizzaplanet')

Server#

An export that fails returns false and a reason string (or a { success = false, error } table, as each export says).

Messaging and notifications#

exports.nx_computer:sendSystemEmailserver

Deliver a system or automated email into a player's laptop inbox from another resource. Returns the new email id, or false when the recipient cannot be resolved. The recipient's email forwarding rules apply to system mail too.

Parameters

payload table
Email fields. See below.

Returns

number | false

The payload table fields:

  • to (string or number, required): the recipient, given as an @handle or an account id. recipientAccountId is accepted in its place.
  • subject (string, required): the email subject line.
  • body (string, required): the email body.
  • sourceApp (string, optional): the app the email is attributed to.
  • senderName (string, optional): the display name of the sender. Defaults to a capitalized sourceApp, or System.
  • location (table, optional): { x, y, name, sub? }. A map card on its own last line with Set waypoint, on the laptop and on nx_phone. A bad location returns false.
Lua
exports['nx_computer']:sendSystemEmail({    to = '@jdoe',    subject = 'Your order shipped',    body = 'Your package is on the way.',    sourceApp = 'store',    senderName = 'Pizza Planet',})
exports.nx_computer:PushNotificationserver

Push a notification into a player's laptop notification centre. It appears immediately if that account is signed in, and waits in the centre otherwise. Returns the new notification id, or nil when the target cannot be resolved or the title or message is empty.

Parameters

input table
Notification fields. See below.

Returns

number | nil

The target is resolved from the first of these that matches an account:

  • accountId (string): a laptop account id.
  • handle or username (string): an @handle, with or without the leading @.
  • source (number): a player server id. Resolves to the account currently signed in on that player's laptop.

The remaining fields:

  • title (string, required): capped at 120 characters.
  • message (string, required): capped at 512 characters.
  • appId (string, optional): the app the notification belongs to. Defaults to system.
  • category (string, optional): a grouping key. Defaults to system.
  • severity (string, optional): one of info, success, warning, error. Defaults to info.
  • deepLinkApp (string, optional): the app id to open when the notification is clicked.
  • deepLinkPayload (table, optional): data handed to that app on open.
  • sourceEvent (string, optional): a free-form origin tag.
  • computerId (string, optional): scope the notification to one device.
  • expiresAt (string, optional): an explicit expiry timestamp. Omit it to use the retention window from Config.Notifications.RetentionDays.
Lua
exports['nx_computer']:PushNotification({    handle = '@jdoe',    appId = 'store',    title = 'Order ready',    message = 'Your pizza is waiting at the counter.',    severity = 'success',})
exports.nx_computer:PhoneNotifyserver

Raise a notification on the player's phone through the phone bridge. Returns false when the bridge is off, the kind is not enabled in Config.PhoneBridge.Events, the player is not online, or there is no text to show. It never throws.

Parameters

target string | number | table
An account id, a player server id, or a table with accountId, source, or identifier.
kind string
A key in Config.PhoneBridge.Events: Email, Message, or a key you added.
payload table
The notification text. See below.

Returns

boolean

Pass title and body to set the text directly. Without them, the Email kind builds its text from subject and the sender, and the Message kind from preview and the sender. The sender is the first of from, senderHandle, senderDisplayName, or senderName that is set.

The notification is skipped when the payload marks it as the player's own action: outgoing = true, a folder other than inbox, or a senderAccountId or senderSource that matches the target.

Notifications of the same kind that arrive within Config.PhoneBridge.CoalesceMs merge into one, and Config.PhoneBridge.MaxPerMin caps how many a player receives per minute. The phone app each kind appears under is set in Config.PhoneBridge.Apps.

Lua
-- config.lua: Config.PhoneBridge.Events = { Email = true, Message = true, Dispatch = true }exports['nx_computer']:PhoneNotify(source, 'Dispatch', {    title = 'Dispatch',    body = '10-50 reported at Legion Square.',})

NPC mailboxes#

An NPC mailbox is an address on your mail domain that your resource answers, for example a fixer a quest player can write to. Mail from it shows its name and address, and Reply works. A player's mail to it, from the laptop or a linked nx_phone, lands in their Sent folder and reaches your onMail. Mailboxes live in memory and belong to your resource: register them again when it starts.

exports.nx_computer:RegisterMailboxserver

Claim an address for your resource. Returns the full address. Registering it again from your resource updates it.

Parameters

address string
A name ('fixer', letters, digits and _), or name@your mail domain.
opts table
{ name, onMail? }

Returns

address | false, err
  • name: the sender name players see, up to 60 characters.
  • onMail(src, mail): a player wrote to it. src is their server id when they are online. mail is { mailbox, from, fromName, accountId, subject, body, emailId, source }; from is their address and emailId their Sent copy.

A mailbox takes mail sent to it. A copy in cc is not delivered.

Errors: invalid_address, invalid_name, invalid_handler, address_taken (a player account or another resource has that name).

Lua
exports.nx_computer:RegisterMailbox('fixer', {    name = 'The Fixer',    onMail = function(src, mail)        if mail.body:lower():find('in') then StartQuest(src) end   -- your own function    end,})
exports.nx_computer:SendMailboxEmailserver

Mail a player from an NPC mailbox. Errors: invalid_mailbox, invalid_recipient, invalid_location, empty_message, insert_failed.

Parameters

address string
A mailbox your resource registered.
to string
An account id, @handle, username or address.
subject string
The subject line.
body string
The body.
opts table?
{ location? = { x, y, name, sub? } }

Returns

{ success, id } | { success = false, error }
Lua
exports.nx_computer:SendMailboxEmail('fixer', '@jdoe', 'A job',    'Interested? Reply to this mail.', { location = { x = 215.4, y = -810.2, name = 'Legion Square' } })

nx_phone's SendMail with this address as from does the same.

exports.nx_computer:IsMailboxserver

Whether the address is a registered NPC mailbox.

Parameters

address string
An address, @name or name.

Returns

boolean
exports.nx_computer:RemoveMailboxserver

Release a mailbox. Mail players already have keeps its address; a reply to it then bounces. Errors: not_found, not_owner.

Parameters

address string
A mailbox your resource registered.

Returns

true | false, err

NPC darknet vendors#

Put goods on the darknet under an NPC alias, with no player seller. They show in the darknet Catalog with the vendor's name, and are bought like any catalog item: the same money (cash, or the darknet coin), the same courier pickup, the same order history. Listings live in memory and belong to your resource: create them again when it starts. An order already paid for is collected at the courier even after its listing is gone.

exports.nx_computer:CreateDarknetListingserver

Create (or replace) an NPC listing. Returns 'npc:<your resource>:<id>'.

Parameters

def table
The listing. See below.

Returns

listingId | false, err
  • id (required): unique in your resource, letters, digits, _ and -, up to 40.
  • vendor (required): the alias buyers see, up to 32 characters.
  • label (required): the product name, up to 60.
  • item (required): an ox_inventory item. amount per order (default 1).
  • price (required): per order, in dollars (shown in the coin when the darknet sells in crypto).
  • stock (optional): how many orders remain. Unlimited when nil. At 0 the listing leaves the catalog.
  • delivery (optional): seconds until the courier has it. Default 0.
  • instant (optional): true puts it straight in the buyer's inventory, no courier.
  • metadata (optional): ox_inventory metadata handed over with the item.
  • description, category, code (optional): catalog text.
  • visibleTo (optional): a list of player server ids or character identifiers. Only they see and can buy it. Nil means everyone with darknet access.
  • onPurchase(src, order) and onCollect(src, order) (optional): order is { listingId, vendor, item, amount, price, accountId, identifier, source }.

Errors: invalid_id, invalid_vendor, invalid_label, unknown_item, invalid_price, invalid_amount, invalid_stock, invalid_delivery, invalid_metadata, invalid_handler, invalid_visibility.

Lua
exports.nx_computer:CreateDarknetListing({    id = 'humane_card', vendor = 'Vlad', label = 'Humane Labs keycard',    item = 'keycard_humane', price = 2500, stock = 1, delivery = 120,    metadata = { quest = 'humane' }, visibleTo = { playerId },    onCollect = function(src, order) AdvanceQuest(src, 'has_card') end,   -- your own function})
exports.nx_computer:UpdateDarknetListingserver

Change a listing, for example its price or stock. Errors: not_found, not_owner, or a field error.

Parameters

listingId string
What CreateDarknetListing returned.
patch table
Any CreateDarknetListing field except id.

Returns

true | false, err
exports.nx_computer:RemoveDarknetListingserver

Take a listing off the darknet. Errors: not_found, not_owner.

Parameters

listingId string
What CreateDarknetListing returned.

Returns

true | false, err
exports.nx_computer:GetDarknetListingserver

The listing as buyers see it: { id, vendor, label, item, amount, price, stock, delivery, instant }.

Parameters

listingId string
A listing id.

Returns

table | nil

Accounts and identity#

A character can own up to Config.MaxAccountsPerCharacter laptop accounts. One of them is the character's primary account.

exports.nx_computer:GetActorIdentifierserver

Resolve the identifier of the character a player is currently playing. This is the key laptop accounts are bound to. Returns nil when the player or their character cannot be resolved.

Parameters

source number
A player server id.

Returns

string | nil
Lua
local actor = exports['nx_computer']:GetActorIdentifier(source)
exports.nx_computer:GetAccountByActorserver

Look up the laptop account bound to a character. When the character has several accounts, this returns the primary one. Returns the stored account record, or nil when no live account matches.

Parameters

actorIdentifier string
The identifier returned by GetActorIdentifier.

Returns

table | nil

The returned record carries credential material. Never forward it to a client. Pass it through ResolveAccountSummary when you need something displayable.

Lua
local actor = exports['nx_computer']:GetActorIdentifier(source)local account = actor and exports['nx_computer']:GetAccountByActor(actor)if account then    print(account.username)end
exports.nx_computer:GetAccountByIdserver

Look up an account by its account id. Same record and same caution as GetAccountByActor. Returns nil for an unknown or deleted account.

Parameters

accountId string
A laptop account id.

Returns

table | nil
exports.nx_computer:GetAccountByUsernameserver

Look up an account by its username. Same record and same caution as GetAccountByActor. Returns nil for an unknown or deleted account.

Parameters

username string
A username, with or without the leading @.

Returns

table | nil
exports.nx_computer:GetAccountsByActorserver

Every live account a character owns, primary first, then oldest first. Returns an empty table when there are none. Each entry is the same record GetAccountByActor returns, with the same caution.

Parameters

actorIdentifier string
The identifier returned by GetActorIdentifier.

Returns

table
Lua
local actor = exports['nx_computer']:GetActorIdentifier(source)for _, account in ipairs(exports['nx_computer']:GetAccountsByActor(actor)) do    print(account.username)end
exports.nx_computer:ResolveActorAccountserver

The account a player is using right now. That is the account signed in on their laptop when a session is open, and the character's primary account otherwise. A session left over from a different character on the same player is ignored. Same record and same caution as GetAccountByActor.

Parameters

source number
A player server id.

Returns

table | nil

Use this, not GetAccountByActor, when something your resource delivers should land on the account the player is working in.

Lua
local account = exports['nx_computer']:ResolveActorAccount(source)
exports.nx_computer:ResolveActorAccountByIdentifierserver

The same resolution as ResolveActorAccount, for code that holds a character identifier instead of a server id. If that character has a laptop session open, its signed-in account is returned. Otherwise the primary account.

Parameters

actorIdentifier string
A character identifier.

Returns

table | nil
exports.nx_computer:ResolveAccountSummaryserver

Return the display-safe summary of an account. This is the shape to send to a client. Returns nil for an unknown account.

Parameters

accountId string
A laptop account id.

Returns

table | nil

The returned table:

  • accountId (string): the account id.
  • username (string): the raw username.
  • displayName (string): the account's display name.
  • handle (string): the username with a leading @.
Lua
local summary = exports['nx_computer']:ResolveAccountSummary(accountId)
exports.nx_computer:IsAdminserver

Whether a player holds the nx_computer.admin ACE. The broad command ACE is not accepted unless Config.AllowCommandAceAdmin is enabled. Use it to gate your own admin surfaces on the same principal nx_computer uses.

Parameters

source number
A player server id.

Returns

boolean
Lua
if not exports['nx_computer']:IsAdmin(source) then return end
exports.nx_computer:CanUsePlacerserver

Whether a player may use the /nxc_place and /nxc_cable placement tools. True for everyone while Config.Debug is on. Otherwise true for holders of the nx_computer.admin ACE and for framework admins, unless Config.PlacerAdminAccess is false. Never throws.

Parameters

source number
A player server id.

Returns

boolean
exports.nx_computer:AdminListComputersserver

List laptop devices, most recently updated first. This is the list the Admin app shows. The search matches the start of a computer id or of the owner's or last user's username. limit is clamped to 1 through 100. The export does no permission check of its own, so gate the caller.

Parameters

filter? string | table
A search string, or a table of search and limit.

Returns

table

The result is { success, computers }, with success = false and an empty list when the query fails. Each computer is a table of:

  • computerId (string): the device id.
  • deviceName (string): the device name, or a fallback built from the id.
  • deviceState (string): the device state. Defaults to active.
  • owner (table or nil): the owning account's handle and displayName.
  • lastUser (table or nil): the last signed-in account's handle and displayName.
  • createdAt, updatedAt: the row timestamps.
Lua
local result = exports['nx_computer']:AdminListComputers({ search = '@jdoe', limit = 20 })for _, computer in ipairs(result.computers) do    print(computer.computerId, computer.deviceName)end

Mail addresses#

Every account's address is <username>@<domain>. The domain comes from Config.Mail.Domain. See Configuration.

exports.nx_computer:GetMailDomainserver

The mail domain this server uses right now, for example 'yourcity.com'.

Returns

string
Lua
local domain = exports['nx_computer']:GetMailDomain()
exports.nx_computer:MailAddressForserver

Build the full mail address for a username, for example 'jdoe@yourcity.com'. Returns nil for input that is not a valid username.

Parameters

handleOrUsername string
An @handle or a bare username.

Returns

string | nil
Lua
local address = exports['nx_computer']:MailAddressFor('@jdoe')
exports.nx_computer:ResolveMailAddressserver

Find the account a mail address belongs to. Accepts the current domain and any older domain the server has used. A live account wins over an old name of a renamed account. Returns nil for a foreign domain or an unknown name.

Parameters

input string
A full address, an @handle, a username, or 'Name <address>'.

Returns

table | nil

The result is { account_id, username, display_name, address, viaAlias }. viaAlias is true when the match came from an account's old username.

Lua
local match = exports['nx_computer']:ResolveMailAddress('jdoe@yourcity.com')if match then    print(match.account_id, match.address)end

Acting for a signed-in player#

These exports let another device, such as a phone, perform a player action against a laptop account. They run the same checks, caps, and rate limits as the laptop app. The caller is responsible for having authenticated the player into that account first: the export acts as whatever account id it is given.

exports.nx_computer:SendEmailFromAccountserver

Send an email as a player, exactly as if they had pressed Send in the Email app. A copy lands in the sender's Sent folder. Returns { success, item, counts } on success, or { success = false, error } with an error such as invalid_account.

Parameters

accountId string
The sending account.
to string
The recipient: an @handle, a username, or an account id.
subject string
The subject line, capped at 255 characters.
body string
The message body.
cc? table
A list of carbon-copy recipients, in the same forms as to.

Returns

table
Lua
local result = exports['nx_computer']:SendEmailFromAccount(    accountId, '@jdoe', 'Meeting', 'See you at six.')
exports.nx_computer:CreateClassifiedForAccountserver

Post a classifieds listing as a player. Only resources named in Config.Classifieds.ExportResources may call it. That list defaults to nx_phone, and any other caller gets { success = false, error = 'forbidden' }. Returns { success, listing } on success.

Parameters

accountId string
The posting account.
data table
The listing. See below.

Returns

table

The data table fields:

  • category (string, required): one of for-sale, wanted, services, housing, community.
  • title (string, required): the listing title.
  • body (string, required): the listing text.
  • priceText (string, optional): a free-form price.
  • contactPref (string, optional): how to get in touch.

The active-listing cap and the posting cooldown apply. Hitting the cap returns { success = false, error = 'too_many', cap }.

Lua
local result = exports['nx_computer']:CreateClassifiedForAccount(accountId, {    category = 'for-sale',    title = 'Used Blista',    body = 'Runs well. Some rust.',    priceText = '$4,000',})
exports.nx_computer:DeleteClassifiedForAccountserver

Remove one of a player's own classifieds listings. The same caller allow-list as CreateClassifiedForAccount applies. Returns { success } or { success = false, error }.

Parameters

accountId string
The account that owns the listing.
id number
The listing id.

Returns

table
exports.nx_computer:CreateAccountForCharacterserver

Create a laptop account for the character a player is playing, with the same username, PIN and account-limit rules as signing up on a laptop. Only resources named in Config.AccountExportResources may call it. That list defaults to nx_phone. Returns { success = true, accountId, account }, or { success = false, error }.

Parameters

source number
The player whose character gets the account.
data table
username, displayName (optional) and pin.

Returns

table

The character always comes from source, never from the caller. The errors are forbidden, invalid_source, no_character, invalid_username, invalid_display_name, invalid_pin, account_limit (with maxAccounts), username_taken, rate_limited and signup_failed. A character can create at most three accounts through this export in ten minutes, on top of Config.MaxAccountsPerCharacter.

Lua
local result = exports['nx_computer']:CreateAccountForCharacter(source, {    username = 'jdoe',    displayName = 'John Doe',    pin = '4821',})
exports.nx_computer:IsSourceNearComputerserver

Whether a player physically controls a laptop: they are carrying it, or standing within Config.PickupMaxDistance of where it is placed. Use it to gate anything that should require possession of a specific device.

Parameters

source number
A player server id.
computerId string
The id of a laptop device.

Returns

boolean
Lua
if exports['nx_computer']:IsSourceNearComputer(source, computerId) then    -- the player can reach this laptopend

Money and ledger#

exports.nx_computer:GetPlayerBalancesserver

Read a player's cash and bank balances through the configured framework. Returns whole-dollar integers, and zeros when the player is offline or unknown.

Parameters

source number
A player server id.

Returns

table

The returned table:

  • cash (number): the on-hand balance.
  • bank (number): the bank balance.
Lua
local balances = exports['nx_computer']:GetPlayerBalances(source)print(balances.cash, balances.bank)
exports.nx_computer:RecordTransactionserver

Write an entry into the laptop's Wallet ledger so a money movement your resource performed shows up in the player's transaction history. Returns false when a required field is missing or the entry type is not recognised.

Parameters

payload table
Ledger entry fields. See below.

Returns

boolean

The payload table fields:

  • computerId (string, required): the device the entry belongs to.
  • accountId (string, required): the account the entry belongs to.
  • entryType (string, required): one of trade_buy, trade_sell, transfer_out, transfer_in, casino_session, vehicle_sale_in, vehicle_sale_out, darknet_purchase, darknet_sale, job_payout, listing_fee, trade_fee, bank_deposit, bank_withdraw, bank_transfer_in, bank_transfer_out.
  • assetSymbol (string, required): the traded symbol, uppercased and capped at 20 characters. Fiat entries use a currency symbol.
  • assetAmount (number, required): the quantity moved. Must be greater than zero.
  • unitPrice (number, optional): price per unit. Ignored when it is negative or not finite.
  • fiatTotal (number, optional): the dollar value of the movement.
  • counterpartyAccountId (string, optional): the other side of the movement.
  • counterpartyLabel (string, optional): a display label for the other side, capped at 80 characters.
  • referenceId (string, optional): your own reference, capped at 64 characters.
  • metadata (table, optional): extra fields stored alongside the entry.
Lua
exports['nx_computer']:RecordTransaction({    computerId = computerId,    accountId = accountId,    entryType = 'job_payout',    assetSymbol = 'USD',    assetAmount = 1,    fiatTotal = 850,    counterpartyLabel = 'Pizza Planet',    referenceId = 'shift-4471',})
exports.nx_computer:RecordCasinoHandResultserver

Roll one hand into the player's open casino session so a game your resource runs lands in the same session ledger the built-in tables use. The session commits itself after an idle period, a hand cap, or when the player disconnects. Returns false for an unknown game type or a missing account.

Parameters

source number
A player server id.
accountId string
The account playing the hand.
computerId string
The device the session belongs to.
gameType string
blackjack, hilo, videopoker, or roulette.
stake number
Total wagered on the hand, after any doubling.
payout number
Total credited back, including the returned bet. Zero on a clean loss.

Returns

boolean
Lua
exports['nx_computer']:RecordCasinoHandResult(    source, accountId, computerId, 'blackjack', 250, 500)
exports.nx_computer:WriteAuditserver

Append an entry to the security audit log that the admin console reads. Returns the new entry id, or nil when the action is empty.

Parameters

entry table
Audit entry fields. See below.

Returns

number | nil

The entry table fields:

  • action (string, required): a short action key, capped in length.
  • actorAccountId (string, optional): the account that performed the action.
  • actorKind (string, optional): one of user, admin, system. Defaults to user.
  • actorLabel (string, optional): a display label for the actor.
  • targetAccountId (string, optional): the account acted on.
  • computerId (string, optional): the device involved.
  • severity (string, optional): one of info, notice, warning, critical. Defaults to info.
  • ip (string, optional): a caller-supplied address, capped at 64 characters.
  • detail (table, optional): extra context stored with the entry.
Lua
exports['nx_computer']:WriteAudit({    action = 'store.refund',    actorAccountId = accountId,    severity = 'notice',    detail = { orderId = 4471, amount = 250 },})

Market data#

The market engine holds live prices in memory. These reads do not touch the database and do not yield. They fail closed before the engine has finished starting: MarketGetPrice returns nil and the list reads return an empty table, so an unknown symbol is never priced.

exports.nx_computer:MarketGetPriceserver

The current price of one asset. Returns nil for an unknown symbol or before the engine is live.

Parameters

symbol string
An asset symbol.

Returns

number | nil
Lua
local price = exports['nx_computer']:MarketGetPrice('NXC')
exports.nx_computer:MarketGetAssetserver

The full public snapshot for one asset. Returns nil for an unknown symbol or before the engine is live.

Parameters

symbol string
An asset symbol.

Returns

table | nil

Fields worth reading:

  • symbol, name, class, sector: the asset's identity.
  • price (number): the current price.
  • change24h (number): the 24 hour change as a fraction, so -0.134 is a 13.4 percent fall.
  • volume24h (number): traded volume over the same window.
  • valuation (number): how far the price sits from its public centre, in standard deviations. Negative reads cheap, positive reads rich.
  • regime (string): calm, normal, or turbulent.
  • halted (boolean): whether trading hours currently block the asset.
  • decimals (number): the display precision.
  • spreadBps (number): the quoted spread in basis points.

The table also carries the asset's static definition fields.

Lua
local asset = exports['nx_computer']:MarketGetAsset('NXC')if asset then    print(asset.name, asset.price, asset.regime)end
exports.nx_computer:MarketListAssetsserver

Every asset's snapshot, in the same shape MarketGetAsset returns. Returns an empty table before the engine is live.

Returns

table
Lua
for _, asset in ipairs(exports['nx_computer']:MarketListAssets()) do    print(asset.symbol, asset.price)end
exports.nx_computer:MarketGetCandlesserver

Price history for one asset, oldest first, with the live in-progress candle appended last. Returns an empty table for an unknown symbol or an unrecognised resolution.

Parameters

symbol string
An asset symbol.
resolution string
One of 1m, 5m, 1h, 1d.
limit? number
How many candles to return. Clamped to 1 through 500. Defaults to 200.

Returns

table

Each candle is a table of t (bucket timestamp), o, h, l, c (open, high, low, close) and v (volume). History can be sparse at the finer resolutions, so gaps are skipped rather than padded.

Lua
local candles = exports['nx_computer']:MarketGetCandles('NXC', '1h', 48)
exports.nx_computer:MarketRecentEventsserver

Recent market events, newest first. Only moves that clear a newsworthiness bar are published, so this is a headline feed rather than every tick.

Parameters

sinceTs? number
Only return events at or after this unix timestamp. Defaults to 0.
limit? number
How many events to return. Clamped to 1 through 64. Defaults to 32.

Returns

table

Each event is a table of:

  • kind (string): the event kind.
  • scope (string): whether the event hit one asset or a whole sector.
  • symbol (string or nil): set for single-asset events.
  • sector (string or nil): set for sector-wide events.
  • magnitude (number): the signed fractional move, so -0.134 is a 13.4 percent fall.
  • ts (number): the unix timestamp of the event.
Lua
local events = exports['nx_computer']:MarketRecentEvents(os.time() - 3600, 10)

Job rosters#

These read the framework job data the laptop uses for job-wide email forwarding.

exports.nx_computer:GetJobInfoForSourceserver

The player's current job as { name, label }. Returns nil when the player has no job, or when the job is unemployed or none.

Parameters

source number
A player server id.

Returns

table | nil
Lua
local job = exports['nx_computer']:GetJobInfoForSource(source)if job then print(job.name, job.label) end
exports.nx_computer:GetJobMemberIdentifiersserver

The character identifiers of everyone in a job, online and offline, without duplicates. Capped at 250 and cached for 60 seconds per job. Returns an empty table for an unknown job and never throws.

Parameters

jobName string
A framework job name.

Returns

table
Lua
for _, identifier in ipairs(exports['nx_computer']:GetJobMemberIdentifiers('police')) do    local account = exports['nx_computer']:ResolveActorAccountByIdentifier(identifier)end

Permissions from your own script#

By default, Config.SiteBuilder.AllowedRanks decides who may build a company's website, and Config.Newsroom.Jobs decides which jobs write for the Newsroom. A company or job script can set both from its own data instead, so you don't have to copy its grade list into nx_computer's config.

These settings are kept in memory and belong to the resource that made them. When that resource stops, they are dropped. Register them again when your resource starts and when nx_computer starts. The nx_computer:permissionsReady server event fires once nx_computer is ready to accept them. Each export returns true, or false, err when the arguments are invalid.

Who may build a site is decided in this order:

  1. Config.SiteBuilder.Enabled = false turns the builder off for everyone.
  2. A per-character setting from SetSiteBuilderAccess for the character's current job.
  3. Grades set with SetSiteBuilderRanks for that job.
  4. Config.SiteBuilder.AllowedRanks.

The same rule decides who reviews the job applications sent to that company, on its site and in the Jobs app. That covers its own grades, not the reviewers a boss adds by name.

exports.nx_computer:SetSiteBuilderRanksserver

Choose which grades of a job may build and manage its company website. This replaces Config.SiteBuilder.AllowedRanks for that job, including its default entry. A grade name is matched against the framework's grade name. On QBCore and Qbox that is the grade's label, such as 'Omistaja'.

Parameters

jobName string
A framework job name.
ranks table | nil
Grade names and grade numbers allowed to build, as a list or in AllowedRanks form. {} allows nobody. nil goes back to the config.

Returns

true | false, err

Errors: invalid_job, invalid_ranks, too_many_ranks (more than 64).

Lua
-- grades 3 and 4, plus any grade named 'Esimies'exports['nx_computer']:SetSiteBuilderRanks('autoshop', { 3, 4, 'Esimies' })-- the AllowedRanks form works tooexports['nx_computer']:SetSiteBuilderRanks('autoshop', { [3] = true, Esimies = true })-- back to the configexports['nx_computer']:SetSiteBuilderRanks('autoshop', nil)
exports.nx_computer:SetSiteBuilderAccessserver

Allow or block one character for one company's website. The setting applies only while their current job is jobName, so it does not follow them to another job. It overrides the grade rules.

Parameters

identifier string | number
The character's identifier (ESX identifier, QBCore/Qbox citizenid), or an online player's server id.
jobName string
The job this setting applies to.
allowed boolean | nil
true: may build whatever their grade. false: may not, even at a boss grade. nil: removes the setting.

Returns

true | false, err

Errors: invalid_job, invalid_allowed, invalid_identifier, no_player (a server id with no character loaded), too_many_entries (more than 512 per job).

Lua
exports['nx_computer']:SetSiteBuilderAccess(citizenid, 'autoshop', true)
exports.nx_computer:CanUseSiteBuilderserver

Whether a player may build their current job's company website right now, after every rule above. The reason is player_grant, player_denied, job_ranks, config, rank_denied, no_job, disabled, or invalid_source.

Parameters

source number
A player server id.

Returns

boolean, reason
Lua
local ok, reason = exports['nx_computer']:CanUseSiteBuilder(source)
exports.nx_computer:SetNewsroomJobserver

Add a job to Config.Newsroom.Jobs, or take one out of it. The Newsroom app appears or disappears for that job's online players without a relog. Who may edit and publish still follows Config.Newsroom.EditorGrade.

Parameters

jobName string
A framework job name.
minGrade number | false | nil
The lowest grade that writes. false: not a Newsroom job, even if the config lists it. nil goes back to the config.

Returns

true | false, err

Errors: invalid_job, invalid_grade.

Lua
exports['nx_computer']:SetNewsroomJob('lsnews', 0)
Lua
-- Register on your own start, on nx_computer's start, and on its ready event.local function registerWithComputer()    if GetResourceState('nx_computer') ~= 'started' then return end    exports['nx_computer']:SetSiteBuilderRanks('autoshop', { 3 })endAddEventHandler('nx_computer:permissionsReady', registerWithComputer)CreateThread(registerWithComputer)

Job postings#

Player-run company sites can publish job postings. These reads let a jobs board or a hiring resource show those postings next to its own.

exports.nx_computer:GetPublishedSitePostingsserver

Every open posting on a published player site, newest first. Returns an empty table when there are none.

Returns

table

Each posting is a table of postingId, siteId, siteSlug, siteName, jobName, title, description, requirements, salaryMin, salaryMax, category, and questions (the posting's application form schema).

Lua
local postings = exports['nx_computer']:GetPublishedSitePostings()
exports.nx_computer:PostingExistsAndOpenserver

Whether a posting is still open on a still-published site. Check this before accepting an application against a posting id.

Parameters

postingId number
A posting id from GetPublishedSitePostings.

Returns

boolean
exports.nx_computer:GetPostingQuestionsserver

The saved application-form schema for one posting, so answers can be rendered with their labels instead of raw ids. Returns an empty table when the posting has no questions or does not exist.

Parameters

postingId number
A posting id from GetPublishedSitePostings.

Returns

table

Employees#

The Employees app keeps per-grade permissions for every job. These exports answer from the same data, and they give the same answers as nx_employeemanagement's exports of the same name, so a script written for one works with the other.

exports.nx_computer:HasRankPermissionserver

Whether a grade of a job holds one of the Employees permissions. A boss grade always does. Every other grade answers from what the boss granted it on the app's Access page. Returns false for an unknown key, a bad grade, or while Config.Business.Enabled is false. It never throws.

Parameters

job string
A framework job name.
grade number
A grade number of that job.
key string
One of employees, management, payroll, bossActions, society.

Returns

boolean

nx_realbanking reads the society key ("Society funds") from here when nx_employeemanagement is not running, to decide who may use a company's account in Banking.

Lua
if exports['nx_computer']:HasRankPermission('mechanic', 3, 'payroll') then    -- grade 3 of mechanic may run payrollend
exports.nx_computer:RunPayrollserver

Pay a job's tracked hours now, the same as Pay now on the app's Payroll page. Every payment gets its payslip and pay notification as usual.

Parameters

job string
A framework job name.

Returns

true, summary | false, err

On success, summary is a table of job, employees, paid, queued (offline employees, paid at their next login), insufficient (the company account was short), failed, settledZero, total, runId and status.

Errors:

  • invalid_job: not a job the Employees app manages.
  • disabled: Config.Business.Enabled is false.
  • em_running: nx_employeemanagement is running, so it runs payroll. Call its RunPayroll instead.
  • payroll_disabled: payroll is turned off.
  • framework_mode: the job is paid by your framework (Payroll.Mode or PerJobModes is 'framework').
  • no_employees: nobody had hours to pay.
  • error: the run failed. The server console has the reason.
Lua
local ok, result = exports['nx_computer']:RunPayroll('mechanic')if ok then    print(('%d paid, total %s'):format(result.paid, result.total))else    print('payroll not run: ' .. result)end

Dispatch#

The MDT's built-in dispatch board takes calls from other resources. These exports work only while Config.MDT.Dispatch.Enabled is true. With dispatch off, DispatchAlert and DispatchPanic return false, 'dispatch_off'.

exports.nx_computer:DispatchAlertserver

Put a call on the dispatch board. A report of the same incident close in time and place joins the existing call instead of making a second one.

Parameters

alert table
The call. See below.

Returns

callNo, info | false, err

The alert table fields:

  • pos (vector3 or { x, y, z }, required): where it happened.
  • kind (string, optional): the call type, one of the types in data/mdt/dispatch.lua (shots, robbery, medical, fire, suspicious and so on). An unknown type becomes other. The type sets the default services and priority.
  • services (table, optional): { 'police' }, { 'ems' }, { 'fire' } or a mix. Without it, the call goes to the departments that hold the job names in jobs, or else to the type's default services.
  • jobs (table, optional): framework job names the alert is meant for, such as { 'ambulance' }.
  • priority (number, optional): 2 urgent, 3 normal, 4 low. Priority 1 is kept for the panic button and officer down; a higher request becomes 2.
  • title (up to 160 characters), body (up to 1000), code (such as 10-71), street, zone (strings, optional): the text officers see.
  • plate, vehicle, suspect, weapon (strings, optional): descriptions. The plate is stored partly masked.
  • data (table, optional): your own data, up to 2 KB as JSON.

On success, info is 'created', 'merged' (joined an existing call) or 'escalated' (joined it and raised its priority).

Errors: dispatch_off, bad_alert (no pos, or a bad field), no_agency (no enabled department serves the call), rate_limited (more than 30 calls in 10 seconds from your resource), db_error.

Lua
local callNo, info = exports['nx_computer']:DispatchAlert({    kind = 'robbery',    title = 'Store robbery',    body = 'Silent alarm at the 24/7 on Innocence Blvd.',    code = '10-31',    pos = GetEntityCoords(GetPlayerPed(source)),})
exports.nx_computer:DispatchPanicserver

Press the panic button for an officer: a priority 1 call at their position for police and for their own department, exactly as the panic key does.

Parameters

source number
The officer's server id.

Returns

callNo | false, err

The player must be on duty in an MDT department. One officer can panic once every 10 seconds. Errors: dispatch_off, bad_source, cooldown, no_agency, db_error, or the reason the player may not use dispatch.

Lua
exports['nx_computer']:DispatchPanic(source)
exports.nx_computer:DispatchStatusserver

Whether built-in dispatch is running, and who it serves: { v = 1, running, jobs, services }. jobs are the framework job names of the enabled departments and services the services they cover. While dispatch is off, running is false and both lists are empty.

Returns

table
Lua
local status = exports['nx_computer']:DispatchStatus()if status.running then    -- send alerts to nx_computer instead of your old dispatch scriptend
exports.nx_computer:GetDispatchCallsserver

The calls on the board right now, most urgent first. Each is { callId, callNo, kind, code, title, priority, state, pos, street, services, unitCount, createdAt }. It carries no names or other personal details.

Returns

table

MDT records#

Other resources can write to the MDT the way an officer would. Every call returns true, data or false, err, writes an audit entry, and is limited to 30 calls per 10 seconds per resource. Config.MDT.Exports turns them off (Enabled) or limits them to named resources (Allow).

Pass officer = <server id> to act as that officer: their rank, permissions and duty are checked as on the laptop. Without it the call runs as the system. A person is citizen = <server id> or identifier = '<citizenid or ESX identifier>'. Name the department with agency = '<key>' when the server runs more than one police department.

ExportArgumentsReturns
CreateWanted(args){ target = 'person'|'vehicle', citizen?|identifier?, plate?, description?, warrant?, reason, body?, charges? = {{code, count}}, expiresHours?, agency?, officer? }true, { id, refNo }
CancelWanted(id, opts){ reason?, served?, agency?, officer? } (served = true marks the person found)true, { id, state }
CreateReport(args){ kind = 'incident'|'arrest', title, body?, people? = {{citizen?|identifier?, role}}, plates?, callId?, agency?, officer } (officer is required)true, { id, number }
AddReportCharge(reportId, args){ citizen?|identifier?, charges = {{code, count}}, months?, banHours?, agency?, officer? } (draft reports only; adds the person as a suspect)true, charges
RegisterWeapon(args){ serial, item?, label?, owner?, state?, notes? }true, { id, created }
SetWeaponState(serial, state, opts)state = registered, unregistered, stolen, seized or destroyed; { notes? }true, { id, state }
ApplyTag(args){ kind, ref, tag (id or name), on? = true, citizen?|identifier?, agency? }true, { tags }
SuspendLicence(args){ citizen?|identifier?, licence = 'driver', hours? (none = until lifted), reportId?, agency?, officer? }true, { citizenId }
CreateBulletin(args){ title, body, pinned?, agency?, officer? }true, { id }
SetProfilePhoto(args){ citizen?|identifier?, url, caption? }true, { imageId, photoUrl }
AddGalleryImage(args){ citizen?|identifier?, url, caption? }true, { imageId }
GetPersonFlags(who, opts)who = server id or identifier; { agency? }true, { citizenId, name, flags, wanted, warrant }
CreateFiling(args){ kind = 'crime'|'dispute', citizen?|identifier?, body, place?, when?, people?, contact?, reportId? (disputes), agency?, officer? }true, { id, number }

Common errors: officer_required, bad_citizen, not_found, bad_agency, agency_required, bad_officer, denied, off_duty, feature_off (the module behind the export is off) and rate_limited.

Lua
local ok, res = exports.nx_computer:CreateWanted({    target = 'person',    citizen = targetSource,    warrant = true,    reason = 'Armed robbery at the Vinewood jewellery store',})

The MDT on the phone#

exports.nx_computer:RegisterPocketSectionserver

Add a read-only page of your own to nx_phone's MDT app. Every read is audited, rows and text are clamped, and the page is removed when your resource stops. RemovePocketSection(id) removes it sooner. See Configuration, The MDT on the phone, for the layout and an example.

Parameters

id string
Your page id. Put it in the phone layout tabs to make it a tab.
def table
{ label, icon?, cap?, services?, list, get? }. label is { <locale> = text }. icon is one of file, list, shield, car, user, building, flag, book, alert, star. cap is the MDT permission the officer needs (nil = any member). list(officer, payload) returns rows { id, title, sub?, badge?, tone? }; get(officer, id) returns { id, title, sub?, facts = { { label, value } }, text? }.

Returns

true | false, err
Lua
exports.nx_computer:RegisterPocketSection('permits', {    label = { en = 'Permits' }, icon = 'book', cap = 'citizen.read',    list = function(officer, payload) return { { id = 'pm-1', title = 'Firearm permit', sub = 'Mia Laine' } } end,    get = function(officer, id) return { id = id, title = 'Firearm permit', facts = { { label = 'Holder', value = 'Mia Laine' } } } end,})

Newsroom#

The Newsroom stores the city's news stories. nx_phone's Bulletin app reads and writes them through these exports. Only resources named in Config.Newsroom.ExportResources may call them (default nx_phone); any other caller gets { success = false, error = 'forbidden' }.

The acting exports take the player's server id first. nx_computer resolves the character, the byline and the job itself, so the same job check applies on every device. Every reply carries success.

ExportArgumentsReturns
NewsStatus()none{ success, enabled, categories }
NewsHome(source, req){ category?, before? }A page of story cards, plus canWrite, isEditor and the current Breaking story
NewsArticle(source, req){ id }{ success, article }
NewsSearch(source, req){ q, before? }A page of matching cards
NewsMine(source, req){}The player's own stories, in any status
NewsSave(source, req){ id?, category, title, standfirst, blocks }{ success, article }
NewsPublish(source, req){ id, breaking? }{ success, article }, or an error with retryIn during the Breaking cooldown
NewsUnpublish(source, req){ id }{ success, article }
NewsDelete(source, req){ id }{ success }. Drafts only
NewsImport(origin, rows)An origin name and up to 50 stories{ success, imported, skipped, failed }
NewsImportWatermark(origin)An origin name{ success, watermark }, the id below which every row is imported

A story body is a list of blocks: { type = 'p', text } for a paragraph and { type = 'img', url, width, height, caption } for a picture. When you save through an export, a new picture needs a photoId and an https url. A picture the story already has can be kept by passing its ref.

Lua
local home = exports['nx_computer']:NewsHome(source, { category = 'crime' })if home.success then    for _, card in ipairs(home.items) do        print(card.title, card.author.name)    endend
exports.nx_computer:NewsEditionserver

The newspaper.lc front page: the same city-wide edition every player sees, built from real server activity. It needs no session and no allow-list.

Returns

table
Lua
local edition = exports['nx_computer']:NewsEdition()

Client#

exports.nx_computer:useCameraclient

Open in-world photo mode. This is the ox_inventory usable-item entry point for the camera item, wired as client = { export = 'nx_computer.useCamera' } in the item definition. It requires the screencapture (screenshot-basic) resource. Captured shots sync to the Photos app for the active account.

Lua
-- ox_inventory item definition['camera'] = {    label = 'Camera',    weight = 500,    stack = false,    client = { export = 'nx_computer.useCamera' },},
exports.nx_computer:usePolaroidclient

Hold a printed polaroid up to look at it. Nearby players see the photo on the prop. This is the ox_inventory usable-item entry point for the polaroid item, wired as client = { export = 'nx_computer.usePolaroid' }. A polaroid with no stored photo is refused.

Parameters

item table
The item template ox_inventory passes first. Unused.
slotData table
The used slot, carrying the polaroid's metadata.

The polaroid item must be stack = false: each printed photo carries its own slot metadata.

Lua
-- ox_inventory item definition['polaroid'] = {    label = 'Polaroid',    weight = 10,    stack = false,    client = { export = 'nx_computer.usePolaroid' },},
exports.nx_computer:placePolaroidclient

Start placing a printed polaroid on a wall or a surface. It takes the same two arguments ox_inventory passes to a client export, so it can be bound to a secondary action on the polaroid item. The same placement flow is reachable in game while holding a polaroid.

Parameters

item table
The item template ox_inventory passes first. Unused.
slotData table
The chosen slot, carrying the polaroid's metadata.

Internal exports#

The exports below exist so that the resource's own server files can call each other across Lua chunks, or so that development tools can drive the client. They are not an integration surface: their arguments, return shapes, and existence can change between versions without notice.

Server: GetRoleInfo, PublicAccountFields, ValidateSessionPayload, GetSessionContext, GetCharacterDisplayName, RotateAccountSessions, SetAccountPin, AdminUnlockAccount, GenerateNumericPin, SetDeviceState, ListOwnerDevices, AdminRevokeAccountSessions, RefreshAccountAccess, ExecuteTrade, GetAuthoritativePrice, GetSourceFromAccountId, MarketQuoteFill, MarketRecordTrade, MarketTickAgeMs, IsBlocked, IsBlockedEitherWay, GetDarknetAlias, RecordDarknetOrder, GetSellerRatingStats, ResolveMentions, PushMentionNotifications, base64Encode.

Client: cameraDebugLiveAttach, cameraDebugCurrentProp, polaroidDebugRender, polaroidDebugCurrentProp, polaroidDebugTune, polaroidDebugStartHeld, polaroidDebugStopHeld, polaroidDebugClear.

We are not affiliated with or endorsed by Rockstar North, Take-Two Interactive or other rights holders. FiveM is a copyright and registered trademark of Take-Two Interactive Software, Inc. Our checkout process is owned & operated by Tebex Limited, who handle product fulfilment, billing support and refunds.