Loading the SDK…

LS:MP SDK: Gamescripting reference

This reference is normally built in the browser from /resources/sdk.json. The same content is published as Markdown at /resources/sdk.md, one file per section under /resources/api/<section>.md, and indexed at /llms.txt.

Get started

Get started

LS:MP scripting

Everything your server does beyond the base game is a resource: a folder of Lua or JavaScript scripts, web pages and assets. This SDK is the lsmp API those scripts use.

A resource is a folder in your server's resources/. Its server scripts run on your server; its client scripts are sent to every player and run in their game; its web pages draw interfaces in game. Each side can be written in Lua or JavaScript, with the same functions in both languages.

You want to…Use
React to players joining, spawning, dying, leavingEngine events with lsmp.on
Send data between server and clientsEvents (lsmp.emitServer / lsmp.emitClient, lsmp.onServer / lsmp.onClient) and calls (lsmp.call / lsmp.callServer / lsmp.callClient, lsmp.onCall)
Spawn vehicles, peds and objects that everyone seesEntities, with ownership and dimensions
Store dataMeta for live replicated values, storage, MySQL and files to keep them
Show an interfaceWeb pages in 2D or on a surface of the world (browsers)
Talk to players by voiceVoice channels driven by your scripts
Call web servicesThe HTTP client, and HTTP routes on the server
Drive the game itselfAbout 6,700 game natives, as global functions in client scripts
Ship models, maps and vehiclesAssets and streaming

Start here

Coming from FiveM

β„Ή
What maps to what

Most ideas carry over; the names change.

- fxmanifest.lua β†’ manifest.json, with client_scripts, server_scripts and shared_scripts. The resource's name is its folder name; no ensure line is needed.
- TriggerServerEvent β†’ lsmp.emitServer, received with lsmp.onClient; TriggerClientEvent β†’ lsmp.emitClient (target first), lsmp.emitAllClients or lsmp.emitDimensionClients, received with lsmp.onServer. On the server, the sending player is the first argument of the handler, not a source global.
- AddEventHandler / TriggerEvent β†’ lsmp.on / lsmp.emit. Server callbacks β†’ lsmp.onCall + lsmp.callServer / lsmp.callClient, built in. Exports β†’ lsmp.onCall + lsmp.call (any resource, Lua or JavaScript). GetHashKey β†’ lsmp.hash.
- Citizen.Wait / Citizen.CreateThread β†’ lsmp.wait / lsmp.createThread in Lua, await in JavaScript.
- Routing buckets β†’ dimensions. State bags β†’ meta. SetResourceKvp β†’ lsmp.storage.
- NUI β†’ browsers: browser.emit / browser.on in the script, lsmp.emit / lsmp.on in the page.
- Natives are camelCase globals and out-params come back as results: see Game natives.

Get started

Quick start: your first resource

From an empty folder to a server script and a client script talking to each other in game, in five minutes.

You need a running server on your machine and the LS:MP client. We build a resource named hello: the client greets the server, the server answers that player, and the client asks the server how many players are online.

  1. Create the folder

    In your server's folder, create resources/hello/. The folder name is the resource's name: 1 to 64 characters, lowercase letters, digits, _ and -, starting with a letter or a digit. Hello or my mod would be refused, with a suggested name in the console. Names starting with lsmp are reserved.

    Lua only:

    resources/
    └─ hello/
       β”œβ”€ manifest.json
       β”œβ”€ server/
       β”‚  └─ main.lua      # runs on the server only
       └─ client/
          └─ main.lua      # sent to every player, runs in their game

    JavaScript only:

    resources/
    └─ hello/
       β”œβ”€ manifest.json
       β”œβ”€ server/
       β”‚  └─ main.js       # runs on the server only
       └─ client/
          └─ main.js       # sent to every player, runs in their game
  2. Write the manifest

    manifest.json lists which files run where. Each list takes a string or an array, and accepts patterns such as "client/*.lua". A side can mix .lua and .js files. Every key is described in Resource layout.

    Lua only:

    jsonmanifest.json
    {
      "title": "Hello",
      "server_scripts": ["server/main.lua"],
      "client_scripts": ["client/main.lua"]
    }

    JavaScript only:

    jsonmanifest.json
    {
      "title": "Hello",
      "server_scripts": ["server/main.js"],
      "client_scripts": ["client/main.js"]
    }
  3. Write the scripts

    The server listens for the client's hello:ping event and answers with hello:pong to that player only. It also handles the remote call hello:playerCount, whose return value travels back to the caller. Prefix your event names with the resource name: event names are shared by every resource.

    luaserver/main.lua
    -- server/main.lua
    lsmp.on("playerJoin", function(playerId, name)
      lsmp.log(name .. " joined (#" .. playerId .. ")")
    end)
    
    -- A client says hello: answer that player only.
    -- 'source' is the sender's playerId, set by the server: it cannot be forged.
    lsmp.onClient("hello:ping", function(source, text)
      lsmp.log("ping from #" .. source .. ": " .. text)
      lsmp.emitClient(source, "hello:pong", "hello, " .. lsmp.getPlayerName(source))
    end)
    
    -- A remote call: the client waits for this return value.
    lsmp.onCall("hello:playerCount", function(source)
      return #lsmp.getPlayers()
    end)
    luaclient/main.lua
    -- client/main.lua
    lsmp.onServer("hello:pong", function(text)
      lsmp.log("server says: " .. text)
    end)
    
    lsmp.emitServer("hello:ping", "hi from the client")
    
    -- The file body may wait: lsmp.callServer suspends it until the answer comes.
    local count, err = lsmp.callServer("hello:playerCount")
    if count then
      lsmp.log(count .. " player(s) online")
    else
      lsmp.warn("call failed: " .. err)
    end
    jsserver/main.js
    // server/main.js
    lsmp.on('playerJoin', (playerId, name) => {
      lsmp.log(`${name} joined (#${playerId})`);
    });
    
    // A client says hello: answer that player only.
    // 'source' is the sender's playerId, set by the server: it cannot be forged.
    lsmp.onClient('hello:ping', (source, text) => {
      lsmp.log(`ping from #${source}: ${text}`);
      lsmp.emitClient(source, 'hello:pong', `hello, ${lsmp.getPlayerName(source)}`);
    });
    
    // A remote call: the client waits for this return value.
    lsmp.onCall('hello:playerCount', (source) => lsmp.getPlayers().length);
    jsclient/main.js
    // client/main.js
    lsmp.onServer('hello:pong', (text) => {
      lsmp.log(`server says: ${text}`);
    });
    
    lsmp.emitServer('hello:ping', 'hi from the client');
    
    lsmp.callServer('hello:playerCount')
      .then((count) => lsmp.log(`${count} player(s) online`))
      .catch((err) => lsmp.warn(`call failed: ${err.code}`));
  4. Start the resource

    The server loads its resources when it starts: restart it so it loads hello (type quit in the server console, the terminal or the Console tab of the admin panel, then start the server again). After each change to the files, restart the server again.

  5. Join and look

    Join your server with LS:MP. The server console shows [hello] … joined (#…) and the ping. In the game, open the client console with F8: it shows [hello] server says: hello, … and the player count. Every line of a resource starts with its name.

  6. Go further

    You have the whole loop: files in a folder, a manifest, both sides, events and a remote call.

βœ“
When something goes wrong

A resource that fails to start says why in the server console, in red, with the file and the line: an invalid manifest.json, a script that raises at load, a missing dependency. resources in the console lists every resource with its state.

Get started

Core concepts

The handful of ideas every page of this SDK relies on. A few lines each, with a link to the full story.

Resources

A resource is a folder in resources/ with a manifest.json. Its name is the folder name, and that name is its identity everywhere: logs ([bank] …), the console (resources), dependencies, web addresses (rsc://bank/), and the storage that belongs to it. A resource starts, runs and stops as one unit (on a server: from the server start to its shutdown); when it stops, what it created goes with it: handlers, timers, entities, settings. See Resource layout and Lifecycle.

Server, client and page

SideWhere it runsTypical job
ServerOn your server, once.The authority: rules, money, permissions, persistent data, entities everyone shares.
ClientIn each player's game, sent with the resource.What one player sees and does: natives, HUD, input, camera, local effects.
PageIn a web page the client script opens in game.Interfaces in HTML, CSS and JavaScript, with their own small lsmp object (Page API).

Never trust the client: anything a client sends can be forged by a modified game. Check it on the server.

Lua and JavaScript

Every side can be written in Lua or JavaScript: the server runs Lua and Node.js, the client runs Lua and V8. The lsmp API has the same functions, arguments and results in both. The few differences of style (obj:m() against obj.m(), nil against null, coroutines against Promises) are listed in Conventions. A resource can mix both languages on one side: they talk through events.

Identifiers

NameWhat it identifiesValid
playerIdA connected player, for this session. Given by the server, the same on every side.until the player leaves
lsmpIdA player's LS:MP account. nil / null for a guest.forever
netIdA networked entity (vehicle, ped, object), the same on the server and on every client.while the entity exists
handleAn entity in one player's game: what the natives take. Get it from a netId with lsmp.getEntityFromNetId.on that client, while the entity is streamed in
dimensionA separate world on the same server, 0 by default.0 to 65535

Engine events and script events

Engine events are sent by LS:MP itself: playerJoin, playerSpawn, playerDeath, resourceStart… You listen to them with lsmp.on; their names are reserved, so no script can fake one. The full list is in Engine events.

Script events are yours. lsmp.emit reaches the handlers of the same side, in every resource and both languages; network events carry their direction in their name: lsmp.emitServer (client β†’ server, received with onClient) and lsmp.emitClient / emitAllClients / emitDimensionClients (server β†’ players, received with onServer). A call asks a question and waits for the answer: lsmp.call to another resource of the same side, lsmp.callServer from a client, lsmp.callClient from the server, all answered by lsmp.onCall. See Events, Remote calls and the Events and RPC guide.

luaLua
lsmp.on("playerDeath", function(playerId, killerId)
  lsmp.log(lsmp.getPlayerName(playerId) .. " died")
end)

lsmp.onClient("shop:buy", function(source, item)
  -- source: the playerId that sent the event
end)
jsJavaScript
lsmp.on('playerDeath', (playerId, killerId) => {
  lsmp.log(`${lsmp.getPlayerName(playerId)} died`);
});

lsmp.onClient('shop:buy', (source, item) => {
  // source: the playerId that sent the event
});

Entities and ownership

A networked entity exists once for the whole server, with one netId. Its physics and AI are simulated by one player's game at a time, its owner, usually a player close to it; the others receive its state. When the owner leaves or moves away, another player takes over. The server decides who may own an entity and when it is deleted (ownerPolicy, lifePolicy), and can keep an entity alive after the resource that created it stops. See Entities and Ownership.

Dimensions

A dimension is a separate copy of the world on the same server. Players and entities only see, hear and meet what shares their dimension. Use one for an interior, a race, a private lobby. Everyone starts in dimension 0. See Dimensions.

Meta and storage

MetaStorage
WhatLive values attached to the server (global), a player or an entity.Your resource's persistent key/value store.
WhereReplicated: every client reads them, and gets notified when they change.On the server only.
How longUntil the player leaves, the entity goes, or the server stops.Kept across restarts.
ForA player's job title on their nametag, a door state, a vehicle's fuel.Balances, unlocks, settings.

See Meta, storage and the Storing data guide.

Asynchronous calls

Anything that waits for the network, the disk or the game (remote calls, HTTP, captures, resource jobs) is asynchronous, and never completes during the call itself. In JavaScript it returns a Promise: await it. In Lua the file body, every handler and lsmp.createThread run in a coroutine, so local value, err = lsmp.call(…) simply waits; a callback as last argument works too. See Conventions.

Sandbox and capabilities

Server resources run sandboxed by default: no access to the machine beyond their own data folder, and sensitive functions refused. The server operator decides, per resource, what is lifted (in resources.json and the admin panel), and grants capabilities such as changing the weather or deleting other resources' entities. A function refused for lack of a capability returns the permission code instead of raising. See Operator settings and Capabilities.

Run a server

Run a server

Install and first start

From an empty folder to a server that players can join, on Windows or Linux: download, first start, setup page, and the folders the server creates.

An LS:MP server is one program. It reads server.cfg, packs the resources it finds in resources/, starts them, and waits for players. You need a machine that stays on, an LS:MP account to link the server to, and two open ports.

WindowsLinux
SystemWindows x64x64 with glibc 2.34 or newer: Debian 12, Ubuntu 22.04, RHEL / Rocky / Alma / Oracle Linux 9, Fedora 35, or newer. Packages: libcurl, brotli, libstdc++, ca-certificates.
Programlsmp-server.exe./lsmp-server
Ports2086 TCP (HttpPort), 9530 TCP and UDP (GamePort)the same

Install

  1. Download

    Get the server package for your system on the download page, and unpack it in a folder of its own. Keep everything together: the program, its libraries and the uiadmin/ folder (the admin panel's interface). On Linux, make the program executable, and do not run it as root.

    bashLinux
    cd /home/lsmp/server
    chmod +x lsmp-server
  2. Start it once

    Run the program from its folder: the server looks for every file in its working folder. On Windows, open a terminal in the folder and run lsmp-server.exe, so that you can read the console. At this first start the server writes a commented server.cfg with every default, packs the resources, opens its ports and prints a framed SETUP REQUIRED message with a one-time code. Leave it running.

    textserver console
    SETUP REQUIRED
    
    Open the admin panel of this gameserver:
        http://203.0.113.10:2086/lsadmin
    and enter this one-time setup code:
        XXXX-XXXX-XXXX
  3. Open the ports

    Open HttpPort (2086) in TCP, and GamePort (9530) in TCP and UDP. Behind a home router, also forward them to this machine. The commands for each system are in Go public.

  4. Run the setup page

    Open http://<server-ip>:2086/lsadmin in a web browser and enter the code. A new code is printed at each start until the setup is finished. The setup has five steps, and you can go back to any of them:

    1. Terms: read the LS:MP EULA to the end and accept it. It is the text of eula.txt, next to server.cfg.
    2. LS:MP account: press Continue with LS:MP, approve on lsmp.gg, and check that the pairing code matches. LS:MP sends the server its network Token by itself. You can skip this step and link the server later.
    3. Server: name, description, maximum players and map. A linked server can turn on the public listing here.
    4. Access: how administrators sign in. LS:MP sign-in only is recommended; a local account needs a password of 8 characters or more.
    5. Finish: review, press Finish setup, then Restart now. Everything is written to server.cfg and applies at this restart.
  5. Join it

    Start LS:MP and join by address: ip:2086, the HTTP port, never the game port. Your server does nothing visible without resources: players need at least a resource that spawns them. Start from the resources that ship with the server, or write your first one.

βœ“
Setting up by hand

Read eula.txt, set Eula=true (and your Token, if you have one) in server.cfg, and restart. The panel then opens normally, at /lsadmin.

The server folder

After the first start, the folder looks like this. You edit the files marked yours; the others are written by the server.

server/
β”œβ”€ lsmp-server           # the program (lsmp-server.exe on Windows)
β”œβ”€ uiadmin/              # the admin panel's interface: keep it next to the program
β”œβ”€ server.cfg            # yours: ports, name, limits, token (see server.cfg reference)
β”œβ”€ resources.json        # yours: per-resource settings (enabled, sandbox, client mount)
β”œβ”€ eula.txt              # the licence you accepted
β”œβ”€ admin-users.json      # local accounts of the admin panel
β”œβ”€ blacklist.json        # bans and whitelist
β”œβ”€ perms.json            # permissions and resource capabilities
β”œβ”€ resources/            # yours: one folder per resource
β”‚  └─ hello/
β”‚     └─ manifest.json
β”œβ”€ manifest.json         # generated: what players download first
β”œβ”€ packages/             # generated: each resource packed for clients and for the server
β”œβ”€ data/                 # generated: private data folders of your resources
β”œβ”€ storage/              # generated: the persistent storage of your resources
β”œβ”€ logs/                 # generated: one log file per session
└─ stats/                # generated: metrics history for the admin panel
⚠
manifest.json at the root is not yours

The manifest.json next to the program is regenerated at every start from your resources. Edit the manifest.json inside each resource folder, and per-resource settings in resources.json.

What happens at startup

  1. The server reads server.cfg. An unknown key, an invalid value or an old key name is reported with its line, and the default is used: see server.cfg reference.
  2. It reads resources.json, then scans resources/. Every valid folder becomes a resource named after the folder; a folder with an invalid name is refused, with the name to use instead.
  3. It packs each resource: a client package for the players and a server package for itself. A package that did not change is not rebuilt.
  4. It starts every enabled resource, dependencies first, then delivers serverStart.
  5. It opens the game port (GamePort, TCP and UDP) and serves HTTP on HttpPort: the manifest, the downloads, the admin panel at /lsadmin, and the HTTP routes of your resources.

A player gives out the HTTP address (ip:2086). Their client downloads the manifest there, learns the game port from it, downloads the packages it is missing, then opens the game session on GamePort.

Add or change a resource

Copy the folder into resources/, then restart the server: resources are read once, when the server starts, and every enabled resource starts on its own. The same goes after editing a resource.

Stop it cleanly

Type quit in the console, press Ctrl+C, stop the service, or use Shutdown in the admin panel. The server then refuses new players, says goodbye to the connected ones (playerLeave with the reason "shutdown"), gives your resources ShutdownGraceMs (5 s) to finish their serverStop handlers, stops them, and writes their key/value stores. A crash or a killed process skips all of this.

Keep it running on Linux

A systemd service starts the server with the machine and restarts it after a crash. A service has no terminal: set ConsoleStdin=false in server.cfg, and use the Console tab of the admin panel. Read the output with journalctl -u lsmp -e.

ini/etc/systemd/system/lsmp.service
[Unit]
Description=LS:MP gameserver
After=network-online.target
Wants=network-online.target

[Service]
User=lsmp
WorkingDirectory=/home/lsmp/server
ExecStart=/home/lsmp/server/lsmp-server
Restart=always
KillSignal=SIGINT
TimeoutStopSec=30

[Install]
WantedBy=multi-user.target
bash
sudo systemctl daemon-reload
sudo systemctl enable --now lsmp

Troubleshooting

SymptomCause and fix
The Linux program does not start, with a GLIBC or library errorThe system is too old, or libcurl or brotli is missing: see the table at the top of this page.
/ answers 404 on the HTTP portNormal: the panel is at /lsadmin.
The panel page is blank or brokenThe uiadmin/ folder is not next to the program, or the server was not started from its folder.
The setup code is lostA new one is printed at each start. On a service, read journalctl -u lsmp -e.
HttpPort (line …) and GamePort (line …) are both … and the server exitsThe two ports must differ: fix server.cfg.
MaxPlayers is lower than what you setIt is capped by the plan of the server's owner, with a line in the log.
Players connect, then nothing movesGamePort is open in TCP but not in UDP.
Players cannot reach the server at allCheck HttpPort from outside your network, and that players use ip:HttpPort. See Go public.
A resource does not startThe console says why, in red: invalid manifest.json (with line and column), a script that raises at load, a missing dependency. resources lists every resource with its state. See Debugging.
resource folder 'MyMod' is not a valid name …: use 'mymod'Rename the folder: names are lowercase, see Resource layout.
Ports stay in use after a crash, or at a second startAnother instance is running. To run two servers, give each one its own folder, HttpPort and GamePort.
Run a server

server.cfg reference

Every key of the server's configuration file: type, unit, default and range, how the file is read, and what happens to a file that still uses old key names.

server.cfg sits next to the server program. The server writes it, commented, at its first start, and reads it at every start. The Settings tab of the admin panel edits the same file, with a form and a raw view. Per-resource settings (enabled, sandbox, client mount) are not here: they live in resources.json.

iniserver.cfg (excerpt)
# Game TCP/UDP port. Open both protocols on this port. Must differ from HttpPort.
# Range: 1..65535 port. Default: 9530
GamePort=9530

HttpPort=2086
Name=My LS:MP server
MaxPlayers=64
PublicList=false
Token=

How the file is read

  • One Key=Value per line. Spaces around the key and the value are ignored. A line starting with # or ; is a comment.
  • Key names are case-sensitive: GamePort, not gameport. When a key appears twice, the last line wins.
  • Booleans: true/false, yes/no, on/off or 1/0, in any case.
  • Lists: comma-separated values; an empty value means an empty list.
  • Text (Name, Description, Discord texts): \n, \r, \t and \\ are escapes, so a multi-line description stays on one line.
  • The file is at most 4 MiB, 64 KiB per line. A UTF-8 BOM is accepted.
  • Every change applies at the next start, except where a key says otherwise.

Mistakes and warnings

The server never stops on a bad line, with one exception (equal ports). Each problem is logged with its line number, and the server carries on with the default:

ProblemWhat the log saysWhat the server does
Invalid value (type, range, malformed list)[server.cfg] line 12: 'MaxPlayers' = 'lots' is invalid (expected …), using default 64Uses the default. The value of Token is never printed.
Unknown key[server.cfg] line 4: 'Gameport' is not a key, did you mean 'GamePort'?Ignores the line.
Old key name (see below)[server.cfg] line 7: obsolete key 'PlayPort': use 'GamePort'Ignores the line; one warning per key.
GamePort equal to HttpPortHttpPort (line 3) and GamePort (line 2) are both 9530: they must differ. The server does not start.Exits. Fix the file and start again.
Line without =[server.cfg] line 9: expected a nonempty key=valueIgnores the line.
Missing fileserver.cfg created with default settingsWrites a commented file with every default.
⚠
An invalid SandboxNetConnect allows nothing

Every invalid value falls back to its default, except SandboxNetConnect: an invalid list becomes an empty list, which forbids every outgoing connection of sandboxed resources. Check the log after editing it.

General

KeyTypeDefaultRange / valuesDescription
Eulaboolfalsetrue accepts the LS:MP gameserver EULA (eula.txt). The setup page writes it for you.
NametextLS:MP Serverup to 256 UTF-8 bytesDisplay name in the server browser.
Descriptiontextemptyup to 16384 UTF-8 bytesShown under the name. Use \n for a new line.
MaxPlayersint641..4096 playersMaximum connected players. Capped at startup by the plan of the server's owner, with a line in the log.
Mapenummpmp \| spThe world players load: mp is the multiplayer map, with every multiplayer location; sp is the story-mode map.
Tokentextemptyprintable ASCIIYour private LS:MP network token, from My Servers. Never share it. See Go public.
PublicListboolfalseAdvertise the server in the public server browser. Needs a valid Token. Switched from the admin panel on a linked server, it applies at once.
LsmpNetworkbooltrueLink with the LS:MP network. false cuts every link: the server is not registered or listed, players are not verified (an LS:MP ID is whatever the client claims), plan features and benefits are off, no new marketplace mod is downloaded, and the server no longer learns its public address (set PublicAddress). Not recommended. File only: the panel has no switch for it.
AutoUpdatebooltrueInstall new server versions by itself once no player has been connected for 5 minutes. Applies at once from the admin panel. See Updates.
UpdateChanneltextstablea-z, 0-9 and -Release channel of the self-updater. Change it only if LS:MP asks you to.

Network and ports

KeyTypeDefaultRange / valuesDescription
GamePortport95301..65535Game port, TCP and UDP. Must differ from HttpPort.
HttpPortport20861..65535HTTP port, TCP: the address players join, the downloads, the admin panel (/lsadmin) and the HTTP routes of your resources.
PublicAddresstextemptyIP:port or [IPv6]:portAddress announced for joins, with the HTTP port: an IP address, not a domain name. Empty uses the address the server is reached at. Set it behind NAT or a proxy.
ClientIdleTimeoutSecuint150..86400 sSeconds without traffic before a player is disconnected. 0 turns the check off.
MaxTcpConnectionsPerIpuint160..4294967295Simultaneous game TCP connections per source IP. 0 = no limit.
MaxPkgStreamsPerIpuint40..4294967295Simultaneous package downloads per source IP. 0 = no limit.
MaxPkgStreamsuint00..4294967295Simultaneous package downloads in total. 0 = max(64, 2 Γ— MaxPlayers).

Players and protection

KeyTypeDefaultRange / valuesDescription
RequireAdmissionbooltruePlayers need a valid admission from LS:MP to join. Turn it off only for development or a LAN.
AllowGuestsbooltrueLet guest players (no LS:MP account) join. false refuses them before they download anything. Reliable with VerifyLsmpIntegrity, which proves the account. Applies at once from the admin panel.
VerifyLsmpIntegrityboolfalseHave LS:MP verify every joining player. Needs a Token and the matching subscription.
PermsTrustDeclaredIdsboolfalseLet LS:MP IDs that are not verified count for permissions. Unsafe: a modified client can claim someone else's ID. Applies at once from the admin panel.
MaxClientPayloadBytesuint419430465536..268435456 bytesLargest single request from an authenticated client.
MaxPreAuthPayloadBytesuint10240, or 512..MaxClientPayloadBytes bytesLargest request before authentication. 0 = same as MaxClientPayloadBytes.
MaxClientSendQueueBytesuint671088640..4294967295 bytesOutgoing bytes queued per player. 0 = no limit.
ScriptEventBytesPerSecuint10485760..4294967295 bytes/sBudget of script events and remote calls sent by each player to the server, with a 4-second burst. Events over budget are dropped. 0 = no limit.
MetaMaxKeysuint2560..65535Meta keys a client may write per player or entity. 0 = no limit.
MetaMaxBlobBytesuint655360..4294967295 bytesMeta bytes a client may write per player or entity. 0 = no limit.
MetaMaxEntriesPerWriteuint2560..65535Meta entries in one client write. 0 = no limit.
MetaWriteBytesPerSecuint655360..4294967295 bytes/sMeta written by each client, with a 4-second burst. 0 = no limit.
MaxCreatedEntitiesPerPlayeruint20480..65535Living entities created by one client. 0 = no limit.
MaxAdoptedPerPlayeruint480..65535Ordinary entities simulated by one client. 0 = no limit.

Peer-to-peer and sync

KeyTypeDefaultRange / valuesDescription
P2PbooltrueNearby players exchange movement updates directly over UDP; the server keeps authority.
P2PMaxPeersuint161..64 peersDirect peers per player (the closest ones). More peers mean more upload for each player.
P2PRangeMetersuint25050..1000 mTwo players link up when they are closer than this.
MaxSyncRateHzuint6015..120 HzHighest rate at which a player may send each entity's state. Clients normally send at 40 Hz.

World

KeyTypeDefaultRange / valuesDescription
DefaultDimensionuint00..65535Dimension every new player lands in. 0 is the shared world.
DefaultDimensionPopulationbooltrueAmbient population is allowed in dimensions unless a script says otherwise.
DefaultDimensionClientEntitiesbooltrueWhether players' games may create their own networked entities (ambient and scripted), in every dimension by default. false: only server scripts create entities. Per dimension: lsmp.setDimensionClientEntities.
PickupSyncbooltrueDropped weapons, cash and other pickups are shared by every player, and the server decides who collects them.
PickupLifetimeSecuint1800..86400 sTime before a dropped pickup disappears. 180 matches the game; 0 keeps it forever.

Ambient population

Traffic, parked cars and pedestrians generated around each player and shared with the others. Off by default.

KeyTypeDefaultRange / valuesDescription
PopulationboolfalseTurns synchronized ambient population on. The dimension policy also applies.
PopulationVehiclesbooltrueMoving traffic.
PopulationParkedbooltrueParked vehicles.
PopulationPedsbooltrueWalking pedestrians and animals.
PopulationScenariobooltrueScenario pedestrians (sitting, working…).
PopulationVehicleDensityfloat10..1Requested moving-vehicle density. Clients lower it to fit their budgets.
PopulationParkedDensityfloat10..1Requested parked-vehicle density.
PopulationPedDensityfloat10..1Requested pedestrian density.
PopulationScenarioDensityfloat10..1Requested scenario density.
PopulationBudgetPedsuint1400..1000Pedestrians a client keeps in total: players, scripts and population.
PopulationBudgetVehiclesuint1200..1000Vehicles a client keeps in total: scripts and population.
PopulationBudgetObjectsuint25000..60000Object count at which population thins out. 0 ignores objects.
PopulationMaxOwneduint960..1000Population entities simulated by one client. 0 = no limit.
PopulationReserveIdsuint6416..255IDs reserved per client to create population without waiting for the server.
PopulationRangeMetersfloat400250..800 mDistance at which players receive population generated by other players.
PopulationAreaVehiclesuint1200..1000Population vehicles within 160 m. Keep it at least at the client vehicle budget. 0 = no cap.
PopulationAreaPedsuint1600..1000Population pedestrians within 160 m. Keep it at least at the client pedestrian budget. 0 = no cap.
PopulationCreateRatePerSecuint601..1000 /sPopulation creations per second per player.
PopulationCrowdStartuint80..4095 playersNearby players at which population starts thinning out.
PopulationCrowdEnduint320..4096 playersNearby players at which population reaches zero. Must be above PopulationCrowdStart (both defaults are used otherwise); 0 turns thinning off.

Discord

What players' Discord profiles show while they play on your server. Players can always turn it off. Scripts can change it with the Discord API.

KeyTypeDefaultRange / valuesDescription
DiscordPresencebooltrueShow this server in the player's Discord profile.
DiscordJoinablebooltrueOffer a Join button. Players must also allow sharing the server address.
DiscordAppIdtextemptydecimal IDYour own Discord application, for your own branding. Needs the matching subscription.
DiscordLargeImagetextemptyasset key (32 bytes) or https:// URLLarge image.
DiscordLargeTexttextemptyup to 128 UTF-8 bytesTooltip of the large image.
DiscordSmallImagetextemptyasset key (32 bytes) or https:// URLSmall image.
DiscordSmallTexttextemptyup to 128 UTF-8 bytesTooltip of the small image.
DiscordButtonLabeltextemptyup to 32 UTF-8 bytesLabel of a link button, shown when there is no Join button.
DiscordButtonUrltextemptyhttps:// URL, up to 512 bytesTarget of that button.
DiscordLinkHostslistempty8 domains at mostDomains (subdomains included) your scripts may use for Discord buttons and images, such as discord.gg.

Scripts and sandbox

Server resources run in a sandbox by default: they reach their own data folder and what you allow here, nothing else. A single resource is trusted with "sandbox": false in resources.json. Details in Capabilities and sandbox.

KeyTypeDefaultRange / valuesDescription
LuaMemoryLimitMiBuint2560..1048576 MiBMemory quota of each Lua resource. 0 = no quota. Applies when a resource starts.
JsHeapLimitMiBuint00..1048576 MiBJavaScript heap shared by all server JS resources. 0 = sized from the machine's memory.
SandboxbooltrueSandbox for server resources, Lua and JavaScript. false trusts every resource with full machine access.
SandboxAuditboolfalseLog restricted operations instead of refusing them. For diagnosis only.
SandboxWatchdogSecuint100..3600 sSeconds a Lua or JavaScript script may run without suspending before it is interrupted. 0 turns the watchdog off. Trusted (unsandboxed) resources only get a warning.
SandboxFsReadlistemptyfoldersExtra folders sandboxed resources may read, absolute or relative to the server. Write paths as they are, without escaping backslashes.
SandboxFsWritelistemptyfoldersExtra folders they may read and write. Their own data folder is always allowed.
SandboxNetConnectlist*rulesOutgoing connections they may open. * allows everything, an empty list nothing. An invalid list allows nothing.
SandboxNetListenlistemptyIP:port, port, CIDR, unix:/path, pipe:nameSockets they may listen on. Empty allows none.
SandboxEnvlistNODE_ENV, TZ, LANG, LC_ALLnames; a trailing * matches a prefixEnvironment variables they can see. Empty hides all.

Resource lifecycle and console

KeyTypeDefaultRange / valuesDescription
ResourceStartTimeoutMsuint300001000..600000 msLongest wait for the top-level awaits of a starting resource. Past it, the resource is marked failed.
ResourceStopGraceMsuint20000..30000 msTime given to the resourceStop handlers of a stopping resource.
ShutdownGraceMsuint50000..60000 msTime given to resources at shutdown (serverStop handlers, pending MySQL queries) before they are stopped anyway.
PreConnectionTimeoutMsuint100001000..19000 msDeadline of the playerPreConnection verdict. A handler that answers later refuses the player.
ConsoleStdinbooltrueRead console commands from the terminal. Set false under a service manager that closes the input.

Admin panel

KeyTypeDefaultRange / valuesDescription
AdminLsmpIdslistemptydecimal LS:MP IDsWho may sign in to /lsadmin with Continue with LS:MP, besides the server's owner. Read at each sign-in.
AdminPublicUrltextemptyhttp(s):// originAddress of the panel behind a domain name or a reverse proxy (https://admin.example.com). Empty accepts only this server's IP, loopback and private networks.

Old key names and automatic migration

Several keys were renamed so that every unit is in the name (…Ms, …Sec, …MiB, …Meters, …Hz, …PerSec). When the server starts with a file that still uses old names, it updates the file by itself:

  1. It keeps a copy

    The original file is saved next to it as server.cfg.bak.

  2. It rewrites the file

    Each old key line gets its new name and keeps its value. ClientIdleTimeoutMs is converted to seconds (rounded up), and RoutingBucketLockdown becomes off (0) or strict (1, 2). The comment the server had written above the key is replaced by the new one; your own comments, the other lines and their order stay as they are.

  3. It says so

    One line in the log lists the renamed keys, never their values: [server.cfg] migrated to the v2 key names (PlayPort -> GamePort, Port -> HttpPort); the previous file is kept as …. If the file cannot be written, the old values still apply for this start, with an error asking you to rename the keys by hand.

Old keyKey now
PlayPortGamePort
PortHttpPort
SemiP2P, SemiP2PMaxPeers, SemiP2PRangeP2P, P2PMaxPeers, P2PRangeMeters
MaxSyncRateMaxSyncRateHz
LuaMemoryLimitMbLuaMemoryLimitMiB
ScriptHeapLimitMbJsHeapLimitMiB
ClientIdleTimeout, ClientIdleTimeoutMsClientIdleTimeoutSec
RoutingBucket, RoutingBucketPopulation, RoutingBucketLockdown, DefaultDimensionLockdownDefaultDimension, DefaultDimensionPopulation, DefaultDimensionClientEntities
PickupLifetimePickupLifetimeSec
PopulationRange, PopulationCreateRatePopulationRangeMeters, PopulationCreateRatePerSec
SandboxWatchdogSandboxWatchdogSec
UnsandboxedResources"sandbox": false per resource in resources.json, copied there when that file is first created.

These keys are gone and only produce a warning: TrustDeclaredIdentity, LuaBytecode, VoiceEnabled and VoiceRange (voice is set up by scripts, see Voice), RequiresDiscord, RequiresSteam, LsmpApiBase, LsmpLinkBase, LsmpLinkRealm, LsmpMarketBase, UpdateBaseUrl.

Run a server

Console and admin panel

Run the server day to day: the console commands that show and moderate it, and the admin panel that monitors, moderates and reconfigures it from a web browser.

The console

You type commands in two places, and both behave the same way:

- the terminal the server runs in (turn it off with ConsoleStdin=false under a service manager, see server.cfg);
- the Console tab of the admin panel.

A command name is not case-sensitive, and a leading / is accepted (/status works). A line is at most 512 bytes. The server first looks for a built-in command, then for a command registered by a resource with lsmp.registerCommand, and otherwise answers unknown command: … ('help' lists the commands).

Built-in commands

CommandWhat it does
help [command]Lists the built-in commands, or explains one.
statusServer version, uptime, ports, players connected / maximum, resources counted by state, and the memory of the server process (Lua and JS hosts included).
playersConnected players: player ID, name, LS:MP ID (or guest), dimension, ping (- until measured), time connected.
resourcesEvery resource: name, state, origin (local folder or marketplace mod), sandboxed or not, client mount. Resources start with the server and run until it stops: to apply a change to a resource, restart the server.
kick <playerId> [reason…]Kicks a player, with an optional reason shown to them.
say <text…>Sends a message to every player. A client resource can handle it with the serverMessage event; otherwise LS:MP shows it to the player.
quit [reason…]Shuts the server down cleanly: new connections are refused, players leave with the reason "shutdown" and are disconnected, resources get ShutdownGraceMs for their serverStop handlers, then stop, and their data is written. A second quit during the shutdown is ignored.
textserver console
> status
LS:MP server 0.6.254, up 2h 14m
ports: game 9530, http 2086
players: 3/64
resources: 12 started, 1 failed
memory: 412 MiB (server process, Lua and JS hosts included)
> resources
chat                              started   local  sandboxed    client auto
shop                              failed    local  sandboxed    client auto
2 resource(s)
  • There is no start, stop, restart or refresh: resources start with the server and run until it stops. Typed anyway, they print unknown command: restart (resources start with the server and run until it stops: restart the server to apply a change).
  • A resource cannot register a command with the name of a built-in command: registerCommand raises.

Your own commands

A command registered by a server script runs from the terminal and the admin panel with every right, whatever permission it requires from players. Players only reach it through lsmp.executeCommand, and only with that permission. See Console commands.

luaLua
-- server/main.lua: a console command that lists who is online.
lsmp.registerCommand("who", { help = "lists who is online" }, function(args, raw, source)
  local names = {}
  for _, id in ipairs(lsmp.getPlayers()) do
    names[#names + 1] = lsmp.getPlayerName(id)
  end
  lsmp.log(#names .. " online: " .. table.concat(names, ", "))
end)
jsJavaScript
// server/main.js: a console command that lists who is online.
lsmp.registerCommand('who', { help: 'lists who is online' }, () => {
  const names = lsmp.getPlayers().map((id) => lsmp.getPlayerName(id));
  lsmp.log(`${names.length} online: ${names.join(', ')}`);
});

The admin panel

Every server serves a web admin panel at /lsadmin on its HTTP port: http://<server-ip>:2086/lsadmin. Nothing to install; keep the uiadmin/ folder that ships with the server next to the program. The root of that port serves what players download, so / answers 404.

  1. Sign in

    Continue with LS:MP signs in the server's owner and the LS:MP IDs listed in AdminLsmpIds. A local account uses a user name and a password. On a new server, the panel shows the setup first.

  2. Work in the tabs

    Monitor, moderate and reconfigure without touching the shell: see the table below.

  3. Restart when the panel asks

    Settings written by the panel apply at the next start. While the files on disk differ from what runs, a banner at the top says so and lists the differences; putting a setting back clears it.

TabWhat it does
OverviewLive CPU, memory and network of the server. The version in the sidebar checks for updates.
PlayersConnected players, with kick and ban (by LS:MP account, address or machine). The Bans list lifts bans; the Whitelist card turns the whitelist on and edits it. Changes apply at once.
BenefitsThe in-game benefits sold for this server, and their deliveries.
NetworkHow full the network ID space is, and a list of network entities.
StatisticsHistory charts, sampled every minute, from the last hour to two years.
P2P MapWith P2P on: which players exchange their updates directly.
ResourcesEvery resource with three switches: On/Off, Auto-mount (players mount it as they join, or a client script starts it) and Sandbox. They write resources.json and apply at the next start. Permissions opens the capabilities of a resource, which apply at once. Also lists the marketplace mods of your account for this server.
ConsoleThe live log, with severity filters, a History mode for earlier sessions, and a command box that runs the console commands.
PermissionsGroups, members, online players, checks and the journal: see Permissions. Every change applies at once.
SettingsA form for server.cfg, grouped in cards, with a search box and a Raw file view. A field left empty shows the default. Old key names are read and saved under their new names. The Game configuration card uploads a custom gameconfig.xml (below).
AdministrationWho may sign in: AdminLsmpIds and the local accounts.
Restart / ShutdownRestart the server in place, or stop it cleanly.
βœ•
Secure the panel first

The panel shares the HTTP port with what players download, so that port stays reachable, and it speaks plain HTTP. Use LS:MP sign-in only, or a strong password. To use the panel from outside, put it behind a reverse proxy with TLS and set AdminPublicUrl. Repeated failed logins lock the address out for a while, longer at each repeat.

ProblemFix
Lost access to the panelStop the server and delete admin-users.json: the default admin / admin account comes back at the next start, and must get a new password before anything else.
The server refused the connection at sign-inToo many failed logins from your address: wait, then try again.
A switch of the Resources tab did nothingIt applies at the next server start: restart the server.

A custom game configuration

Every player runs the game with the gameconfig.xml that ships with LS:MP, which sizes the engine pools (peds, vehicles, objects…). A server that needs other sizes can ship its own: upload it in the Game configuration card of Settings, or drop it as resources/gameconfig.xml. There is one at most.

  • At start, the server checks the file and announces it to players. A file that fails the check is not used, the console says why, and players keep the LS:MP configuration.
  • When a player joins, LS:MP asks them to restart the game with your file, then joins your server again by itself. The file stays in their cache.
  • When they leave, LS:MP offers to restart with its own configuration.
  • Replacing or removing the file applies at the next server start.
⚠
Test it before you ship it

Only the shape of the file is checked: UTF-8 XML, 2 MiB at most, a <fwAllConfigs> root. Its values are yours, and a pool raised beyond what the engine can hold closes the game of every player. Start from the gameconfig.xml of your LS:MP folder, change one value at a time, and join your own server before you open it.

Run a server

Go public (ports, firewall, token)

Make your server reachable from the Internet and listed in the LS:MP server browser: ports, firewall, router, token and public listing.

A server needs two ports open to the Internet. Players only ever type the HTTP address (ip:2086); their game learns the game port from it.

KeyDefaultProtocolCarries
HttpPort2086TCPThe address players join, resource downloads, the admin panel, your resources' HTTP routes.
GamePort9530TCP and UDPThe game session: movement, events, voice.
  1. Open the firewall

    On the machine itself. A VPS may also have a firewall in its provider's panel: open the same ports there.

    bashWindows, in an administrator terminal
    netsh advfirewall firewall add rule name="LS:MP HTTP" dir=in action=allow protocol=TCP localport=2086
    netsh advfirewall firewall add rule name="LS:MP game TCP" dir=in action=allow protocol=TCP localport=9530
    netsh advfirewall firewall add rule name="LS:MP game UDP" dir=in action=allow protocol=UDP localport=9530
    bashLinux, with ufw
    sudo ufw allow 2086/tcp
    sudo ufw allow 9530/tcp
    sudo ufw allow 9530/udp
    bashLinux, with firewalld (RHEL, Rocky, Alma, Fedora)
    sudo firewall-cmd --permanent --add-port=2086/tcp --add-port=9530/tcp --add-port=9530/udp
    sudo firewall-cmd --reload
  2. Forward the ports (home connection)

    Behind a home router, forward 2086 TCP and 9530 TCP and UDP to this machine's local address. If the address players should use is not the one the server sees (NAT, reverse proxy), set PublicAddress=<public-ip>:2086 in server.cfg.

  3. Link the server to your LS:MP account

    If you skipped this step of the setup page, add a server in My Servers and copy its token into Settings of the admin panel, or as Token= in server.cfg, then restart. The token identifies your server on the LS:MP network: keep it secret, never commit it to a repository.

  4. Turn the listing on

    Switch Public listing on in Settings: on a linked, running server it applies at once. Setting PublicList=true by hand applies at the next start. Without it, the server runs fine and players reach it by address.

  5. Check from outside

    Join by address from another network (a phone's connection works), then look for your server in the browser. In My Servers, set its icon, banner and loading cover.

When players cannot join

SymptomCause and fix
Nobody can reach the serverHttpPort is closed from outside, or players use the game port. Test http://<public-ip>:2086/lsadmin from another network.
Players connect, then nothing movesGamePort is open in TCP but not in UDP.
Friends on the Internet are refused, players on the LAN are fineBehind NAT the server does not know its public address: set PublicAddress.
The server is not in the browserPublicList=true needs a valid Token the server started with. Look for Token or listing errors in the log.
MaxPlayers is lower than setIt is capped by the plan of the server's owner.
β„Ή
Before you open the doors

Give yourself the admin rights (Permissions), secure the admin panel, and check RequireAdmission is on: it is the default.

Run a server

Updates

How the server updates itself, what it never touches, and how it comes back to the previous version when a new one does not start.

  1. It checks

    The server looks for a new version about once an hour, when you open the admin panel, and when you click the version in the panel's sidebar. It follows the release channel set by UpdateChannel (stable).

  2. It prepares

    A new version is downloaded and verified in the background, then tried on this machine. A version that cannot run here is never installed, and nothing changes.

  3. It installs

    With AutoUpdate=true (the default), the server installs the prepared version once no player has been connected for 5 minutes. Otherwise, click the version in the panel's sidebar. New players are refused during the swap, then the server restarts in place: on Linux it keeps its process ID, so systemd, Docker or screen keep following it.

  4. It checks itself

    The new version must run for 60 seconds after opening its ports. If it crashes in that window, or fails to start three times, the previous version is put back and started, and that build is never installed automatically again.

β„Ή
Never touched by an update

server.cfg, resources.json, the panel accounts, bans, permissions, your resources, their data and key/value stores, and the logs. An update replaces only the files of the server release.

Choose when it happens

You wantDo this
Updates whenever the server is emptyNothing: AutoUpdate=true is the default.
To pick the moment yourselfSet AutoUpdate=false (in Settings it applies at once), then click the version in the panel's sidebar when you are ready.
A test channel LS:MP gave youSet UpdateChannel to its name, and restart.

After an update

  • The first start of a new version may rebuild the packages of your resources: players download what changed.
  • Players need an up-to-date LS:MP client: it updates itself when they start it.
  • Read the log of the first start. A key of server.cfg that changed name is migrated by itself; anything the server cannot use is reported with its line.

Build resources

Build resources

Resource layout and manifest

What a resource folder holds, how it is named, and every key of its manifest.json: scripts, files, web pages, game data, asset sets and dependencies.

A resource is a folder in the server's resources/ with a manifest.json that says which file runs where. The same folder works on a server, as a local resource in Story mode, and as a marketplace mod.

A typical resource

Lua only:

resources/
└─ shop/                    # the folder name is the resource's name
   β”œβ”€ manifest.json         # what runs where (below)
   β”œβ”€ shared/
   β”‚  └─ config.lua         # shared_scripts: runs on both sides, first
   β”œβ”€ server/
   β”‚  └─ main.lua           # server_scripts: never sent to players
   β”œβ”€ client/
   β”‚  └─ main.lua           # client_scripts: sent to players, runs in their game
   β”œβ”€ web/                  # webui: served to your pages at rsc://shop/
   β”‚  β”œβ”€ index.html
   β”‚  └─ app.js
   β”œβ”€ data/
   β”‚  └─ items.json         # files: sent to players, read by scripts
   └─ stream/               # game assets (.ydr, .ytd, .ymap…), always streamed
      └─ shop_counter.ydr

JavaScript only:

resources/
└─ shop/                    # the folder name is the resource's name
   β”œβ”€ manifest.json         # what runs where (below)
   β”œβ”€ shared/
   β”‚  └─ config.js          # shared_scripts: runs on both sides, first
   β”œβ”€ server/
   β”‚  └─ main.js            # server_scripts: never sent to players
   β”œβ”€ client/
   β”‚  └─ main.js            # client_scripts: sent to players, runs in their game
   β”œβ”€ web/                  # webui: served to your pages at rsc://shop/
   β”‚  β”œβ”€ index.html
   β”‚  └─ app.js
   β”œβ”€ data/
   β”‚  └─ items.json         # files: sent to players, read by scripts
   └─ stream/               # game assets (.ydr, .ytd, .ymap…), always streamed
      └─ shop_counter.ydr

Lua only:

jsonmanifest.json
{
  "title": "Shop",
  "description": "A counter where players buy items.",
  "author": "Jane",
  "version": "1.2.0",
  "shared_scripts": "shared/config.lua",
  "server_scripts": "server/*.lua",
  "client_scripts": ["client/main.lua"],
  "files": "data/*.json",
  "webui": "web",
  "dependencies": "bank"
}

JavaScript only:

jsonmanifest.json
{
  "title": "Shop",
  "description": "A counter where players buy items.",
  "author": "Jane",
  "version": "1.2.0",
  "shared_scripts": "shared/config.js",
  "server_scripts": "server/*.js",
  "client_scripts": ["client/main.js"],
  "files": "data/*.json",
  "webui": "web",
  "dependencies": "bank"
}

Folder names such as server/ or web/ are conventions: only the manifest decides. Every list accepts a single string or an array of strings.

The name of a resource

The folder name is the resource's name, and its only identity: for lsmp.getResourceName(), dependencies, rsc://shop/ pages, /res/shop/ HTTP routes, the [shop] prefix of its log lines, the resources console command, and the storage that belongs to it (data folder, storage, capabilities).

  • 1 to 64 characters: lowercase letters a-z, digits, _ and -, starting with a letter or a digit.
  • lsmp, and names starting with lsmp- or lsmp_, are reserved.
  • A folder with another name is not loaded, and the log gives the name to use: resource folder 'MyShop' is not a valid name (…): use 'myshop'.
  • title in the manifest is only a display name (admin panel, marketplace). Renaming the folder changes the identity, and with it the storage the resource finds.

Manifest keys

KeyTypeDefaultWhat it does
titlestringthe resource nameDisplay name, up to 64 characters. Never an identity.
descriptionstring""Display only, up to 1024 characters.
authorstring""Display only, up to 128 characters.
versionstring""Display only, up to 64 characters. Marketplace versions are managed by lsmp.gg.
shared_scriptsstring \| string[][]Scripts run on both sides, before the side-specific ones.
server_scriptsstring \| string[][]Scripts run on the server: .lua, .js, .mjs, .cjs. Never sent to players.
client_scriptsstring \| string[][]Scripts run in each player's game: .lua or .js, in this order.
filesstring \| string[][]Extra files sent to players, not run: data read with lsmp.readResourceFile, modules loaded with require.
webuistring \| string[][]Folders served to the resource's pages at rsc://<name>/ (below).
dependenciesstring \| string[][]Resources that must be started first, on both sides.
server_dependenciesstring \| string[][]Same, on the server only.
client_dependenciesstring \| string[][]Same, in the player's game only.
data_filesarray[]Game data files mounted in the player's game with the resource: "data/vehicles.meta", or { "path", "type", "set", "language" } (below).
stream_setsarray[]Parts of stream/ that scripts load and unload in game: { "name", "folder", "load" } (below).

Paths and patterns

  • Paths are relative to the resource folder, with /. A path that leads outside the folder (absolute, ..) is refused, and so is a link whose target is outside it.
  • Patterns: * matches within one folder level, ** any depth, ? one character. "client/*.lua", "web/**".
  • node_modules, .git, .svn and .hg folders are never sent to players. The server keeps the node_modules at the root and under server/.

Scripts and their order

  • On each side, shared_scripts run first, then the side's own scripts, each list in manifest order.
  • A resource starts once its dependencies on that side are started. It is started when every file has run to its end, or to its first wait (lsmp.wait, a pending call). A file that raises makes the whole resource failed.
  • On the server, a resource may mix .lua and .js files. They run in two separate script environments (no shared globals) of one resource: same name, same state, same storage. JavaScript files run before Lua files. The two halves talk with lsmp.emit and lsmp.call.
  • Client scripts can be .lua or .js too, in one resource. Choosing one language per side keeps things simple: see Runtimes.

Web pages (webui)

Each webui folder is served at the root of rsc://<resource name>/: with "webui": "web", the file web/index.html is rsc://shop/index.html, and web/js/app.js is rsc://shop/js/app.js. Open the page with lsmp.createBrowser. Put the built output of a web project here (dist/), not its sources. See Web interfaces.

Game data files

data_files mounts game metadata in the player's game, the way the game mounts a DLC. A bare path works for the usual file names, whose type is known: vehicles.meta, handling.meta, carvariations.meta, carcols.meta, vehiclelayouts.meta, weapons.meta, peds.meta, water.xml, dlctext.meta and more. Give the type for any other name.

jsonmanifest.json
{
  "title": "Sports car pack",
  "data_files": [
    "data/vehicles.meta",
    "data/handling.meta",
    { "path": "data/my_cars_colors.meta", "type": "CARCOLS_FILE" },
    { "path": "lang/french.gxt2", "language": "french" },
    { "path": "data/island_water.xml", "set": "island" }
  ]
}
FieldMeaning
pathThe file, relative to the resource. Required.
typeThe game's data file type (VEHICLE_METADATA_FILE, CARCOLS_FILE…). Deduced from the file name when absent.
setName of a stream set: the file is mounted and unmounted with that set instead of the resource.
languageFor a text file (.gxt2): the game language it is for (american, french…). Only the one matching the player's language is mounted.

Stream sets

Everything in stream/ is streamed while the resource is mounted. A stream set cuts a sub-folder of stream/ out of that block, so that a client script loads and unloads it in game: an interior, a seasonal map. Files in no set are always streamed. How to load them: Assets and streaming.

jsonmanifest.json
{
  "title": "My island",
  "client_scripts": "client/main.lua",
  "stream_sets": [
    { "name": "club", "folder": "stream/night_club", "load": "manual" },
    { "name": "winter", "folder": "stream/winter" }
  ]
}
FieldTypeDefaultMeaning
namestringrequiredThe set's name for scripts: 1 to 64 characters among a-z, 0-9, _ and -, unique in the resource.
folderstringrequiredFolder relative to the resource root, like every path of the manifest, and inside stream/: "stream/night_club"; "stream" is the whole stream/.
loadstring"auto""auto": loaded with the resource. "manual": loaded only when a script asks (loadStreamSet).
  • Nested sets: a file belongs to the set of its closest folder. Declaring stream/map and stream/map/night cuts night out of map.
  • A resource holds at most 256 sets. A name declared twice keeps the first.

Dependencies

  • By exact resource name. dependencies apply to both sides; server_dependencies and client_dependencies to one side only, so the player's game never waits for a server-only resource.
  • A dependency that is missing, disabled in resources.json or failed keeps the resource from starting: it is failed, with a message such as dependency 'db' of 'bank' is missing (did you mean 'mysql-db'?).
  • A cycle fails every resource in it, and the log prints the cycle.
  • Stopping a resource stops the resources that depend on it first.
  • The server's operator can add load-order constraints of their own with after in resources.json.

Mistakes and warnings

In manifest.jsonWhat happens
Invalid JSONThe resource does not start: resource 'shop': manifest.json is not valid JSON (line 7, column 3), not loaded.
Unknown keyWarning, key ignored: 'client_script' is not a manifest key, ignored (did you mean 'client_scripts'?).
Key of the wrong typeWarning, key ignored: 'dependencies' must be a string or an array of strings, ignored.
Key that no longer existsWarning, key ignored, with what to use (table below).
No manifest.jsonOnly stream/ is used (a pure asset resource, such as a map). A client/, server/ or shared/ folder is ignored, with a warning.
A file larger than 16 MiB, or nested too deeplyThe resource does not start.
KeyUse instead
nameNothing: the identity is the folder name. Use title for a display name.
enabled"enabled" in the server's resources.json.
client_script, server_script, shared_scriptclient_scripts, server_scripts, shared_scripts.
dependencydependencies (a string is accepted).
scriptsList scripts in client_scripts, server_scripts or shared_scripts.
webui_dirs, webui_domainwebui. Pages are always served at rsc://<resource name>/.
files_mountdata_files.
stream-setsstream_sets.

What players receive

At start, the server packs each resource twice:

- the client package, downloaded by players: shared_scripts, client_scripts, files, webui folders, data_files and stream/, nothing else. Lua scripts are checked: one with a syntax error stops the package, with the file and the line in the log.
- the server package, for the server only: the folder without stream/, the webui folders and the client-only data.

server_scripts are never sent to players. Anything a player must not read (keys, passwords) belongs on the server side (Storing data), never in files, webui or client scripts.

Build resources

Operator settings (resources.json)

One file, next to server.cfg, for everything the server's operator decides about each resource: whether it runs, whether it is sandboxed, how players mount it, and extra load order.

A resource's manifest.json belongs to its author. What the operator of a server decides lives in resources.json, at the root of the server folder, never inside a resource folder: updating a resource never overwrites your choices. The Resources tab of the admin panel writes this file; you can also edit it by hand.

jsonresources.json
{
  "resources": {
    "bank": { "enabled": true, "sandbox": false, "clientMount": "auto" },
    "admin-tools": { "clientMount": "manual" },
    "old-hud": { "enabled": false },
    "shop": { "after": ["bank"] },
    "mod.las-venturas": { "enabled": true }
  }
}
  • Each entry is keyed by the resource name. A marketplace mod is keyed mod.<name>, so that a mod and a local folder of the same name never share settings.
  • A resource that is not in the file uses every default. Write only what you change.
  • The file is created at the first start, with the resources whose settings differ from the defaults.

Fields

FieldTypeDefaultMeaning
enabledbooleantruefalse: the resource is not packed, not started, and not sent to players.
sandboxbooleantruefalse trusts the resource: its server scripts get full machine access and lsmp.mysql. Only for code you trust. See Capabilities and sandbox.
clientMountstring"auto""auto": players mount it as they join. "manual": players download it, and a client script mounts it with lsmp.mountResource. "never": it is not sent to players at all (its server part still runs).
afterstring[][]Resources to start before this one, on top of its own dependencies. A soft rule: a name that does not exist only gives a warning.

When changes apply

You changeIt applies
Any field, from the admin panelAt the next server start. The panel shows a banner until then.
The file, by handAt the next server start: resources and their settings are read once, when the server starts.

Mistakes

ProblemWhat happens
Unknown fieldresources.json: 'shop': unknown setting "autoMount", ignored.
Wrong typeresources.json: 'shop': "enabled" must be true or false, default kept.
Invalid clientMount… "clientMount" must be "auto", "manual" or "never", default kept.
The file is not valid JSONEvery resource uses the defaults, and the file is left as it is so that you can fix it.
β„Ή
What is not here

Server-wide settings live in server.cfg. What each resource may do (capabilities) is granted in the Permissions of its row in the admin panel: see Capabilities and sandbox.

Build resources

Lua and JavaScript runtimes (timers, threads, modules, npm, sandbox)

What the Lua and JavaScript engines provide on the server and on the client: isolation, threads, timers, modules and npm, budgets.

A resource is written in Lua, in JavaScript, or in both. Both languages see the same lsmp API with the same names, arguments and results; the few deliberate differences are listed in Conventions.

LuaJavaScript
ServerLua 5.5Node.js 24: CommonJS and ES modules, Node core modules, npm packages
ClientLua 5.5V8, without Node: plain scripts, no Node modules
Isolationone Lua state per resourceone context per resource

One resource, its own world

  • Each resource has its own globals: a resource that overwrites a global, or even lsmp.emit, only breaks itself.
  • Resources talk through events, remote calls and meta. Values are copied between resources, never shared.
  • Everything a resource registered (handlers, timers, commands, threads, browsers, pools...) is cleaned up when it stops. See Isolation and restore.
  • Errors are contained: an error in a handler, a timer or a thread is logged with the resource name and file position, and the rest of the resource keeps running.

Mixed Lua and JavaScript resources

A server resource may list both .lua and .js scripts in its manifest. They form one resource (same name, same state, same storage, same data folder) running in two engines with separate globals. The JavaScript scripts start first. The two halves talk with lsmp.emit (delivered to the other engine a moment later) and lsmp.call (a local call).

Lua

  • Lua 5.5, with 64-bit integers: math.type(x) tells "integer" from "float", and the API keeps them apart (3 and 3.0 are different values). Use // for integer division.
  • Vector3 is a built-in value type of the engine, with fields .x, .y and .z (32-bit floats). Functions accept a plain {x, y, z} table as well.
  • print is lsmp.log.
  • The standard library functions that reach outside the resource (io, os.execute, load, debug...) raise an error that names the lsmp alternative (lsmp.fs, lsmp.readResourceFile). debug.traceback works.

Threads and waiting

Lua code waits with coroutines. The host runs the body of each script file, every event and RPC handler, and every lsmp.createThread function in a host coroutine: inside, lsmp.wait and asynchronous functions without a callback suspend only that coroutine. A coroutine you create yourself with coroutine.create is not a host coroutine.

luaLua
lsmp.createThread(function()
  while true do
    local count = #lsmp.getPlayers()
    lsmp.setGlobalMeta("online", count)
    lsmp.wait(5000)
  end
end)

Modules

On the server, require(name) loads another Lua file of the same resource, from its package: require("lib.util") loads lib/util.lua, or lib/util/init.lua. Like standard Lua, a module runs once per resource and its return value is cached (true when it returns nothing). Names use letters, digits, _, - and .; there are no native (C) modules.

lualib/money.lua
local M = {}
function M.format(n) return ("$%d"):format(n) end
return M
luaserver/main.lua
local money = require("lib.money")
lsmp.log(money.format(1500))

JavaScript

  • console.log, info, warn, error and debug go to the resource's log (see Logging).
  • Asynchronous lsmp functions return Promises: use async/await. An async function is the JavaScript equivalent of a Lua thread.
  • Timers are the standard setTimeout/setInterval/clearTimeout/clearInterval. On the server they are Node timers (Timeout objects); on the client their ids are integers.
  • An uncaught exception or an unhandled Promise rejection is logged; it never stops the resource or the server.
  • Integers beyond 2^53 travel as BigInt.

Server: Node.js modules and npm

  • Each resource has its own module system, rooted in its package. CommonJS (require) and ES modules (import, .mjs, or "type": "module" in a package.json) both work, with Node's rules.
  • require and import look in the resource first, including a node_modules folder shipped inside the resource; then in Node's core modules and in npm packages installed next to the server.
  • __filename and __dirname are paths inside the resource (/<resource>/server/main.js), not disk paths: read your own files with lsmp.readResourceFile, and write files in lsmp.getDataPath().
  • The process belongs to the server: process.exit() and process.abort() raise. In the sandbox, child processes, native addons and internal bindings are refused, and os.tmpdir() is inside the resource's data folder.
  • An ES module may use top-level await: the resource reaches "started" when it settles (at most ResourceStartTimeoutMs).
js
// server/main.mjs
import { createHash } from "node:crypto";

const digest = createHash("sha256").update("hello").digest("hex");
lsmp.log(digest);

const config = JSON.parse(lsmp.readResourceFile("config.json"));
lsmp.log(`loaded ${Object.keys(config).length} settings`);

Client

Client JavaScript runs on V8 without Node: there is no Node core module and no npm. require loads the files of the same resource as CommonJS modules: ./ is relative to the calling file, a bare name starts at the resource root, .js, .json and folder/index.js are tried, and each module runs once (cached; cycles work). A required file must reach the client: list it in the manifest's client_scripts, shared_scripts or files. ES modules (import) are server only. Each client resource has a memory budget of 256 MiB. Use the lsmp API and the game natives.

Budgets

  • Time: a script must not block. On the server, Lua or JavaScript that runs longer than SandboxWatchdogSec (default 10 s) without suspending is interrupted in the sandbox (script interrupted: time budget exceeded); outside the sandbox it is only logged. On the client, one run is interrupted after 250 ms, and each resource gets 100 ms of script time per frame in total: a resource that keeps going over is stopped (see Limits). Split long work with lsmp.wait/await lsmp.wait(0).
  • Memory: each server Lua resource has a quota (LuaMemoryLimitMiB, default 256 MiB); server JavaScript resources share the heap set by JsHeapLimitMiB.
  • Budgets are counted per resource: a resource is never cut for the time or memory another resource used. See Limits and quotas.
Build resources

Events and RPC (guide)

Patterns for talking between the server, the clients and your resources, and the mistakes to avoid.

This guide shows how the server, the clients and your resources talk to each other. The reference pages are Events, Remote calls and Engine events.

Choosing a tool

NeedToolWhy
React to the game or the serverlsmp.on("playerJoin", ...)Engine events, same names on both sides.
Fire and forget, one sidelsmp.emit / lsmp.onSynchronous for handlers in the same language, cheap.
Fire and forget, across the networklsmp.emitServer β†’ lsmp.onClient, lsmp.emitClient β†’ lsmp.onServerOrdered, no answer.
Ask and wait for an answerlsmp.callServer, lsmp.callClient, lsmp.call β†’ lsmp.onCallOne result or one error code, with a deadline.
Share a state everyone readsMetaReplicated, late joiners see it, metaChange notifies.

A request from a client

  1. The client sends

    The client sends what the player asked for, nothing more. It never decides prices, damage or rights.

    luaLua
    -- client
    lsmp.emitServer("shop:buy", "pistol")
    jsJavaScript
    // client
    lsmp.emitServer("shop:buy", "pistol");
  2. The server checks everything

    On the server, the first argument of an onClient handler is the sending player: it cannot be forged. Every other argument comes from the client and must be checked.

    luaLua
    -- server
    local PRICES = { pistol = 500, smg = 2500 }
    
    lsmp.onClient("shop:buy", function(source, item)
      local price = type(item) == "string" and PRICES[item]
      if not price then return end
      local money = lsmp.getPlayerMeta(source, "money") or 0
      if money < price then
        return lsmp.emitClient(source, "shop:result", false, "not enough money")
      end
      lsmp.setPlayerMeta(source, "money", money - price)
      lsmp.emitClient(source, "shop:result", true, item)
    end)
    jsJavaScript
    // server
    const PRICES = { pistol: 500, smg: 2500 };
    
    lsmp.onClient("shop:buy", (source, item) => {
      const price = typeof item === "string" ? PRICES[item] : undefined;
      if (price === undefined) return;
      const money = lsmp.getPlayerMeta(source, "money") ?? 0;
      if (money < price) return lsmp.emitClient(source, "shop:result", false, "not enough money");
      lsmp.setPlayerMeta(source, "money", money - price);
      lsmp.emitClient(source, "shop:result", true, item);
    });
  3. Or use a remote call

    When the client needs the answer, a remote call is simpler than two events: the result comes back to the caller, with a deadline and an error code when something goes wrong.

    luaLua
    -- server
    lsmp.onCall("shop:buy", function(source, item)
      local price = type(item) == "string" and PRICES[item]
      if not price then return { ok = false, reason = "unknown item" } end
      -- ... same checks as above ...
      return { ok = true }
    end)
    
    -- client, in an event handler or a thread
    local res, err = lsmp.callServer("shop:buy", "pistol")
    if not res then lsmp.warn("shop unavailable: " .. err) end
    jsJavaScript
    // server
    lsmp.onCall("shop:buy", (source, item) => {
      const price = typeof item === "string" ? PRICES[item] : undefined;
      if (price === undefined) return { ok: false, reason: "unknown item" };
      // ... same checks as above ...
      return { ok: true };
    });
    
    // client
    async function buy(item) {
      try {
        return await lsmp.callServer("shop:buy", item);
      } catch (e) {
        lsmp.warn(`shop unavailable: ${e.code}`);
        return null;
      }
    }

An API for other resources

A resource offers functions to other resources with lsmp.onCall on its side; others call them with lsmp.call, in Lua or JavaScript, without depending on its code. On the server, such local calls receive source = nil/null, which tells them apart from player calls.

luaLua
-- resource "bank" (server)
lsmp.onCall("bank:getBalance", function(source, account)
  if source ~= nil then return nil end -- server resources only
  return lsmp.storage.get("balance:" .. account) or 0
end)

-- another resource (server), in a host coroutine
local balance, err = lsmp.call("bank:getBalance", 4211)
jsJavaScript
// resource "bank" (server)
lsmp.onCall("bank:getBalance", (source, account) => {
  if (source !== null) return null; // server resources only
  return lsmp.storage.get(`balance:${account}`) ?? 0;
});

// another resource (server)
async function show(account) {
  const balance = await lsmp.call("bank:getBalance", account);
  lsmp.log(`balance: ${balance}`);
}
βœ“
Naming

Prefix your names with the resource or feature (bank:getBalance, race:start): names are global to the side, and only one resource can handle a callable name.

Broadcasting state

For a value that every client needs, including players who join later, prefer meta to a broadcast event: a late joiner receives the current meta values, but never past events.

luaLua
-- server
lsmp.setGlobalMeta("race:state", { phase = "countdown", startsAtMs = lsmp.nowMs() + 5000 })

-- client
lsmp.on("metaChange", function(scope, target, key, value)
  if value then showRaceState(value) end
end, { scope = "global", key = "race:state" })
jsJavaScript
// server
lsmp.setGlobalMeta("race:state", { phase: "countdown", startsAtMs: lsmp.nowMs() + 5000 });

// client
lsmp.on("metaChange", (scope, target, key, value) => {
  if (value) showRaceState(value);
}, { scope: "global", key: "race:state" });

Common mistakes

  • Trusting the client. Anything after source in a server onClient or onCall handler can be anything. Check types and ranges, and decide prices and rights on the server.
  • Emitting an engine event. lsmp.emit("playerJoin", ...) raises: engine event names are reserved. Use your own name.
  • Expecting a reply from emitServer. Network events have no answer. Use lsmp.callServer.
  • Sending before the other side listens. A network event that arrives before its handler is registered is lost. Clients should ask for the state when their resource starts (a lsmp.callServer), rather than wait for an event they may have missed.
  • Waiting in the wrong place (Lua). lsmp.wait and asynchronous calls without callback need a host coroutine (event handler, RPC handler, file body, lsmp.createThread).
  • Huge payloads. A client can send at most 4 MiB βˆ’ 1 KiB per event, and the server limits each player's traffic per second. Send what changed, not the whole state. See Limits.
  • Expecting identity across resources. Values are copied between resources: a table you emit is not the table another resource receives.
Build resources

Storing data (meta, storage, MySQL, files)

Where to keep data, and complete patterns to load and save player data.

Resources keep data in five places. Pick by who reads it and how long it must live.

StorageLivesWho reads itGood forReference
Metauntil the player leaves, the entity is deleted or the server stopsevery script, server and clientsstate players see: job, team, fuel, a door lockMeta
Storageon disk, foreverthe resource itself, on the serversettings, counters, small records per accountstorage
MySQLin your databaseanything that connects to it (website, other servers)large or relational data, data shared with a websiteMySQL
Fileson diskthe resource (data folder), the operatorlogs, exports, generated filesFiles
Resource filesshipped with the resource, read-onlythe resourceconfiguration, translations, templateslsmp.readResourceFile
  • Meta are not saved: they disappear with the player or the server. Combine them with storage or MySQL: load into meta when a player joins, save from meta when they leave.
  • Key saved player data on the account, lsmp.getPlayerLsmpId, never on the playerId (reused) or the name (chosen by the player). Guests have no account: decide what they may keep.
  • Storage, MySQL and files exist only on the server. A client gets data through events and calls or meta.
  • MySQL needs an unsandboxed resource (see Sandbox); storage and the data folder work everywhere.

Saving player data with storage

  1. Load on join

    Read the account's record and expose what clients need as meta.

    luaLua
    lsmp.on("playerJoin", function(playerId, name)
      local account = lsmp.getPlayerLsmpId(playerId)
      if not account then return end -- guest: nothing saved
      local data = lsmp.storage.get("player:" .. account) or { money = 1000, level = 1 }
      lsmp.setPlayerMeta(playerId, "money", data.money)
      lsmp.setPlayerMeta(playerId, "level", data.level)
    end)
    jsJavaScript
    lsmp.on("playerJoin", (playerId, name) => {
      const account = lsmp.getPlayerLsmpId(playerId);
      if (account === null) return; // guest: nothing saved
      const data = lsmp.storage.get(`player:${account}`) ?? { money: 1000, level: 1 };
      lsmp.setPlayerMeta(playerId, "money", data.money);
      lsmp.setPlayerMeta(playerId, "level", data.level);
    });
  2. Save on leave

    In playerLeave, the leaving player's account and meta are still readable.

    luaLua
    lsmp.on("playerLeave", function(playerId)
      local account = lsmp.getPlayerLsmpId(playerId)
      if not account then return end
      lsmp.storage.set("player:" .. account, {
        money = lsmp.getPlayerMeta(playerId, "money") or 0,
        level = lsmp.getPlayerMeta(playerId, "level") or 1,
      })
    end)
    jsJavaScript
    lsmp.on("playerLeave", (playerId) => {
      const account = lsmp.getPlayerLsmpId(playerId);
      if (account === null) return;
      lsmp.storage.set(`player:${account}`, {
        money: lsmp.getPlayerMeta(playerId, "money") ?? 0,
        level: lsmp.getPlayerMeta(playerId, "level") ?? 1,
      });
    });
  3. Flush when stopping

    Storage writes reach the disk within about 750 ms, and the server flushes on a clean shutdown. To be sure before the server stops, flush in resourceStop.

    luaLua
    lsmp.on("resourceStop", function(name)
      if name == lsmp.getResourceName() then lsmp.storage.flush() end
    end)
    jsJavaScript
    lsmp.on("resourceStop", async (name) => {
      if (name === lsmp.getResourceName()) await lsmp.storage.flush();
    });
⚠
Crashes

Nothing runs when the server crashes: playerLeave and serverStop are not fired. For valuable data (money from a purchase), save at the moment it changes, not only when the player leaves.

The same with MySQL

With a database, load asynchronously when the player joins. The handler can wait for the query: other players and events are not blocked.

  1. Create the pool once
    luaLua
    local db = lsmp.mysql.createPool({ user = "game", password = "secret", database = "lsmp" })
    jsJavaScript
    const db = lsmp.mysql.createPool({ user: "game", password: "secret", database: "lsmp" });
  2. Load and save
    luaLua
    lsmp.on("playerJoin", function(playerId)
      local account = lsmp.getPlayerLsmpId(playerId)
      if not account then return end
      local rows, err = db:query("SELECT money FROM players WHERE account = ?", { account })
      if not rows then return lsmp.error("load failed: " .. err) end
      lsmp.setPlayerMeta(playerId, "money", rows[1] and rows[1].money or 1000)
    end)
    
    lsmp.on("playerLeave", function(playerId)
      local account = lsmp.getPlayerLsmpId(playerId)
      if not account then return end
      db:query("INSERT INTO players (account, money) VALUES (?, ?) ON DUPLICATE KEY UPDATE money = VALUES(money)",
        { account, lsmp.getPlayerMeta(playerId, "money") or 0 })
    end)
    jsJavaScript
    lsmp.on("playerJoin", async (playerId) => {
      const account = lsmp.getPlayerLsmpId(playerId);
      if (account === null) return;
      const rows = await db.query("SELECT money FROM players WHERE account = ?", [account]);
      lsmp.setPlayerMeta(playerId, "money", rows[0]?.money ?? 1000);
    });
    
    lsmp.on("playerLeave", async (playerId) => {
      const account = lsmp.getPlayerLsmpId(playerId);
      if (account === null) return;
      await db.query(
        "INSERT INTO players (account, money) VALUES (?, ?) ON DUPLICATE KEY UPDATE money = VALUES(money)",
        [account, lsmp.getPlayerMeta(playerId, "money") ?? 0],
      );
    });

Common mistakes

  • Storing in meta and expecting it after a restart. Meta live in memory only.
  • Keying on playerId or name. Use the account (lsmpId).
  • Building SQL with string concatenation. Always use ? parameters.
  • Writing files next to the resource. A resource has no folder of its own on disk at run time: write in lsmp.getDataPath().
  • Huge stored values. One value is at most 64 KiB and a store 16 MiB: move large data to MySQL or files.
Build resources

Web interfaces (guide)

Build in-game interfaces with HTML, CSS and JavaScript: where the files go, how the page and your script talk, focus, frameworks, and the mistakes everyone makes once.

An interface is three pieces: files in a webui folder of your resource, a client script that opens them with lsmp.createBrowser, and the page, which talks to that script through its lsmp object. The full reference is in Browsers and The lsmp object in a page; a step-by-step build is in the UI tutorial.

  1. Put the page in a webui folder

    Declare the folder in the manifest. Its content is served at rsc://<resource name>/: here web/index.html is rsc://hud/index.html.

    Lua only:

    resources/
    └─ hud/
       β”œβ”€ manifest.json
       β”œβ”€ client/
       β”‚  └─ main.lua
       └─ web/
          β”œβ”€ index.html
          β”œβ”€ style.css
          └─ app.js

    JavaScript only:

    resources/
    └─ hud/
       β”œβ”€ manifest.json
       β”œβ”€ client/
       β”‚  └─ main.js
       └─ web/
          β”œβ”€ index.html
          β”œβ”€ style.css
          └─ app.js

    Lua only:

    jsonmanifest.json
    {
      "title": "HUD",
      "client_scripts": "client/main.lua",
      "webui": "web"
    }

    JavaScript only:

    jsonmanifest.json
    {
      "title": "HUD",
      "client_scripts": "client/main.js",
      "webui": "web"
    }
  2. Open it from a client script

    Without bounds, a page covers the whole screen; everything you do not paint stays transparent, so a full-screen page with a small panel in a corner is fine. Send the first data once the page is loaded.

    luaclient/main.lua
    local hud = lsmp.createBrowser("rsc://hud/index.html")
    
    hud:on("load", function()
      hud:emit("money", 1500)
    end)
    jsclient/main.js
    const hud = lsmp.createBrowser('rsc://hud/index.html');
    
    hud.on('load', () => {
      hud.emit('money', 1500);
    });
  3. Listen in the page

    lsmp is there before your first script runs. Keep the page background transparent.

    htmlweb/index.html
    <!doctype html>
    <html>
    <head>
      <link rel="stylesheet" href="style.css">
    </head>
    <body>
      <div id="money" class="panel">$0</div>
      <script src="app.js"></script>
    </body>
    </html>
    cssweb/style.css
    html, body { margin: 0; background: transparent; overflow: hidden; }
    .panel {
      position: absolute; top: 2vh; right: 2vw;
      padding: .6em 1em; border-radius: 8px;
      background: rgba(0, 0, 0, .6); color: #7CFC9A;
      font: 600 2.2vh system-ui, sans-serif;
    }
    jsweb/app.js
    lsmp.on('money', (amount) => {
      document.getElementById('money').textContent = `$${amount.toLocaleString()}`;
    });
  4. Start it and look

    Restart the server so it loads hud, then join. Open the client console with F8 to read errors, and DevTools to inspect the page.

Choosing the direction

You wantScript sidePage side
Push data to the pagebrowser:emit("money", 1500)lsmp.on('money', fn)
Tell the script something happenedbrowser:on("close", fn)lsmp.emit('close')
Ask the script, wait for the answerbrowser:on("buy", fn) returns the answerawait lsmp.call('buy', id)
Ask the page, wait for the answerbrowser:call("getForm")lsmp.on('getForm', fn) returns the answer
Reach the serverThe client script calls the server (lsmp.callServer, lsmp.emitServer) and forwards the resultNever directly
⚠
The page is the player's

Pages run on the player's machine, like client scripts: a player can change what they send. Check every value in the client script, and decide everything that matters (money, items, permissions) on the server.

Menus: focus and cursor

A page without the focus is click-through: perfect for a HUD. A menu needs the mouse and keyboard: give it the focus while it is open, and take it back when it closes. The cursor shows only while a page holds the mouse. A text field that needs no mouse, like a chat, takes the keyboard alone with setFocus(true, { cursor = false }) ({ cursor: false } in JS): no cursor appears while the player types. A panel that must stay usable while the player keeps playing takes the mouse alone with { keepInput = true } ({ keepInput: true } in JS). The player can always escape with Ctrl+Alt+Backspace; your script then gets focusLost, so close the menu there too.

luaclient/main.lua
local menu = lsmp.createBrowser("rsc://hud/menu.html", { visible = false })

local function setOpen(open)
  menu:setVisible(open)
  menu:setFocus(open)
end

lsmp.registerCommand("menu", function() setOpen(true) end)
menu:on("close", function() setOpen(false) end)      -- the page's close button
menu:on("focusLost", function() setOpen(false) end)  -- Ctrl+Alt+Backspace
jsclient/main.js
const menu = lsmp.createBrowser('rsc://hud/menu.html', { visible: false });

function setOpen(open) {
  menu.setVisible(open);
  menu.setFocus(open);
}

lsmp.registerCommand('menu', () => setOpen(true));
menu.on('close', () => setOpen(false));      // the page's close button
menu.on('focusLost', () => setOpen(false));  // Ctrl+Alt+Backspace
jsweb/menu.js
document.querySelector('#close').addEventListener('click', () => lsmp.emit('close'));
document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') lsmp.emit('close');
});
  • Hide rather than destroy a menu you reopen often: a hidden page keeps its state and opens instantly.
  • Several pages: zIndex orders them. Only focused, visible pages take the mouse.

Frameworks and build tools

React, Vue, Svelte and plain modules all work. Point webui at the built output, not at the sources: node_modules is never sent to players anyway.

  1. Build into the resource

    Each resource has its own host (rsc://hud/), so absolute paths (/assets/app.js) and relative ones both resolve inside it.

    jsonmanifest.json
    {
      "title": "HUD",
      "client_scripts": "client/main.js",
      "webui": "ui/dist"
    }
  2. Develop with hot reload

    Outside a server session, a 2D browser may open http://localhost: run your dev server and point the browser at it from a local resource in Story mode. Switch back to rsc:// before you ship: on a server, http:// is refused.

    luaclient/main.lua
    local DEV = lsmp.gameType() == "SP"
    local url = DEV and "http://localhost:5173/" or "rsc://hud/index.html"
    local hud = lsmp.createBrowser(url)
    jsclient/main.js
    const DEV = lsmp.gameType() === 'SP';
    const url = DEV ? 'http://localhost:5173/' : 'rsc://hud/index.html';
    const hud = lsmp.createBrowser(url);
  3. Design in a normal browser

    Outside the game there is no lsmp: load the small stand-in first.

A page in the world (3D)

A cinema screen, a billboard, a laptop: lsmp.createBrowser3D renders a page into a texture, and lsmp.replaceTexture puts it in place of a game texture. 3D pages have no mouse or keyboard; drive them with emit and call. Keep their size and fps as low as the content allows: each one costs rendering time on the player's machine.

Common mistakes

SymptomCause and fix
createBrowser raises URL refusedhttp:// on a server, or a typo in the scheme. Use rsc://<resource>/… or https://.
loadError with http-404The file is not in a webui folder, or the path includes the folder name: with "webui": "web", it is rsc://hud/index.html, not rsc://hud/web/index.html.
The page shows but receives nothingYou emitted to another handle, or the page registers its lsmp.on handlers too late (inside a callback). Register them at the top of the page's script.
lsmp.call rejects with no-handlerThe script has no browser:on handler for that name on this browser.
The game no longer reacts to the keyboardA page kept the focus. Call setFocus(false) when your menu closes; players can always press Ctrl+Alt+Backspace.
Clicks go through the pageIt has no focus, or took the keyboard only (cursor set to false): setFocus(true).
alert does nothing, stored data is missing2D pages have no dialogs: draw your own. Storage is per server, and a 2D page and a 3D page do not share it. See Storage, microphone, camera and limits.
A black or white rectangle over the gameThe page paints a background: set background: transparent on html and body.
Guide Β· client

Assets and streaming

Ship models, textures, maps and vehicles with a resource, load parts of them only when they are needed, and take parts of the base game out of the world.

A resource carries streamed assets: the game files (.ydr, .ytd, .yft, .ymap, .ybn…) that players download with it and that the game streams in as it needs them. This guide shows how to lay them out, how they combine with the game and with other resources, and how client scripts change them while the game runs. The functions are documented in Hot resources, stream sets and archives.

Where streamed files go

Files in the stream/ folder of a resource are streamed as soon as the resource is mounted on the client. Sub-folders are only for your own order. To load some files later, put them in a sub-folder of stream/ and declare it as a stream set in the manifest.

my_island/
β”œβ”€ manifest.json
β”œβ”€ client/
β”‚  └─ main.lua
└─ stream/                 # streamed while the resource is mounted
   β”œβ”€ island_terrain.ybn
   β”œβ”€ island_terrain.ymap
   β”œβ”€ island_props.ytyp
   β”œβ”€ night_club/          # stream set "club": loaded by a script
   β”‚  β”œβ”€ club_interior.ymap
   β”‚  └─ club_props.ydr
   └─ winter/              # stream set "winter": loaded with the resource
      └─ island_snow.ytd
jsonmanifest.json
{
  "title": "My island",
  "client_scripts": ["client/main.lua"],
  "stream_sets": [
    { "name": "club", "folder": "stream/night_club", "load": "manual" },
    { "name": "winter", "folder": "stream/winter", "load": "auto" }
  ]
}
KeyMeaning
stream_sets[].nameThe set's name for scripts: [a-z0-9_-], 1 to 64 characters.
stream_sets[].folderFolder of the set, relative to the resource root like every path of the manifest, and inside stream/: "stream/night_club". A file belongs to the set of its closest folder.
stream_sets[].load"auto" (default): loaded with the resource. "manual": loaded only by lsmp.resources.loadStreamSet.
data_filesGame data files (metadata, text, water…) mounted with the resource, or with one of its sets. See Resource layout.

Who wins when two files share a name

Every mounted resource is a layer over the game's own files. When two layers provide the same file name, the one mounted last wins. Inside a resource, a loaded set wins over the rest of the resource, and a set loaded later wins over one loaded before.

Taking a layer away (stopping a resource, unloading a set) lets the next one show through: another resource, the game's file, or nothing if only that layer had the name.

β„Ή
In-use assets are never pulled away

A model or a texture that something still draws, or that a script requested, keeps its file until it is released. Unloading a set or unregistering it does not fail because of that: the asset follows once it is free. Release what you request (setModelAsNoLongerNeeded, setStreamedTextureDictAsNoLongerNeeded) before you swap content.

Load content on demand

A set declared "manual" costs nothing until a script loads it. A typical use is an interior that only matters when a player goes there.

luaLua
-- client/main.lua: load the club when the player comes near, unload it when they leave.
local CLUB = { x = -1569.0, y = -3017.0, z = -74.0 }
local loaded = false

lsmp.createThread(function()
  while true do
    local p = getEntityCoords(playerPedId(), false)
    local near = getDistanceBetweenCoords(p.x, p.y, p.z, CLUB.x, CLUB.y, CLUB.z, true) < 150.0
    if near ~= loaded then
      loaded = near
      local ok, err
      if near then
        ok, err = lsmp.resources.loadStreamSet("my_island", "club")
      else
        ok, err = lsmp.resources.unloadStreamSet("my_island", "club")
      end
      if not ok then lsmp.warn("club set: " .. err) end
    end
    lsmp.wait(1000)
  end
end)
jsJavaScript
// client/main.js: load the club when the player comes near, unload it when they leave.
const CLUB = { x: -1569.0, y: -3017.0, z: -74.0 };
let loaded = false;

setInterval(async () => {
  const p = getEntityCoords(playerPedId(), false);
  const near = getDistanceBetweenCoords(p, CLUB, true) < 150.0;
  if (near === loaded) return;
  loaded = near;
  try {
    if (near) await lsmp.resources.loadStreamSet('my_island', 'club');
    else await lsmp.resources.unloadStreamSet('my_island', 'club');
  } catch (err) {
    lsmp.warn(`club set: ${err.code}`);
  }
}, 1000);

Replace part of the base map

To put your own map where the game has one, take the game's pieces out first. Two tools work together:

  • invalidateArchives switches whole archives of the game off: their maps and collisions disappear, the way a map DLC removes what it replaces.
  • unregisterAssets takes named assets out, and frees their place in the game's asset stores: that is what makes room for many new models and textures.
  1. Hide the transition

    Show a loading screen, or keep the player somewhere that stays: maps and collisions leave on the spot, and a player standing on them falls.

  2. Switch the game's pieces off

    Call invalidateArchives with every archive of the area in one list, then unregisterAssets for the models and textures you need room for. Ship the lists as JSON files of the resource (files in the manifest) and read them with lsmp.readResourceFile.

  3. Bring yours in

    Start the resource that carries the new map, or load its set. Jobs run in order: there is no need to wait for the previous step before asking.

  4. Undo

    Stopping the resource that made the changes restores the archives it switched off. Leaving the server restores everything.

luaLua
-- Downtown replaced by our own map, in one go.
local archives = lsmp.json.decode(lsmp.readResourceFile("data/downtown_archives.json"))
local assets = lsmp.json.decode(lsmp.readResourceFile("data/downtown_assets.json"))

lsmp.resources.invalidateArchives(archives, function(res, err)
  if not res then lsmp.warn("archives: " .. err) end
end)
lsmp.resources.unregisterAssets(assets, function(res, err)
  if res and res.failed > 0 then lsmp.log(res.failed .. " assets still in use") end
end)
lsmp.resources.loadStreamSet("my_downtown", "city", function(ok, err)
  if not ok then lsmp.warn("city set: " .. err) end
end)
jsJavaScript
// Downtown replaced by our own map, in one go.
const archives = JSON.parse(lsmp.readResourceFile('data/downtown_archives.json'));
const assets = JSON.parse(lsmp.readResourceFile('data/downtown_assets.json'));

async function replaceDowntown() {
  // Requested together: the jobs run in this order.
  const steps = [
    lsmp.resources.invalidateArchives(archives),
    lsmp.resources.unregisterAssets(assets),
    lsmp.resources.loadStreamSet('my_downtown', 'city'),
  ];
  const [, res] = await Promise.all(steps);
  if (res.failed > 0) lsmp.log(`${res.failed} assets still in use`);
}

replaceDowntown().catch((err) => lsmp.warn(`downtown: ${err.code}`));
βœ“
Order inside a list

The engine retries refused names as long as a pass makes progress, so order is not required. Listing maps (.ymap) first, then collisions, types (.ytyp), models, and textures last, simply makes it one pass.

Quiet the story scripts

The game's story scripts still run in a session. Some load extra buildings and interiors, others start activities. suspendScriptIpls removes the map pieces they add, and suspendStoryScript stops one script by name. Both are restored when the resource that asked stops.

Common problems

SymptomCause
A replaced model still shows the old oneThe old model is still in use: an entity draws it, or a script requested it. It switches once released.
unregisterAssets reports failed > 0Those names are in use, or no asset has that name. Check the names with getAssetState.
loadStreamSet rejects with not-foundThe resource is not mounted (and no mountResource for it is queued), or the set name differs: names are case-sensitive.
The player falls through the groundA collision (.ybn) or a map was removed under them. Do the swap behind a loading screen.
An archive counts in failedIt is a data archive, not a streaming one, or its name is not the one the game registered.
Build resources

Local resources

Run a resource straight from its working folder in Story mode: no server, no packaging, reload in seconds. The same folder then goes, unchanged, to a server or to the marketplace.

Every sub-folder of the resources folder of your LS:MP installation is a local resource: %LocalAppData%\LSMP\resources by default. It has exactly the layout a server keeps under resources/ (Resource layout), and it loads in Story mode. Use it to build a map, a vehicle pack, a client script or an interface before putting it on a server or publishing it.

  1. Drop your folder

    Create resources next to the LS:MP client if it does not exist, and put your resource folder in it. The folder name is the resource name: lowercase letters, digits, _ and -.

    %LocalAppData%\LSMP\
    └─ resources/
       β”œβ”€ my-map/
       β”‚  β”œβ”€ manifest.json
       β”‚  └─ stream/
       └─ hud/
          β”œβ”€ manifest.json
          β”œβ”€ client/
          └─ web/
  2. Switch it on

    In the LS:MP menu, My mods lists it with a Local badge and its own switch. It is off by default: dropping a folder is not asking for it to load. A folder with an invalid name is listed, switched off, with the name to rename it to.

  3. Enter Story mode

    The resource is mounted as the world loads. Its client scripts run, and lsmp.gameType() answers "SP". Open the client console with F8 to read its log.

It behaves like its future package

The folder is mounted through the same rules a server applies when it packs a resource for players. That is what makes the test honest:

  • Only what the client package would hold is visible: shared and client scripts, files, webui, data_files, stream/. No server script runs: there is no server in Story mode.
  • Patterns of the manifest are resolved the way the packager resolves them.
  • An invalid manifest.json keeps the resource from mounting, and My mods says why, with the line and column.
On a serverLocal folder
ContentFrozen when the server packs itRead from the disk each time the resource is mounted
On or offenabled in the server's resources.jsonThe switch in My mods
Server scriptsRunIgnored
Page addressesrsc:// and https://Also http://localhost, for a dev server with hot reload
DevToolsFor developers the server allowsAlways, with Ctrl+Shift+I

Reload while you work

Unmounting a local resource then mounting it again reads the whole folder again, manifest included, without leaving Story mode. A small helper resource makes it one command: reload hud in the F8 console.

luadev-tools/client/main.lua
lsmp.registerCommand("reload", { help = "reload a local resource" }, function(args)
  local name = args[1]
  if not name then
    lsmp.warn("usage: reload <resource>")
    return
  end
  lsmp.unmountResource(name, function()
    lsmp.mountResource(name, function(ok, err)
      if ok then lsmp.log(name .. " reloaded") else lsmp.warn(name .. " failed: " .. err) end
    end)
  end)
end)
jsdev-tools/client/main.js
lsmp.registerCommand('reload', { help: 'reload a local resource' }, async (args) => {
  const name = args[0];
  if (!name) return lsmp.warn('usage: reload <resource>');
  try {
    await lsmp.unmountResource(name);
    await lsmp.mountResource(name);
    lsmp.log(`${name} reloaded`);
  } catch (err) {
    lsmp.warn(`${name} failed: ${err.code}`);
  }
});
  • Scripts, JSON files and web pages can be edited at any time.
  • Streamed assets are locked while mounted: a .ydr, .ytd or .ymap of a mounted resource cannot be overwritten, and your export tool reports the file as in use. Unmount the resource, write the asset, mount it again.
  • See Hot resources for mountResource and unmountResource, and Debugging for DevTools.

No manifest yet?

A folder dropped without a manifest.json is not an error: it is someone starting. LS:MP reads the folder and writes the manifest it can deduce, once. From then on the file is yours: it is never regenerated or replaced. To get a fresh one after reorganising the folder, delete it.

KeyDeduced from
titleThe folder name.
shared_scripts, client_scripts, server_scriptsThe usual folders (shared/, client/, server/) as patterns; elsewhere, a script filed by its folder (src/client/x.js) or its name (cl_*, sv_*, sh_*).
filesWhat client/ and shared/ hold besides code.
data_filesGame metadata recognised by its name (vehicles.meta, handling.meta…), and the data file lines of a FiveM fxmanifest.lua.
webuiThe built output of a web project (dist/ or build/ next to a package.json), otherwise a folder holding an index.html.
  • Nothing is guessed. A script whose side nothing tells (main.lua at the root) is not declared, and a config.json at the root is not added to files.
  • FiveM scripts are not declared: they use another API and have to be ported. Their assets and data files are taken as they are: a FiveM vehicle pack loads without writing anything.
  • Game assets outside stream/ are never streamed: move them into stream/.
  • Everything left out is listed in a "_review" key of the generated manifest, with what to write to include it. The key is ignored by LS:MP; delete it when you are done.

Good to know

  • Hidden folders (.git, .vscode) are skipped.
  • The folder wins over the published mod. If you enable both a mod you published and the folder where you rework it, the folder runs, and its assets take precedence.
  • Local resources only exist in Story mode. On a server, players get that server's resources and nothing else.
Build resources

Debugging (logs, DevTools, common errors)

Find out why a resource does not start or does not behave: where every message goes, how to inspect your web pages with Chrome DevTools, and the errors you will meet first.

Where messages go

FromRead it in
Server scripts, server packaging, server.cfgThe server's terminal, the Console tab of the admin panel, and logs/ in the server folder (one file per session; the panel's History mode browses them).
Client scriptsThe client console: F8 in game.
Web pagesThe page's own console, in DevTools.
  • Every line written by a resource starts with its name: [shop] …. Use lsmp.log, lsmp.warn, lsmp.error and lsmp.debug; lsmp.setLogLevel hides the debug lines when you are done.
  • A handler that raises is isolated: the error is logged in red with the resource, the file and the line, and the other handlers still run.
  • A call that returns nil/false on a run-time failure leaves its code in lsmp.getLastError(). Codes are listed in Error codes.
  • resources in the server console lists every resource with its state: started, failed, stopped…

A fast loop

  1. Run a local server

    On your own machine, with RequireAdmission=false and PublicList=false, so you can join it at 127.0.0.1:2086.

  2. Edit, then restart the server

    The server reads its resources once, when it starts: after a change, restart it (quit in its console, then start it again) and join again. For client scripts and pages, local resources reload in seconds in Story mode.

  3. Read both consoles

    The server console for the server half, F8 for the client half, DevTools for pages.

  4. For client-only work, skip the server

    Maps, vehicles, interfaces and client scripts run as local resources in Story mode, with DevTools always open to you.

Common errors

MessageCause and fix
resource folder 'MyShop' is not a valid name (…): use 'myshop', not loadedRename the folder: names are lowercase.
resource 'shop': manifest.json is not valid JSON (line 7, column 3), not loadedA missing comma or quote at that place. JSON allows no comments and no trailing comma.
manifest.json: 'client_script' is not a manifest key, ignored (did you mean 'client_scripts'?)A typo or an old key: the key is ignored, so its scripts do not run. See Manifest keys.
no manifest.json, its client/ folder is ignoredScripts run only when a manifest lists them.
dependency 'db' of 'bank' is missing (did you mean 'mysql-db'?)Install the dependency, fix its name, or enable it in resources.json.
A resource is failed with an error in one of its filesA script raised while loading. Everything the resource had registered is removed; fix the file and restart the server.
A resource is failed after 30 secondsA top-level await never finished: ResourceStartTimeoutMs (server.cfg).
resource 'x' is disabled in resources.jsonSet "enabled": true in resources.json, then restart the server.
A server script is refused a file, a connection or a moduleThe sandbox blocked it; the log line names the operation. Allow it in server.cfg, grant a capability, or trust the resource.
A script is interrupted after 10 secondsIt blocked the server: the watchdog (SandboxWatchdogSec) stopped it. Never wait in a loop; use timers or lsmp.wait.
Players are refused with server check timed outA playerPreConnection handler did not answer within PreConnectionTimeoutMs. The warning names the resource.
Events from a client stop arriving under heavy useThat player went over ScriptEventBytesPerSec: excess events are dropped. Send less, or less often.
A call (call, callServer, callClient) fails with no-handlerNo resource registered that name with lsmp.onCall on the other side, or it is not started yet.
A browser gets loadError with refused-url or http-404See Web interfaces.

DevTools for your pages

Your browser pages are ordinary web pages: inspect them with the DevTools of Chrome or Edge on the same machine (Elements, Console, Sources and the debugger, Network, Performance, Memory, Application). Only the server's pages are offered; LS:MP's own interface is never listed.

Where the player isDevTools
Story mode, local resourcesAlways allowed.
On a serverOnly for a player the server marks as developer with lsmp.setPlayerDev, or who has the permission lsmp.devtools (members of the default admin group have it). Losing both, or leaving the server, closes every DevTools window.
  1. On a server, allow yourself

    Put yourself in a group with lsmp.devtools in the Permissions tab of the admin panel, or mark your developers from a server script:

    luaserver/main.lua
    local DEVELOPERS = { [1234567] = true }   -- LS:MP IDs
    
    lsmp.on("playerJoin", function(playerId)
      if DEVELOPERS[lsmp.getPlayerLsmpId(playerId)] then
        lsmp.setPlayerDev(playerId, true)
      end
    end)
    jsserver/main.js
    const DEVELOPERS = new Set([1234567]);   // LS:MP IDs
    
    lsmp.on('playerJoin', (playerId) => {
      if (DEVELOPERS.has(lsmp.getPlayerLsmpId(playerId))) {
        lsmp.setPlayerDev(playerId, true);
      }
    });
  2. Press Ctrl+Shift+I in game

    Or type devtools in the F8 console. Your web browser opens a local page, http://127.0.0.1:9222/, that lists the pages you can inspect. If you are not allowed, the console says why.

  3. Open a page in Chrome or Edge

    Each page has a Copy link button: paste the link in the address bar of Chrome or Edge. Or open chrome://inspect (edge://inspect): the pages appear under Remote Target, each with an inspect link.

Listed asWhat it is
Gameserver UI (2D browsers)The surface that holds every 2D page of the server, each in its own frame. In the Console, pick the frame with the context selector (top β–Ύ).
3D browser #idOne entry per 3D browser.
Console command (F8)What it does
devtoolsOpens the access and the page that lists your pages. Same as Ctrl+Shift+I.
devtools <port>The same on another port (1024–65535). The default is 9222, or one of the nine after it when it is taken.
devtools statusWhether you are allowed, whether the access is open and where, and how many pages are listed.
devtools closeCloses the access and every DevTools window.
  • Local only: the access listens on 127.0.0.1, and only once you ask for it.
  • One DevTools window per page at a time.
  • A paused debugger freezes the page; on the 2D surface, it freezes every 2D page of the server until you resume.
  • Ctrl+R reloads a 3D page. On the 2D surface it is refused (it would reload every page): reload one page from its script with browser:setUrl.
  • Popups opened by your pages are not listed.
⚠
A convenience, not a protection

The developer status and the lsmp.devtools permission keep DevTools away from ordinary players; they do not stop a modified client. Pages and client scripts run on the player's machine either way: never put a secret in them, and decide what matters on the server.

Publish

Publish

Publish a mod on lsmp.gg

Put a resource online for every LS:MP player: prepare the folder, upload it, and ship new versions. LS:MP checks it, packs it and serves it; you never build an archive yourself.

A mod is a resource folder: the same folder that runs on your server or as a local resource. Players get it with one click, in game and on the site; servers can run it too.

Free modPaid mod or subscription
Wherelsmp.gg β†’ your profile β†’ My creations β†’ Publish modOn Summum, the LS:MP store: create the product there. Your Summum mods are also listed in My creations, with a link to manage them.
UploadThe same uploader, the same checksThe same uploader, the same checks
β„Ή
Before you start

Your LS:MP account needs a verified email address: publishing stays closed until you open the activation link. Uploads are limited per 24 hours; My creations shows what is left.

Prepare the folder

  • Test it first, as a local resource in Story mode and, if it has a server part, on your own server.
  • One folder, with manifest.json at its top. Select that folder itself, not the one above it.
  • Without a manifest, only stream/ is sent: right for a pure asset mod (a map, vehicles), whose .ydr, .ytd, .ymap… are streamed from there. Data files (.meta, .gxt2) and scripts need a manifest.
  • Game assets are only ever streamed from stream/.
  • Leave out what players must not get: node_modules, .git and similar folders are dropped anyway, but secrets in client files are not. Server-side keys belong to the server owner's configuration, not to your mod.
my-mod/                 ← select this folder
β”œβ”€ manifest.json
β”œβ”€ client/
β”œβ”€ server/
β”œβ”€ web/
└─ stream/

Publish a free mod

  1. Details

    Title, address (lsmp.gg/mods/<address>: 3 to 40 lowercase letters, digits and single hyphens), target (LS:MP servers, Singleplayer, or both), category and sub-categories, description, and the other free mods of yours it depends on, if any. The address is final once the mod is published.

  2. Media

    Images and videos for the mod's page; the first one is the cover. Optional: you can add them later from My creations.

  3. Folder

    Drop the folder, or browse to it. The upload is encrypted.

  4. Review

    LS:MP checks the folder in your browser before anything is sent: what it delivers (client scripts, server scripts, assets) and what would make it fail. Errors block the upload: fix them in your folder, then select it again with Change. Warnings and notes do not block. Choose what to protect: 3D models, textures, resources.

  5. Progress

    Three phases: Upload, Packaging (LS:MP builds the client package and, if needed, the server package), Publishing. You may have to wait for a packager when many uploads run at once.

  6. Finish

    Your mod is live: players can get it now. Copy the link of its page to share it.

What the checks look at

The same rules as a server's packaging, so a mod that loads on your server publishes cleanly:

  • manifest.json must be valid JSON; unknown or old keys are reported (Manifest keys).
  • Every script and file the manifest names must exist inside the folder; paths cannot lead outside it.
  • Size limits per file, in total, in number of files and in folder depth, set by the service and shown when you drop the folder.
  • Two files cannot share the same path.
  • An upload whose content already exists is refused as already published.

New versions

In My creations, open the mod and press Add version: give it a version number, then drop the folder again. The same checks run, and the new version goes live at the end. Players see Update available in their library; Version history lists every release.

Mods on servers

  • A mod for LS:MP servers runs like any resource. Server owners get it for their server on lsmp.gg; the server downloads it at start, and it shows in the resources console list as a mod. Its resource name, the one scripts see (lsmp.getResourceName(), rsc://, dependencies, logs), is its slug followed by its mod id: las-venturas-41 for the mod las-venturas with id 41.
  • Its settings in the server's resources.json and its data (data folder, storage, capabilities) are keyed mod.<name> (mod.las-venturas-41), so they never mix with a local folder of the same name.
  • If a server has a local resource folder with the same name as a mod, the mod is not loaded, and the log names both.
  • Your server scripts run in the server's sandbox by default: ask only for what you need, and document it for server owners (Capabilities).

Remove a mod

Delete this mod in My creations withdraws every version. Players who have it keep it for 72 hours, then its files are purged. Its address stays reserved.

βœ“
Let players try it

A marketplace product with a client part gets a Try in game button. Give your mod a short TRY branch that takes the player straight to what you made: see Marketplace trials.

Publish

Marketplace trials

Players can try a marketplace mod in game before they buy it. What that trial world is, and the few lines that make your mod shine in it.

Every marketplace product with a client part (assets in stream/, or client scripts) gets a Try in game button. It starts a world built for that one mod: LS:MP loads the mod's client part and nothing else, and your client scripts know where they are: lsmp.gameType() returns "TRY". Their job is to take the player straight to what you sell: an interior, a map, a vehicle, an interface.

The trial world

  • A fresh session, without a save: no missions, no progress, no character of the player's. The map is the one your mod targets: the multiplayer map for a server mod, the story-mode map for a single-player mod.
  • Only LS:MP scripts run: your mod's Lua and JavaScript. No game mission script runs, including one your mod would try to start.
  • Your mod, alone: no other mod, none of the player's single-player mods, no .asi plugin.
  • No server: the server part of your mod is never downloaded. emitServer, server calls, network meta and voice have no effect, exactly as in Story mode.
  • No pause menu, no replay recording. F1 (or the key the player chose for the LS:MP menu) opens the LS:MP menu: Resume, Get it, End trial. A banner says so all along.
  • Discord shows the player as trying your mod, by its name.

Where the player arrives

LS:MP sets the scene once, when the player arrives. Everything can be changed with natives: they all work normally in a trial.

DefaultTo change it
PositionLegion Square: 195.0, -933.7, 30.7, heading 145setEntityCoordsNoOffset, setEntityHeading: below
HealthInvinciblesetPlayerInvincible(playerId(), false)
Wanted levelCapped at 0setMaxWantedLevel
Clock13:00, pausedsetClockTime, pauseClock(false)
WeatherEXTRASUNNY, persistentsetWeatherTypeNowPersist, clearWeatherTypePersist
Death, arrestIf your script removed invincibility, LS:MP stands the player up again at the arrival point a few seconds after a death

Take the player to your content

While the player is placed, the LS:MP loading screen stays up: at least 1.2 seconds once your scripts have started, then until the player stands still, 6 seconds at most. If your script moved the player more than 20 m, LS:MP then loads the area around them (up to 20 seconds) before the screen fades in.

So teleport at the top level of your client script, or within its first frames: the player never sees Legion Square. The player is frozen during that window: you can teleport them, not walk them.

luaclient/main.lua
if lsmp.gameType() == "TRY" then
  -- Marketplace trial: bring the player straight to the interior.
  local ped = playerPedId()
  setEntityCoordsNoOffset(ped, -1520.4, 110.1, 50.9, false, false, false)
  setEntityHeading(ped, 90.0)
end
jsclient/main.js
if (lsmp.gameType() === 'TRY') {
  // Marketplace trial: bring the player straight to the interior.
  const ped = playerPedId();
  setEntityCoordsNoOffset(ped, -1520.4, 110.1, 50.9, false, false, false);
  setEntityHeading(ped, 90.0);
}
βœ“
There is nothing to spawn

A trial has no arrival to script: LS:MP places the player and closes the loading screen itself. The spawn and loading-screen functions of a server arrival do nothing here.

⚠
Give your mod a TRY branch

Without one, the player lands on Legion Square and sees nothing of what you sell: your assets are streamed, but nobody is there to look at them.

Trials, from the player's side

  • Trials belong to an LS:MP account: guests cannot try mods.
  • Free trials are limited per account each week; past the quota, the menu says so.
  • A player who already owns the mod simply gets it, without using a trial.
  • A trial always runs the latest published version with a client part. A server-only mod has nothing to show, and gets no button.
  • Your protected assets stay protected during a trial, and your server code is never sent.
β„Ή
Single-player mods run in Story mode too

The client scripts of single-player mods also run in Story mode, once the world is visible. There, lsmp.gameType() returns "SP": check it before relying on anything a server provides.

Server & client Β· Lua & JS

In-game benefits

Sell ranks, currency or kits for your server on Summum, on the store or without leaving the game, and deliver them from a server script without ever losing a purchase.

An in-game benefit is something a player buys for your server: a VIP rank, a stack of in-game money, a vehicle. It is a product of your Summum store: the player buys it on Summum, on its product page or in game, and Summum takes the payment. LS:MP then carries the purchase to your server, where a server script applies it and confirms it. LS:MP keeps track of every purchase until a script confirms it, so a crash, a restart or a disconnection only delays a delivery, never loses it.

  1. Create the benefit

    In your Summum store, create a product with the LS:MP integration, choose In-game benefit, attach it to your server and give it a benefit server key: the name your scripts use, such as vip-month or cash-100k (lowercase letters, digits and hyphens between words). Restart the server once after its first benefit: selling is switched on at start.

  2. Sell it

    Players buy it on its Summum page. To sell it in game as well, a client script puts its key in a cart and opens it: see Selling in game.

  3. Apply it

    When the buyer is connected, the benefitGrant event gives your server script the purchase, wherever it was bought. Apply it in your own data (a rank, a balance...).

  4. Confirm it

    Call lsmp.benefits.consume with the purchase id once your change is saved. Until then, the purchase is presented again at each of the player's sessions.

β„Ή
What the server needs

The server must be connected to the LS:MP network with its token (server.cfg). A server that sells benefits always verifies its players: a paid benefit is never delivered to an account a client only claims. The resource needs the benefits.read capability for the events and fetch, and benefits.consume to confirm. Marketplace mods do not get benefits.read unless the server owner grants it.

βœ“
A complete resource

The in-game-benefit resource of the server download does all of this: /shop sells VIP and cash in game, the server applies each purchase exactly once, and takes back what is refunded. See Example resources.

The life of a purchase

StatusMeaningYour script
pendingPaid, not yet received by this server.Apply it, then consume.
deliveredReceived by this server.Apply it, then consume.
consumedApplied and confirmed.Nothing.
revokedRefunded before it was confirmed.Nothing to take back.
revokingRefunded after it was confirmed.Take it back, then consumeRevocation.
reversedTaken back and confirmed.Nothing.
⚠
At least once

A purchase is presented once per session until it is confirmed. A script that applies a benefit and stops before confirming will see it again at the player's next session. Make applying idempotent: store the purchase id together with the change, in the same transaction, and skip an id you already applied.

Delivering on the server

benefitGrant (lsmpId, benefit) presents a purchase to apply, benefitRevoke (lsmpId, benefit) one to take back. They fire for a connected player: for what is outstanding when they join, and live when they buy while playing, on the product page or in game. benefit is a Benefit. Only resources holding benefits.read receive them, and each of them receives every purchase of the server: handle the keys of your resource only, and never confirm the others.

lsmp.benefits.fetch

ServerLua Β· JS
luaLua
lsmp.benefits.fetch(lsmpId [, opts] [, cb]) --> {Benefit}, err
jsJavaScript
lsmp.benefits.fetch(lsmpId: number|string, opts?: BenefitFetchOptions): Promise<Benefit[]>

Read the outstanding purchases of an account on this server.

Outstanding means pending, delivered or revoking: what a script still has to do. Oldest first. The answer may be a page: read again with after set to the last id you received, until an empty list. Useful to reconcile at a time of your choosing; the events already present everything to connected players. A guest account has nothing.

Needs the benefits.read capability.

Parameters
ParameterTypeDescription
lsmpIdlsmpIdThe account: the number from getPlayerLsmpId, or its string form.
opts optBenefitFetchOptionsSee BenefitFetchOptions.
Returns (Lua){Benefit}, err: A list of Benefit, or nil and a failure code.
Returns (JavaScript)Promise<Benefit[]>: Resolves with a list of Benefit; rejects with a failure code.
Failure codeWhen
unavailableThis server sells no benefits, or the LS:MP network cannot be reached.
limitToo many requests in a short time.
timeoutNo answer in time.
invalidThe account or the cursor is not valid.
permissionThe resource does not hold benefits.read.
Example
luaLua
-- Every purchase an account still has to receive or give back, page by page.
-- Call it from an event or command handler: fetch waits for LS:MP there.
local function outstanding(lsmpId)
  local all, after = {}, 0
  while true do
    local page, err = lsmp.benefits.fetch(lsmpId, { after = after })
    if not page then return nil, err end
    if #page == 0 then return all end
    for _, b in ipairs(page) do all[#all + 1] = b end
    after = page[#page].id
  end
end
jsJavaScript
// Every purchase an account still has to receive or give back, page by page.
async function outstanding(lsmpId) {
  const all = [];
  for (let after = 0; ;) {
    const page = await lsmp.benefits.fetch(lsmpId, { after });
    if (page.length === 0) return all;
    all.push(...page);
    after = page[page.length - 1].id;
  }
}

lsmp.benefits.consume

ServerLua Β· JS
luaLua
lsmp.benefits.consume(id [, lsmpId] [, cb]) --> BenefitConsumeResult, err
jsJavaScript
lsmp.benefits.consume(id: number, lsmpId?: number|string): Promise<BenefitConsumeResult>

Confirm that a purchase was applied.

Call it after your change is saved. The confirmation is written to disk before it is sent: if the network cannot be reached it is kept and sent later (queued: true), and the purchase is not presented again in the meantime. Give the lsmpId you applied it to: the network then refuses a purchase that belongs to someone else.

If the purchase was refunded in the meantime, the result has status: "revoking": take the benefit back and confirm with consumeRevocation.

Needs the benefits.consume capability.

Parameters
ParameterTypeDescription
idintThe purchase id.
lsmpId optlsmpIdThe account it was applied to.
Returns (Lua)BenefitConsumeResult, err: A BenefitConsumeResult, or nil and a failure code.
Returns (JavaScript)Promise<BenefitConsumeResult>: Resolves with a BenefitConsumeResult; rejects with a failure code.
Failure codeWhen
not-foundNot a purchase of this server.
invalidNot this account's purchase, or the id is not valid.
unavailableThis server sells no benefits.
ioThe confirmation could not be written to the server's disk: keep your own record and try again.
permissionThe resource does not hold benefits.consume.
Example
luaLua
lsmp.on("benefitGrant", function(lsmpId, benefit)
  if benefit.key ~= "cash-100k" then return end   -- another resource's benefit: leave it
  -- applyOnce saves the change with the purchase id, and skips an id it already applied.
  if not Wallet.applyOnce(benefit.id, lsmpId, 100000 * benefit.quantity) then return end
  local res, err = lsmp.benefits.consume(benefit.id, lsmpId)
  if not res then
    lsmp.warn("purchase " .. benefit.id .. " applied, not confirmed yet: " .. err)
  elseif res.status == "revoking" then
    -- Refunded in the meantime: take it back at once.
    Wallet.revertOnce(benefit.id, lsmpId)
    lsmp.benefits.consumeRevocation(benefit.id, lsmpId)
  end
end)
jsJavaScript
lsmp.on('benefitGrant', async (lsmpId, benefit) => {
  if (benefit.key !== 'cash-100k') return;   // another resource's benefit: leave it
  // applyOnce saves the change with the purchase id, and skips an id it already applied.
  if (!(await Wallet.applyOnce(benefit.id, lsmpId, 100000 * benefit.quantity))) return;
  try {
    const res = await lsmp.benefits.consume(benefit.id, lsmpId);
    if (res.status === 'revoking') {
      // Refunded in the meantime: take it back at once.
      await Wallet.revertOnce(benefit.id, lsmpId);
      await lsmp.benefits.consumeRevocation(benefit.id, lsmpId);
    }
  } catch (err) {
    lsmp.warn(`purchase ${benefit.id} applied, not confirmed yet: ${err.code}`);
  }
});

lsmp.benefits.consumeRevocation

ServerLua Β· JS
luaLua
lsmp.benefits.consumeRevocation(id [, lsmpId] [, cb]) --> BenefitConsumeResult, err
jsJavaScript
lsmp.benefits.consumeRevocation(id: number, lsmpId?: number|string): Promise<BenefitConsumeResult>

Confirm that a refunded purchase was taken back.

For a purchase in the revoking status, after your reversal is saved. Same guarantees as consume.

Needs the benefits.consume capability.

Parameters
ParameterTypeDescription
idintThe purchase id.
lsmpId optlsmpIdThe account it was taken back from.
Returns (Lua)BenefitConsumeResult, err: A BenefitConsumeResult, or nil and a failure code.
Returns (JavaScript)Promise<BenefitConsumeResult>: Resolves with a BenefitConsumeResult; rejects with a failure code.
Failure codeWhen
not-foundNot a purchase of this server.
invalidThe purchase is not refunded, or not this account's.
unavailableThis server sells no benefits.
ioThe confirmation could not be written to the server's disk.
permissionThe resource does not hold benefits.consume.
Example
luaLua
lsmp.on("benefitRevoke", function(lsmpId, benefit)
  if benefit.key ~= "cash-100k" then return end
  Wallet.revertOnce(benefit.id, lsmpId)
  lsmp.benefits.consumeRevocation(benefit.id, lsmpId)
end)
jsJavaScript
lsmp.on('benefitRevoke', async (lsmpId, benefit) => {
  if (benefit.key !== 'cash-100k') return;
  await Wallet.revertOnce(benefit.id, lsmpId);
  await lsmp.benefits.consumeRevocation(benefit.id, lsmpId);
});

Selling in game

A client script can sell your benefits without the player leaving the game. It fills a cart with benefit keys and opens it: LS:MP prepares a Summum order for the player's LS:MP account and shows Summum's checkout in the LS:MP secure payment window. Sign-in, payment and bank checks all happen in that window, and your script sees none of it. A completed payment reaches your server through benefitGrant, like a purchase made on the product page.

A cart names each benefit by its key, the same key that benefitGrant reports. LS:MP finds the product among the benefits on sale for the server the player is connected to: your scripts never handle store product ids, and can only sell their own server's benefits.

⚠
The client never learns whether the player paid

A cart only tells you that its window was shown, then closed, and who closed it. A closed window says nothing about the payment: the player may have paid, given up, or still be waiting for their bank. Never grant anything from the client: deliver on the server, where the same code also delivers what the player bought on the product page.

Building a cart

lsmp.createCart

ClientLua Β· JS
luaLua
lsmp.createCart() --> Cart
jsJavaScript
lsmp.createCart(): Cart

Create an empty cart owned by this resource.

Nothing is sent or checked until the cart is opened. A resource can keep several carts, but the client has only one payment window at a time.

ReturnsCart: A new, empty cart, in the "idle" state.

cart.add

ClientLua Β· JS
luaLua
cart:add(key [, quantity]) --> Cart
jsJavaScript
cart.add(key: string, quantity: number = 1): Cart

Add a benefit, or more of one already in the cart.

A cart holds at most 50 different benefits, and at most 99 of each. Going over raises a RangeError. A key that is not well formed raises an error at once; a well-formed key that this server does not sell is refused when the cart opens (invalid).

Parameters
ParameterTypeDescription
keystringThe benefit server key, exactly as set in the product editor (for example "vip-month"): 1 to 63 letters, digits, _ or -. Case matters.
quantity optintHow many to add, 1 to 99. Default: 1
ReturnsCart: The cart itself, so that calls can be chained.

cart.remove

ClientLua Β· JS
luaLua
cart:remove(key) --> boolean
jsJavaScript
cart.remove(key: string): boolean

Remove a benefit line.

Parameters
ParameterTypeDescription
keystringThe key of the benefit to remove.
Returnsboolean: true if the benefit was in the cart.

cart.clear

ClientLua Β· JS
luaLua
cart:clear() --> Cart
jsJavaScript
cart.clear(): Cart

Remove every benefit.

ReturnsCart: The cart itself, so that calls can be chained.

cart.getItems

ClientLua Β· JS
luaLua
cart:getItems() --> {CartItem}
jsJavaScript
cart.getItems(): CartItem[]

The lines of the cart, in the order they were added.

ReturnsCartItem[]: A list of CartItem, new on each call: changing it does not change the cart.

cart.getState

ClientLua Β· JS
luaLua
cart:getState() --> string
jsJavaScript
cart.getState(): string

Where the cart stands.

Returnsstring: "idle" (never opened), "opening" (the order is being prepared), "open" (the payment window is shown) or "closed" (its last opening is over; it can be opened again).

Opening the payment window

cart.open

ClientLua Β· JS
luaLua
cart:open([cb]) --> string, err
jsJavaScript
cart.open(): Promise<string>

Show the cart in the LS:MP secure payment window, and wait until it closes.

Each opening sends the items the cart holds at that moment. LS:MP checks them with Summum first: the window appears a moment later, or the opening is refused. Asynchronous: see Conventions.

The result is how a window that was shown closed: "player" (the player closed it), "script" (cart.close) or "error" (the window was lost). It never says whether the player paid. A refusal before the window appears rejects with one of these codes, the error message giving the precise reason:

Returns (Lua)string, err: "player", "script" or "error"; nil and a code when the window could not be shown.
Returns (JavaScript)Promise<string>: Resolves with "player", "script" or "error"; rejects with a code when the window could not be shown.
CodeMeaning
invalidThe cart is empty, or a key is not a benefit on sale on this server.
limitThis cart, or another one, already has a window open or being prepared; or too many openings or purchases in a short time.
deniedThe player is a guest or not signed in to LS:MP, or the opening was cancelled by cart.close.
unavailableThe player is not on a server that sells benefits, or this server has not verified the player yet; payments are unavailable right now; or the game has plugins loaded that rule payments out.
errorAnything else that kept the window from appearing.
Example
luaLua
-- /cash [packs]: up to 10 packs of the benefit "cash-100k" in one cart.
local REFUSED = {
  denied = "Sign in to LS:MP to buy: guests cannot pay.",
  limit = "A payment window is already open, or one just closed.",
  unavailable = "Payments are not available right now.",
}

lsmp.registerCommand("cash", { help = "Buy in-game cash" }, function(args)
  local packs = math.min(math.max(math.floor(tonumber(args[1]) or 1), 1), 10)
  local closedBy, err = lsmp.createCart():add("cash-100k", packs):open()
  if not closedBy then
    lsmp.warn(REFUSED[err] or ("the payment window did not open: " .. err))
  end
end)
jsJavaScript
// /cash [packs]: up to 10 packs of the benefit "cash-100k" in one cart.
const REFUSED = {
  denied: 'Sign in to LS:MP to buy: guests cannot pay.',
  limit: 'A payment window is already open, or one just closed.',
  unavailable: 'Payments are not available right now.',
};

lsmp.registerCommand('cash', { help: 'Buy in-game cash' }, async (args) => {
  const packs = Math.min(Math.max(parseInt(args[0], 10) || 1, 1), 10);
  try {
    await lsmp.createCart().add('cash-100k', packs).open();
  } catch (err) {
    lsmp.warn(REFUSED[err.code] ?? `the payment window did not open: ${err.code}`);
  }
});

cart.close

ClientLua Β· JS
luaLua
cart:close() --> boolean
jsJavaScript
cart.close(): boolean

Close this cart's window, or cancel its opening.

A window that is shown closes and open resolves with "script". A cart still being prepared is cancelled: open rejects with denied.

Returnsboolean: true if there was a window to close or an opening to cancel.

Rules and limits

  • One window at a time on the client, whichever resource opened it.
  • Keys, not products. A key sells the benefit on sale under it on this server, whatever its store product: re-publishing or replacing a product changes nothing in your scripts. Should two products of the server grant the same key, the most recently published one on sale is sold.
  • Exclusive input. While the window is open, the game, your scripts and your pages receive no input. No script can draw over the window, read it or type into it.
  • Pop-ups stay in the window. A link of the payment page that opens a new window (the terms of sale, some payment methods) opens inside the payment window, under the same bar, one at a time. Closing it brings the payment back.
  • Cooldown. After a window closes, scripts wait a few seconds before they can open a new one, and the number of openings per minute is limited. Open a cart when the player asks for it, with a command or a click in your interface, never on a timer.
  • When the resource stops, a cart still being prepared is cancelled. A window already shown stays until the player closes it.

Complete example

VIP by the month, sold in game with /vip and delivered on the server exactly once: the purchase id is saved with the change, so a purchase presented again after a crash is only confirmed. A refunded purchase comes back through benefitRevoke (see consumeRevocation); the in-game-benefit resource handles that too.

luaserver/main.lua
-- VIP by the month: the benefit whose server key is "vip-month".
local DAY_MS = 24 * 60 * 60 * 1000

lsmp.on("benefitGrant", function(lsmpId, benefit)
  if benefit.key ~= "vip-month" then return end   -- another resource's benefit: leave it

  local key = "vip:" .. lsmpId
  local vip = lsmp.storage.get(key) or { untilMs = 0, applied = {} }
  local id = tostring(benefit.id)
  if not vip.applied[id] then
    -- Counted from the payment: a player who paid while away loses no day.
    vip.untilMs = math.max(vip.untilMs, benefit.purchasedAtMs) + 30 * DAY_MS * benefit.quantity
    vip.applied[id] = true   -- the id is saved in the same write as the change
    if not lsmp.storage.set(key, vip) or not lsmp.storage.flush() then
      return   -- not on disk: the purchase comes back at the next session
    end
  end

  -- Applied now or at an earlier session: confirm it.
  local res, err = lsmp.benefits.consume(benefit.id, lsmpId)
  if not res then
    lsmp.warn(("purchase %d applied, not confirmed yet: %s"):format(benefit.id, err))
  end
end)
luaclient/main.lua
-- /vip: sells the benefit "vip-month" without leaving the game.
lsmp.registerCommand("vip", { help = "Buy 30 days of VIP" }, function()
  local closedBy, err = lsmp.createCart():add("vip-month"):open()
  if closedBy == "player" then
    -- Not a proof of payment: the server applies the VIP when benefitGrant brings it.
    lsmp.log("If you paid, your VIP arrives in a moment.")
  elseif not closedBy then
    lsmp.warn("the payment window did not open: " .. err)
  end
end)
jsserver/main.js
// VIP by the month: the benefit whose server key is "vip-month".
const DAY_MS = 24 * 60 * 60 * 1000;

lsmp.on('benefitGrant', async (lsmpId, benefit) => {
  if (benefit.key !== 'vip-month') return;   // another resource's benefit: leave it

  const key = `vip:${lsmpId}`;
  const vip = lsmp.storage.get(key) ?? { untilMs: 0, applied: {} };
  if (!vip.applied[benefit.id]) {
    // Counted from the payment: a player who paid while away loses no day.
    vip.untilMs = Math.max(vip.untilMs, benefit.purchasedAtMs) + 30 * DAY_MS * benefit.quantity;
    vip.applied[benefit.id] = true;   // the id is saved in the same write as the change
    if (!lsmp.storage.set(key, vip)) return;   // not saved: it comes back at the next session
    try {
      await lsmp.storage.flush();
    } catch {
      return;
    }
  }

  // Applied now or at an earlier session: confirm it.
  try {
    await lsmp.benefits.consume(benefit.id, lsmpId);
  } catch (err) {
    lsmp.warn(`purchase ${benefit.id} applied, not confirmed yet: ${err.code}`);
  }
});
jsclient/main.js
// /vip: sells the benefit "vip-month" without leaving the game.
lsmp.registerCommand('vip', { help: 'Buy 30 days of VIP' }, async () => {
  try {
    const closedBy = await lsmp.createCart().add('vip-month').open();
    // Not a proof of payment: the server applies the VIP when benefitGrant brings it.
    if (closedBy === 'player') lsmp.log('If you paid, your VIP arrives in a moment.');
  } catch (err) {
    lsmp.warn(`the payment window did not open: ${err.code}`);
  }
});

Shapes

Benefit

FieldTypeDefaultDescription
idintβ€”The purchase id: unique across LS:MP, increasing. Use it to apply each purchase once.
keystringβ€”The key you gave the benefit on lsmp.gg. Ignore the keys your resource does not handle.
quantityintβ€”How many units were bought.
purchasedAtMsepochMsβ€”When it was paid. Compute any expiry from it.
statusstringβ€”See the life of a purchase.

BenefitFetchOptions

FieldTypeDefaultDescription
afterint0Return only purchases with a greater id (the next page).

BenefitConsumeResult

FieldTypeDefaultDescription
idintβ€”The purchase id.
statusstringβ€”The status after the call, or "queued" when the confirmation waits for the network.
appliedbooleanβ€”false when the purchase was already in that state (a repeated call).
queuedbooleanβ€”true when the confirmation is kept and will be sent later.

CartItem

FieldTypeDefaultDescription
keystringβ€”The benefit server key.
quantityintβ€”How many, 1 to 99.

Shared API

Shared Β· Lua & JS

Events

Local events between resources on one side, and network events between the server and clients.

Events let resources talk without knowing each other. Local events (emit, on) stay on the side where they are emitted: the server, or one client, and reach both Lua and JavaScript resources there. Network events carry the direction in their name: a client sends to the server with emitServer and the server listens with onClient; the server sends to clients with emitClient, emitAllClients or emitDimensionClients and clients listen with onServer. To get an answer back, use remote calls instead. The Events and RPC guide shows complete patterns.

You want toUse
react to something LS:MP does (a player joins, a resource stops)lsmp.on with an engine event
notify other resources on the same side (Lua or JS)lsmp.emit + lsmp.on
tell the server something (client)lsmp.emitServer (client) + lsmp.onClient (server)
tell clients something (server)lsmp.emitClient / emitAllClients / emitDimensionClients (server) + lsmp.onServer (client)
ask and wait for an answerlsmp.call / callServer / callClient
β„Ή
Local and network are separate

An emit never reaches an onServer or onClient handler, and a network event never reaches an on handler. The same name can be used for both without conflict.

Local events

lsmp.on

SharedLua Β· JS
luaLua
lsmp.on(name, fn [, filter]) --> function
jsJavaScript
lsmp.on(name: string, fn: Function, filter?: MetaFilter): () => boolean

Subscribes to a local event or an engine event, and returns the function that unsubscribes.

The handler receives the arguments given to emit (or the engine event's arguments). The same (name, fn) pair is only registered once. A handler that raises is logged with its resource name and the other handlers still run. In Lua the handler runs in its own coroutine, so it may wait.

Parameters
ParameterTypeDescription
nameeventEvent name. Engine event names are allowed here.
fnfnThe handler, fn(...args).
filter optMetaFilterOnly for metaChange: { scope, key, target }. See metaChange.
Returns (Lua)function: The unsubscribe function; it returns true if it removed the handler.
Returns (JavaScript)() => boolean: The unsubscribe function; it returns true if it removed the handler.
Example
luaLua
lsmp.on("shop:purchase", function(playerId, item, price)
  lsmp.log(("%d bought %s for $%d"):format(playerId, item, price))
end)
jsJavaScript
lsmp.on("shop:purchase", (playerId, item, price) => {
  lsmp.log(`${playerId} bought ${item} for $${price}`);
});

lsmp.once

SharedLua Β· JS
luaLua
lsmp.once(name, fn [, filter]) --> function
jsJavaScript
lsmp.once(name: string, fn: Function, filter?: MetaFilter): () => boolean

Like lsmp.on, but the handler is removed just before its first call.

Parameters
ParameterTypeDescription
nameeventEvent name. Engine event names are allowed.
fnfnThe handler, called at most once.
filter optMetaFilterOnly for metaChange.
Returns (Lua)function: The unsubscribe function.
Returns (JavaScript)() => boolean: The unsubscribe function.

lsmp.off

SharedLua Β· JS
luaLua
lsmp.off(name, fn) --> boolean
jsJavaScript
lsmp.off(name: string, fn: Function): boolean

Removes a handler this resource registered with lsmp.on or lsmp.once.

Pass the same function that was registered. Calling the function returned by lsmp.on does the same. Removing during a dispatch takes effect at the next dispatch.

Parameters
ParameterTypeDescription
nameeventEvent name.
fnfnThe registered handler.
Returnsboolean: true if a handler was removed.

lsmp.emit

SharedLua Β· JS
luaLua
lsmp.emit(name, ...)
jsJavaScript
lsmp.emit(name: string, ...args: Value[]): void

Emits a local event on this side, to every resource and both engines.

Handlers in the caller's language run immediately, during the call, in registration order. Handlers in the other language (Lua ↔ JavaScript) on the same side run a little later, in the same order. The emitting resource's own handlers receive the very values passed; other resources receive copies. Engine event names cannot be emitted.

Parameters
ParameterTypeDescription
nameeventEvent name: 1 to 128 bytes of UTF-8, case-sensitive. See Reserved names.
...args optvalueUp to 32 transportable values.
⚠
Good to know

- At most 32 emit calls can be nested (a handler that emits, whose handler emits...): beyond, the call raises.
- Arguments are encoded once when a handler outside the emitting resource listens: a value that is not transportable raises even if your own handlers would accept it.

Example
luaLua
-- resource "shop"
lsmp.emit("shop:purchase", playerId, "pistol", 500)

-- resource "stats" (any language)
lsmp.on("shop:purchase", function(playerId, item, price)
  lsmp.log(item .. " sold")
end)
jsJavaScript
// resource "shop"
lsmp.emit("shop:purchase", playerId, "pistol", 500);

// resource "stats" (any language)
lsmp.on("shop:purchase", (playerId, item, price) => lsmp.log(`${item} sold`));

Network events

Network events between a client and the server arrive in the order they were sent, together with remote calls and their answers. When they arrive, they are delivered to both engines (Lua and JavaScript) of the receiving side. A resource that is not started yet, or has no handler at that moment, does not get the event: nothing is queued.

From a client to the server

lsmp.emitServer

ClientLua Β· JS
luaLua
lsmp.emitServer(name, ...) --> boolean
jsJavaScript
lsmp.emitServer(name: string, ...args: Value[]): boolean

Sends an event to the server.

Nothing is queued when the client is not in a session: the call returns false.

Parameters
ParameterTypeDescription
nameeventEvent name: 1 to 128 bytes of UTF-8, case-sensitive. See Reserved names.
...args optvalueUp to 32 transportable values.
Returnsboolean: false when not in a session.
β„Ή
Size and rate

One event is at most 4 MiB βˆ’ 1 KiB encoded; bigger raises. The server limits what each player may send per second (ScriptEventBytesPerSec): events beyond it are dropped on the server. See Limits.

Example
luaLua
lsmp.emitServer("chat:send", "hello")
jsJavaScript
lsmp.emitServer("chat:send", "hello");

lsmp.onClient

ServerLua Β· JS
luaLua
lsmp.onClient(name, fn) --> function
jsJavaScript
lsmp.onClient(name: string, fn: Function): () => boolean

Subscribes to an event sent by clients.

The first argument of the handler is the playerId of the sender. It comes from the connection and cannot be forged; everything else comes from a client and must be checked (types, ranges, permissions).

Parameters
ParameterTypeDescription
nameeventEvent name (engine event names are refused).
fnfnfn(source, ...args).
Returns (Lua)function: The unsubscribe function.
Returns (JavaScript)() => boolean: The unsubscribe function.
Example
luaLua
-- server
lsmp.onClient("chat:send", function(source, text)
  if type(text) ~= "string" or #text == 0 or #text > 200 then return end
  lsmp.emitAllClients("chat:message", lsmp.getPlayerName(source), text)
end)
jsJavaScript
// server
lsmp.onClient("chat:send", (source, text) => {
  if (typeof text !== "string" || text.length === 0 || text.length > 200) return;
  lsmp.emitAllClients("chat:message", lsmp.getPlayerName(source), text);
});

lsmp.offClient

ServerLua Β· JS
luaLua
lsmp.offClient(name, fn) --> boolean
jsJavaScript
lsmp.offClient(name: string, fn: Function): boolean

Removes a client-event handler of this resource.

Parameters
ParameterTypeDescription
nameeventEvent name.
fnfnThe registered handler.
Returnsboolean: true if a handler was removed.

From the server to clients

lsmp.emitClient

ServerLua Β· JS
luaLua
lsmp.emitClient(target, name, ...) --> boolean
jsJavaScript
lsmp.emitClient(target: number | number[], name: string, ...args: Value[]): boolean

Sends an event to one player or to a list of players.

The target comes first, as in callClient.

Parameters
ParameterTypeDescription
targetplayerId | listOne playerId, or a list of playerIds.
nameeventEvent name: 1 to 128 bytes of UTF-8, case-sensitive. See Reserved names.
...args optvalueUp to 32 transportable values.
Returnsboolean: true if at least one target was connected.
β„Ή
Size

One event is at most 16 MiB encoded; bigger raises and nothing is sent. A client whose connection cannot keep up is disconnected. See Limits.

Example
luaLua
lsmp.emitClient(playerId, "hud:notify", "Welcome!")
lsmp.emitClient({ 1, 4, 7 }, "race:start", { laps = 3 })
jsJavaScript
lsmp.emitClient(playerId, "hud:notify", "Welcome!");
lsmp.emitClient([1, 4, 7], "race:start", { laps: 3 });

lsmp.emitAllClients

ServerLua Β· JS
luaLua
lsmp.emitAllClients(name, ...) --> integer
jsJavaScript
lsmp.emitAllClients(name: string, ...args: Value[]): number

Sends an event to every connected player.

Parameters
ParameterTypeDescription
nameeventEvent name: 1 to 128 bytes of UTF-8, case-sensitive. See Reserved names.
...args optvalueUp to 32 transportable values.
Returns (Lua)integer: The number of players reached.
Returns (JavaScript)number: The number of players reached.
Example
luaLua
lsmp.emitAllClients("weather:alert", "storm in 5 minutes")
jsJavaScript
lsmp.emitAllClients("weather:alert", "storm in 5 minutes");

lsmp.emitDimensionClients

ServerLua Β· JS
luaLua
lsmp.emitDimensionClients(dimension, name, ...) --> integer
jsJavaScript
lsmp.emitDimensionClients(dimension: number, name: string, ...args: Value[]): number

Sends an event to every player currently in a dimension.

Parameters
ParameterTypeDescription
dimensiondimensionThe dimension, 0..65535.
nameeventEvent name: 1 to 128 bytes of UTF-8, case-sensitive. See Reserved names.
...args optvalueUp to 32 transportable values.
Returns (Lua)integer: The number of players reached.
Returns (JavaScript)number: The number of players reached.
Example
luaLua
lsmp.emitDimensionClients(12, "arena:countdown", 3)
jsJavaScript
lsmp.emitDimensionClients(12, "arena:countdown", 3);

lsmp.onServer

ClientLua Β· JS
luaLua
lsmp.onServer(name, fn) --> function
jsJavaScript
lsmp.onServer(name: string, fn: Function): () => boolean

Subscribes to an event sent by the server.

Parameters
ParameterTypeDescription
nameeventEvent name (engine event names are refused).
fnfnfn(...args).
Returns (Lua)function: The unsubscribe function.
Returns (JavaScript)() => boolean: The unsubscribe function.
Example
luaLua
lsmp.onServer("chat:message", function(name, text)
  lsmp.log(name .. ": " .. text)
end)
jsJavaScript
lsmp.onServer("chat:message", (name, text) => {
  lsmp.log(`${name}: ${text}`);
});

lsmp.offServer

ClientLua Β· JS
luaLua
lsmp.offServer(name, fn) --> boolean
jsJavaScript
lsmp.offServer(name: string, fn: Function): boolean

Removes a server-event handler of this resource.

Parameters
ParameterTypeDescription
nameeventEvent name.
fnfnThe registered handler.
Returnsboolean: true if a handler was removed.
Shared Β· Lua & JS

Remote calls (RPC)

Call a function in another resource, on the server or on a player's client, and get its result back.

A call runs a function registered with lsmp.onCall and gives you its result. Three functions cover every case, and the direction is in the name:

  • lsmp.call calls a function of this side: on the server, a function of another server resource; on a client, a function of another resource of the same client. Lua and JavaScript resources call each other freely. Nothing goes over the network.
  • lsmp.callServer (client) calls a function published by the server.
  • lsmp.callClient (server) calls a function published by one player's client.
  • There is no client-to-client call: go through the server.
CallerFunctionHandlerHandler receives
any resource, same sidelsmp.call(name, ...)onCall of this sideserver: source = nil/null, then the arguments; client: the arguments
clientlsmp.callServer(name, ...)server onCallsource (the calling player), then the arguments
server resourcelsmp.callClient(playerId, name, ...)that player's client onCallthe arguments

Rules

  • One handler per name and per side, across all resources and both engines: the same handler answers lsmp.call from this side and calls from the other side. A second onCall with the same name raises 'x' is already handled by resource 'y'.
  • The handler returns the result: one transportable value. In Lua only the first returned value counts, and the handler may suspend; in JavaScript it may return a Promise.
  • If the handler raises, rejects or returns a value that cannot be sent, the caller fails with error. The message stays in the log of the side that handled the call: a client never sees server error messages.
  • The default deadline is 10 000 ms. Give { name = "x", timeoutMs = 2000 } instead of the name to change it (1 to 300 000 ms). At the deadline the caller gets timeout; a late answer is dropped.
  • A call never blocks, and is always asynchronous, even inside one resource. Answers of two calls can arrive in any order.
  • When the called resource stops, calls it was handling fail with error and later calls with no-handler. When the calling resource stops, its pending calls end with cancelled.
CodeWhen
timeoutNo answer before the deadline.
no-handlerNobody handles this name on the side that was called.
errorThe handler raised, rejected, or returned a value that cannot be sent.
disconnectedThe client is not in a session, or the player left before answering.
not-foundcallClient to a player who is not connected.
limit4096 calls of the resource are already pending, or the request is too large to send.
cancelledThe calling resource stopped.
βœ•
Never trust the client

A server onCall handler is reachable by every connected player with any arguments. Check types, ranges and the player's rights (source) before doing anything.

Functions

lsmp.onCall

SharedLua Β· JS
luaLua
lsmp.onCall(name, fn) --> function
jsJavaScript
lsmp.onCall(name: string, fn: Function): () => boolean

Registers the handler of a callable name on this side.

Server handler: fn(source, ...args), where source is the calling playerId, or nil/null for a local call (lsmp.call). Client handler: fn(...args). The returned value is the result.

Parameters
ParameterTypeDescription
nameeventCallable name (1 to 128 bytes; engine event names and the lsmp: prefix are refused).
fnfnThe handler; its return value (or resolved Promise) is the result.
Returns (Lua)function: The unregister function.
Returns (JavaScript)() => boolean: The unregister function.
Example
luaLua
-- server
lsmp.onCall("bank:withdraw", function(source, amount)
  if math.type(amount) ~= "integer" or amount <= 0 then return { ok = false } end
  local account = lsmp.getPlayerLsmpId(source)
  if not account then return { ok = false } end
  local balance = lsmp.storage.get("balance:" .. account) or 0
  if balance < amount then return { ok = false, balance = balance } end
  lsmp.storage.set("balance:" .. account, balance - amount)
  return { ok = true, balance = balance - amount }
end)
jsJavaScript
// server
lsmp.onCall("bank:withdraw", (source, amount) => {
  if (!Number.isInteger(amount) || amount <= 0) return { ok: false };
  const account = lsmp.getPlayerLsmpId(source);
  if (account === null) return { ok: false };
  const balance = lsmp.storage.get(`balance:${account}`) ?? 0;
  if (balance < amount) return { ok: false, balance };
  lsmp.storage.set(`balance:${account}`, balance - amount);
  return { ok: true, balance: balance - amount };
});

lsmp.offCall

SharedLua Β· JS
luaLua
lsmp.offCall(name, fn) --> boolean
jsJavaScript
lsmp.offCall(name: string, fn: Function): boolean

Unregisters this resource's handler of a name.

Calls already received still answer; later calls get no-handler.

Parameters
ParameterTypeDescription
nameeventCallable name.
fnfnThe registered handler.
Returnsboolean: true if the handler was removed.

lsmp.call

SharedLua Β· JS
luaLua
lsmp.call(name, ... [, cb]) --> any, err
jsJavaScript
lsmp.call(name: string | CallOptions, ...args: Value[]): Promise<Value>

Calls the handler of a name on this side (another resource, Lua or JavaScript) and returns its result. Asynchronous.

Nothing goes over the network: this is how resources share functions ("exports"). On the server the handler receives source = nil/null. The handler always runs later, never inside the call. In Lua, pass a callback as last argument, or call from a coroutine (see Asynchronous functions).

Parameters
ParameterTypeDescription
nameevent | CallOptionsThe name, or { name, timeoutMs } (timeoutMs 1 to 300 000, default 10 000).
...args optvalueUp to 32 transportable values.
Returns (Lua)any, err: The handler's result. Failure codes: see Rules.
Returns (JavaScript)Promise<Value>: The handler's result. Failure codes: see Rules.
Example
luaLua
-- server, resource "inventory" (Lua)
lsmp.onCall("inventory:count", function(source, playerId, item)
  return countItem(playerId, item)
end)

-- server, resource "shop" (Lua or JavaScript), in a host coroutine
local n, err = lsmp.call("inventory:count", playerId, "pistol")
if not n then lsmp.warn("inventory unavailable: " .. err) end
jsJavaScript
// server, resource "inventory" (JavaScript)
lsmp.onCall("inventory:count", (source, playerId, item) => countItem(playerId, item));

// server, resource "shop" (Lua or JavaScript)
async function stock(playerId) {
  try {
    return await lsmp.call("inventory:count", playerId, "pistol");
  } catch (e) {
    lsmp.warn(`inventory unavailable: ${e.code}`);
    return 0;
  }
}

lsmp.callServer

ClientLua Β· JS
luaLua
lsmp.callServer(name, ... [, cb]) --> any, err
jsJavaScript
lsmp.callServer(name: string | CallOptions, ...args: Value[]): Promise<Value>

Calls the server handler of a name and returns its result. Asynchronous.

The handler receives the calling player as source. The call keeps its order with emitServer. Outside a session it fails with disconnected. In Lua, pass a callback as last argument, or call from a coroutine (see Asynchronous functions).

Parameters
ParameterTypeDescription
nameevent | CallOptionsThe name, or { name, timeoutMs } (timeoutMs 1 to 300 000, default 10 000).
...args optvalueUp to 32 transportable values.
Returns (Lua)any, err: The handler's result. Failure codes: see Rules.
Returns (JavaScript)Promise<Value>: The handler's result. Failure codes: see Rules.
Example
luaLua
-- client, inside a host coroutine (event handler, file body, lsmp.createThread)
local res, err = lsmp.callServer({ name = "bank:withdraw", timeoutMs = 5000 }, 200)
if not res then
  lsmp.warn("withdraw failed: " .. err)
elseif res.ok then
  lsmp.log("new balance: " .. res.balance)
end
jsJavaScript
// client
async function withdraw(amount) {
  try {
    const res = await lsmp.callServer({ name: "bank:withdraw", timeoutMs: 5000 }, amount);
    if (res.ok) lsmp.log(`new balance: ${res.balance}`);
  } catch (e) {
    lsmp.warn(`withdraw failed: ${e.code}`);
  }
}

lsmp.callClient

ServerLua Β· JS
luaLua
lsmp.callClient(playerId, name, ... [, cb]) --> any, err
jsJavaScript
lsmp.callClient(playerId: number, name: string | CallOptions, ...args: Value[]): Promise<Value>

Calls the handler of a name on one player's client and returns its result. Asynchronous.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player whose client is called.
nameevent | CallOptionsThe name, or { name, timeoutMs }.
...args optvalueUp to 32 transportable values.
Returns (Lua)any, err: The client handler's result.
Returns (JavaScript)Promise<Value>: The client handler's result.
β„Ή
Sizes

The request can be up to 16 MiB encoded; the answer from the client up to 4 MiB βˆ’ 1 KiB.

Example
luaLua
-- client
lsmp.onCall("ui:confirm", function(question)
  return showConfirmDialog(question) -- your own function, may suspend
end)

-- server, in a host coroutine
local yes, err = lsmp.callClient(playerId, { name = "ui:confirm", timeoutMs = 30000 }, "Sell your car?")
if yes then sellCar(playerId) end
jsJavaScript
// client
lsmp.onCall("ui:confirm", async (question) => showConfirmDialog(question));

// server
async function askToSell(playerId) {
  const yes = await lsmp.callClient(playerId, { name: "ui:confirm", timeoutMs: 30000 }, "Sell your car?");
  if (yes) sellCar(playerId);
}
Shared Β· Lua & JS

Logging, timers, hashing, JSON, resources

Logging, timers and threads, clocks, hashing, random bytes, JSON for Lua, and information about resources.

Small tools every resource uses: logging, timers and threads, clocks, hashing (lsmp.hash), random bytes, JSON (Lua) and information about resources. They exist on the server and on the client, with the same behaviour.

Logging

Every line is written to the console of the side that logs (server console and admin panel, or the client console), prefixed with the resource name. In Lua, print is lsmp.log. In JavaScript, console.log/console.info go to lsmp.log, console.warn to lsmp.warn, console.error to lsmp.error and console.debug to lsmp.debug.

lsmp.log

SharedLua Β· JS
luaLua
lsmp.log(...)
jsJavaScript
lsmp.log(...values: any[]): void

Writes an information line.

Parameters
ParameterTypeDescription
...values optanyValues to write, separated by a tab. Strings are written as they are.
Example
luaLua
lsmp.log("players online:", #lsmp.getPlayers())
jsJavaScript
lsmp.log("players online:", lsmp.getPlayers().length);

lsmp.warn

SharedLua Β· JS
luaLua
lsmp.warn(...)
jsJavaScript
lsmp.warn(...values: any[]): void

Writes a warning line.

Parameters
ParameterTypeDescription
...values optanyValues to write, separated by a tab. Strings are written as they are.

lsmp.error

SharedLua Β· JS
luaLua
lsmp.error(...)
jsJavaScript
lsmp.error(...values: any[]): void

Writes an error line. It does not raise.

Parameters
ParameterTypeDescription
...values optanyValues to write, separated by a tab. Strings are written as they are.

lsmp.debug

SharedLua Β· JS
luaLua
lsmp.debug(...)
jsJavaScript
lsmp.debug(...values: any[]): void

Writes a debug line, hidden unless the resource's level is "debug".

Parameters
ParameterTypeDescription
...values optanyValues to write, separated by a tab. Strings are written as they are.

lsmp.setLogLevel

SharedLua Β· JS
luaLua
lsmp.setLogLevel(level)
jsJavaScript
lsmp.setLogLevel(level: string): void

Sets the lowest level written for this resource only.

Errors raised by the resource's handlers are always written, whatever the level.

Parameters
ParameterTypeDescription
levelstring"debug", "info" (default), "warn", "error" or "off".
Example
luaLua
lsmp.setLogLevel("debug")
jsJavaScript
lsmp.setLogLevel("debug");

lsmp.getLogLevel

SharedLua Β· JS
luaLua
lsmp.getLogLevel() --> string
jsJavaScript
lsmp.getLogLevel(): string

The current level of this resource ("info" by default).

Returnsstring

Errors

lsmp.getLastError

SharedLua Β· JS
luaLua
lsmp.getLastError() --> string?
jsJavaScript
lsmp.getLastError(): string | null

The failure code of the last synchronous lsmp call of this resource that failed, or nil/null if the last such call succeeded.

Each call that can fail resets it. In Lua the code is also the second return value of the failing call, so this function is mostly for JavaScript, where a failed action only returns false or null. See Error codes.

Returns (Lua)string?: A code such as "not-found" or "permission".
Returns (JavaScript)string | null: A code such as "not-found" or "permission".
Example
luaLua
local ok = lsmp.deleteEntity(netId)
if not ok then lsmp.warn(lsmp.getLastError()) end
jsJavaScript
if (!lsmp.deleteEntity(netId)) lsmp.warn(lsmp.getLastError());

Threads and waiting

lsmp.wait

SharedLua Β· JS
luaLua
lsmp.wait([ms])
jsJavaScript
lsmp.wait(ms: number = 0): Promise<void>

Waits for a number of milliseconds.

Lua: suspends the current host coroutine (a file body, an event or RPC handler, a lsmp.createThread function); 0 waits for the next tick. Called elsewhere, it raises. JavaScript: returns a Promise that resolves after ms; use it with await.

Parameters
ParameterTypeDescription
ms optmsMilliseconds to wait. Default: 0
Example
luaLua
lsmp.createThread(function()
  while true do
    lsmp.emitAllClients("clock:tick", lsmp.nowMs())
    lsmp.wait(60000)
  end
end)
jsJavaScript
(async () => {
  for (;;) {
    lsmp.emitAllClients("clock:tick", lsmp.nowMs());
    await lsmp.wait(60000);
  }
})();

lsmp.createThread

SharedLua
luaLua
lsmp.createThread(fn, ...)

Lua only: runs fn(...) in a new coroutine, right now, until it first waits.

The thread can call lsmp.wait and asynchronous functions without a callback. An error inside it is logged with the resource name and never reaches the caller. In JavaScript, use an async function.

Not available in JavaScript.

Parameters
ParameterTypeDescription
fnfnThe thread body.
...args optanyArguments passed to fn.

Timers

The standard timer functions are globals in every context. A timer belongs to its resource and is cancelled when the resource stops. clearTimeout and clearInterval are the same function.

setTimeout

SharedLua Β· JS
luaLua
setTimeout(fn [, ms, ...]) --> integer
jsJavaScript
setTimeout(fn: Function, ms: number = 0, ...args: any[]): number

Calls fn(...args) once after ms milliseconds.

Parameters
ParameterTypeDescription
fnfnThe callback.
ms optmsDelay. 0 runs it at the next turn. Default: 0
...args optanyArguments passed to fn.
Returns (Lua)integer: The timer id (an integer above 0, unique in the resource; a Node Timeout object in JavaScript on the server).
Returns (JavaScript)number: The timer id (an integer above 0, unique in the resource; a Node Timeout object in JavaScript on the server).
Example
luaLua
local id = setTimeout(function(name) lsmp.log("hello " .. name) end, 1000, "world")
jsJavaScript
const id = setTimeout((name) => lsmp.log(`hello ${name}`), 1000, "world");

setInterval

SharedLua Β· JS
luaLua
setInterval(fn [, ms, ...]) --> integer
jsJavaScript
setInterval(fn: Function, ms: number = 1, ...args: any[]): number

Calls fn(...args) every ms milliseconds.

The next call is planned from the end of the previous one, so a slow server never gets a burst of late calls. The period is at least 1 ms.

Parameters
ParameterTypeDescription
fnfnThe callback.
ms optmsPeriod. Default: 1
...args optanyArguments passed to fn.
Returns (Lua)integer: The timer id.
Returns (JavaScript)number: The timer id.

clearTimeout

SharedLua Β· JS
luaLua
clearTimeout([id])
jsJavaScript
clearTimeout(id?: number): void

Cancels a timer of this resource.

An unknown id, or the id of another resource's timer, does nothing.

Parameters
ParameterTypeDescription
id optintegerThe timer id. A missing id does nothing.

clearInterval

SharedLua Β· JS
luaLua
clearInterval([id])
jsJavaScript
clearInterval(id?: number): void

Same function as clearTimeout.

Parameters
ParameterTypeDescription
id optintegerThe timer id. A missing id does nothing.

lsmp.onTick

ClientLua Β· JS
luaLua
lsmp.onTick(fn) --> function
jsJavaScript
lsmp.onTick(fn: Function): () => boolean

Calls fn every game frame with the milliseconds since the previous frame.

For drawing and per-frame input only: keep it short. The first call receives 0. A tick handler cannot suspend (use lsmp.createThread or an async function). It is disabled after 8 errors in a row.

Parameters
ParameterTypeDescription
fnfnfn(dtMs).
Returns (Lua)function: The unsubscribe function.
Returns (JavaScript)() => boolean: The unsubscribe function.
Example
luaLua
lsmp.onTick(function(dtMs)
  drawText(0.5, 0.05, "FPS: " .. math.floor(1000 / math.max(dtMs, 1)))
end)
jsJavaScript
lsmp.onTick((dtMs) => {
  drawText(0.5, 0.05, `FPS: ${Math.floor(1000 / Math.max(dtMs, 1))}`);
});

lsmp.offTick

ClientLua Β· JS
luaLua
lsmp.offTick(fn) --> boolean
jsJavaScript
lsmp.offTick(fn: Function): boolean

Removes a tick handler of this resource.

Parameters
ParameterTypeDescription
fnfnThe handler.
Returnsboolean: true if it was removed.

Clocks

lsmp.getTickCount

SharedLua Β· JS
luaLua
lsmp.getTickCount() --> integer
jsJavaScript
lsmp.getTickCount(): number

A monotonic clock in milliseconds. Only differences between two values mean something.

Returns (Lua)integer
Returns (JavaScript)number
Example
luaLua
local t0 = lsmp.getTickCount()
doWork()
lsmp.debug("took " .. (lsmp.getTickCount() - t0) .. " ms")
jsJavaScript
const t0 = lsmp.getTickCount();
doWork();
lsmp.debug(`took ${lsmp.getTickCount() - t0} ms`);

lsmp.nowMs

SharedLua Β· JS
luaLua
lsmp.nowMs() --> integer
jsJavaScript
lsmp.nowMs(): number

The wall-clock time in milliseconds since the Unix epoch.

Use it for timestamps you store or send (untilMs, atMs...).

Returns (Lua)integer
Returns (JavaScript)number

Hashing and random

lsmp.hash

SharedLua Β· JS
luaLua
lsmp.hash(name) --> integer
jsJavaScript
lsmp.hash(name: string): number

The game hash of a name, unsigned (0..2^32-1).

ASCII letters are lower-cased first, so "ADDER" and "adder" give the same hash. It is the value the game uses for models, weapons and most names, and the same as the native getHashKey. Functions that take a hash also accept the name directly. lsmp.joaat is the same function, under the name of the algorithm (Jenkins one-at-a-time) that GTA modders know.

Parameters
ParameterTypeDescription
namestringThe name to hash.
Returns (Lua)integer
Returns (JavaScript)number
Example
luaLua
if lsmp.getEntityModel(netId) == lsmp.hash("adder") then
  lsmp.log("an Adder")
end
jsJavaScript
if (lsmp.getEntityModel(netId) === lsmp.hash("adder")) lsmp.log("an Adder");

lsmp.joaat

SharedLua Β· JS
luaLua
lsmp.joaat(name) --> integer
jsJavaScript
lsmp.joaat(name: string): number

Alias of lsmp.hash: same function, same result. Prefer lsmp.hash.

lsmp.randomBytes

SharedLua Β· JS
luaLua
lsmp.randomBytes(n) --> string
jsJavaScript
lsmp.randomBytes(n: number): Uint8Array

Cryptographically secure random bytes.

Use it for tokens, salts and identifiers that must not be guessed. math.random and Math.random are predictable.

Parameters
ParameterTypeDescription
nintegerNumber of bytes, 1 to 65 536.
Returns (Lua)string: The bytes.
Returns (JavaScript)Uint8Array: The bytes.
Example
luaLua
local token = lsmp.randomBytes(16):gsub(".", function(c) return ("%02x"):format(c:byte()) end)
jsJavaScript
const token = Buffer.from(lsmp.randomBytes(16)).toString("hex"); // server (Node)

lsmp.bytes

SharedLua
luaLua
lsmp.bytes(s) --> Bytes

Lua only: marks a string as binary data, so it travels as bytes.

A JavaScript receiver then gets a Uint8Array instead of a string. A string that is not valid UTF-8 is always sent as bytes. See Transportable values.

Not available in JavaScript.

Parameters
ParameterTypeDescription
sstringThe data.
ReturnsBytes: A marked value to pass to emit, emitServer, emitClient, call, meta or storage.

JSON (Lua)

JavaScript has JSON. Lua uses these three functions, which map JSON null to lsmp.null.

lsmp.json.encode

SharedLua
luaLua
lsmp.json.encode(value [, opts]) --> string

Lua only: the JSON text of a value.

lsmp.null becomes null; an empty table becomes [] (use lsmp.json.array to be explicit, and a table with string keys for objects). A value that cannot be written (function, mixed keys) raises.

Not available in JavaScript.

Parameters
ParameterTypeDescription
valueanyThe value.
opts optJsonEncodeOptions{ pretty = false }: indented output.
Returnsstring
Example
luaLua
local text = lsmp.json.encode({ name = "Ada", tags = { "admin" } })

lsmp.json.decode

SharedLua
luaLua
lsmp.json.decode(text) --> value | nil, "invalid"

Lua only: parses JSON text.

Inside arrays null becomes lsmp.null (the length is kept); inside objects a null member is simply absent. Invalid text is not an error: the call returns nil, "invalid", { message }.

Not available in JavaScript.

Parameters
ParameterTypeDescription
textstringJSON text.
Returnsvalue | nil, "invalid"
Example
luaLua
local cfg, err, details = lsmp.json.decode(lsmp.readResourceFile("config.json"))
if not cfg then lsmp.error("bad config.json: " .. details.message) end

lsmp.json.array

SharedLua
luaLua
lsmp.json.array(t) --> table

Lua only: marks a table so json.encode writes it as an array, even when empty.

Not available in JavaScript.

Parameters
ParameterTypeDescription
ttableThe table.
Returnstable: The same table.

Resources

A resource is identified by its name: its folder name on the server. See Resource layout. Starting and stopping resources from a script is on the Server and resource lifecycle page.

lsmp.getResourceName

SharedLua Β· JS
luaLua
lsmp.getResourceName() --> string
jsJavaScript
lsmp.getResourceName(): string

The name of the calling resource.

Returnsstring

lsmp.getResourceState

SharedLua Β· JS
luaLua
lsmp.getResourceState(name) --> ResourceState?
jsJavaScript
lsmp.getResourceState(name: string): ResourceState | null

The state of a resource on this side.

Parameters
ParameterTypeDescription
namenameResource name.
Returns (Lua)ResourceState?: "starting", "started", "failed", "stopping" or "stopped"; nil/null if unknown.
Returns (JavaScript)ResourceState | null: "starting", "started", "failed", "stopping" or "stopped"; nil/null if unknown.
Example
luaLua
if lsmp.getResourceState("mysql-accounts") ~= "started" then
  lsmp.warn("accounts are not available")
end
jsJavaScript
if (lsmp.getResourceState("mysql-accounts") !== "started") lsmp.warn("accounts are not available");

lsmp.getResources

SharedLua Β· JS
luaLua
lsmp.getResources() --> {ResourceInfo}
jsJavaScript
lsmp.getResources(): ResourceInfo[]

Every resource known on this side, in load order.

Returns (Lua){ResourceInfo}: A list of { name, state }.
Returns (JavaScript)ResourceInfo[]: A list of { name, state }.

lsmp.readResourceFile

SharedLua Β· JS
luaLua
lsmp.readResourceFile(path [, opts]) --> string|string?
jsJavaScript
lsmp.readResourceFile(path: string, opts?: ReadFileOptions): string | Uint8Array | null

Reads a file of the calling resource's own package.

Use it for configuration, translations and templates shipped with the resource. The path is relative to the resource folder, with / separators; .. and absolute paths are refused, so a resource only reads its own files. Text (UTF-8) by default.

Parameters
ParameterTypeDescription
pathstringPath inside the resource, for example "config/shop.json".
opts optReadFileOptions{ binary = true } returns bytes (Uint8Array in JavaScript; Lua strings hold bytes anyway).
Returns (Lua)string?: The content, or nil/null if the file is not in the package.
Returns (JavaScript)string | Uint8Array | null: The content, or nil/null if the file is not in the package.
Example
luaLua
local prices = lsmp.json.decode(lsmp.readResourceFile("config/prices.json"))
jsJavaScript
const prices = JSON.parse(lsmp.readResourceFile("config/prices.json"));

lsmp.resourceFileExists

SharedLua Β· JS
luaLua
lsmp.resourceFileExists(path) --> boolean
jsJavaScript
lsmp.resourceFileExists(path: string): boolean

Whether the calling resource's package holds a file.

Parameters
ParameterTypeDescription
pathstringPath inside the resource.
Returnsboolean

lsmp.gameType

SharedLua Β· JS
luaLua
lsmp.gameType() --> string
jsJavaScript
lsmp.gameType(): string

The kind of session the script runs in.

"MP" on a server session. A client can also run resources in single player ("SP") or in a marketplace trial ("TRY").

Returnsstring

lsmp.getVersion

SharedLua Β· JS
luaLua
lsmp.getVersion() --> VersionInfo
jsJavaScript
lsmp.getVersion(): VersionInfo

Version information.

Returns (Lua)VersionInfo: { lsmp, game, gameBuild }: the LS:MP version, and on a client the game version and build number (nil/null on the server).
Returns (JavaScript)VersionInfo: { lsmp, game, gameBuild }: the LS:MP version, and on a client the game version and build number (nil/null on the server).

lsmp.ResourceState

SharedLua Β· JS
luaLua
lsmp.ResourceState
jsJavaScript
lsmp.ResourceState

The states a resource goes through.

lsmp.ResourceState.Starting = "starting" Β· lsmp.ResourceState.Started = "started" Β· lsmp.ResourceState.Failed = "failed" Β· lsmp.ResourceState.Stopping = "stopping" Β· lsmp.ResourceState.Stopped = "stopped"

Shared Β· Lua & JS

HTTP client

Call web services from a script: your own backend, a Discord webhook, a public API.

lsmp.http sends one request and gives back the response. The calls are asynchronous: JS gets a Promise, Lua suspends the calling handler or takes a callback (see Conventions).

A response arrives whatever its status: a 404 or a 500 is a response, check res.ok or res.status. A call fails only when no response came back at all.

ServerClient
Schemeshttps:// and http://https:// only
AddressesAny, unless the operator restricts the resource (sandbox)Public addresses only. localhost or a literal loopback, private or reserved IP in the URL raises RangeError at the call; a host name that resolves to such an address fails with permission.
Requests in flightSandboxed resource: 256; more fail with limit8 per resource (20 per second), 32 for the whole client, 128 MiB of response bodies held at once; more fail with limit
β„Ή
Server resources in the sandbox

A sandboxed server resource reaches only the destinations the operator allows in SandboxNetConnect (server.cfg). Anything else fails with permission. See Resource capabilities and sandbox.

Requests

lsmp.http.request

SharedLua Β· JS
luaLua
lsmp.http.request(opts [, cb]) --> HttpResponse, err
jsJavaScript
lsmp.http.request(opts: HttpRequest): Promise<HttpResponse>

Send a request with any method.

Every option of HttpRequest is accepted; url is required. A value the request cannot carry raises before anything is sent: a header or query value with a line break, a header the transport sets itself (Content-Length, Transfer-Encoding, Host, Connection), a body on GET or HEAD, an unknown method.

Parameters
ParameterTypeDescription
optsHttpRequestThe request: see HttpRequest.
Returns (Lua)HttpResponse, err: The response (see HttpResponse); nil and a failure code when no response came back.
Returns (JavaScript)Promise<HttpResponse>: Resolves with the HttpResponse; rejects with a failure code when no response came back.
Failure codeWhen
timeoutNo complete response within timeoutMs.
ioName resolution, connection, TLS or protocol error.
permissionDestination refused: on a client, a host name that resolves to a private or reserved address; on the server, outside the sandbox rules.
limitThe response body is larger than maxBytes.
errorWith responseType: "json", the body is not valid JSON. The status, headers and raw body come with the error (JS: err.status, err.headers, err.body; Lua: third return value).
Example
luaLua
local function uploadScore(player, score)
  local res, err = lsmp.http.request({
    url = "https://api.example.com/scores",
    method = "PUT",
    headers = { Authorization = "Bearer " .. TOKEN },
    json = { player = player, score = score },
    timeoutMs = 10000,
  })
  if not res then
    lsmp.warn("score upload failed: " .. err)
  elseif not res.ok then
    lsmp.warn("score upload refused: HTTP " .. res.status)
  end
end
jsJavaScript
async function uploadScore(player, score) {
  try {
    const res = await lsmp.http.request({
      url: 'https://api.example.com/scores',
      method: 'PUT',
      headers: { Authorization: `Bearer ${TOKEN}` },
      json: { player, score },
      timeoutMs: 10000,
    });
    if (!res.ok) lsmp.warn(`score upload refused: HTTP ${res.status}`);
  } catch (err) {
    lsmp.warn(`score upload failed: ${err.code}`);
  }
}

lsmp.http.get

SharedLua Β· JS
luaLua
lsmp.http.get(url [, opts] [, cb]) --> HttpResponse, err
jsJavaScript
lsmp.http.get(url: string, opts?: HttpRequest): Promise<HttpResponse>

Send a GET request.

Takes the options of HttpRequest except url, method, body and json: a body on a GET raises, it never turns the request into a POST. Same failure codes as request.

Parameters
ParameterTypeDescription
urlstringThe address, query string included or added with the query option.
opts optHttpRequestHeaders, query, timeout, response type...: see HttpRequest.
Returns (Lua)HttpResponse, err: The response, or nil and a failure code.
Returns (JavaScript)Promise<HttpResponse>: Resolves with the response; rejects with a failure code.
Example
luaLua
lsmp.registerCommand("motd", function()
  local res, err = lsmp.http.get("https://api.example.com/motd", {
    query = { lang = "en" },
    responseType = "json",
  })
  if res and res.ok then
    lsmp.log("message of the day: " .. res.body.text)
  else
    lsmp.warn("no message of the day: " .. (err or res.status))
  end
end)
jsJavaScript
lsmp.registerCommand('motd', async () => {
  try {
    const res = await lsmp.http.get('https://api.example.com/motd', {
      query: { lang: 'en' },
      responseType: 'json',
    });
    if (res.ok) lsmp.log(`message of the day: ${res.body.text}`);
  } catch (err) {
    lsmp.warn(`no message of the day: ${err.code}`);
  }
});

lsmp.http.post

SharedLua Β· JS
luaLua
lsmp.http.post(url [, opts] [, cb]) --> HttpResponse, err
jsJavaScript
lsmp.http.post(url: string, opts?: HttpRequest): Promise<HttpResponse>

Send a POST request.

Takes the options of HttpRequest except url and method. Give the body with body (text or bytes) or json (any value, encoded for you with Content-Type: application/json). Same failure codes as request.

Parameters
ParameterTypeDescription
urlstringThe address.
opts optHttpRequestBody, headers, timeout...: see HttpRequest.
Returns (Lua)HttpResponse, err: The response, or nil and a failure code.
Returns (JavaScript)Promise<HttpResponse>: Resolves with the response; rejects with a failure code.
Example
luaLua
-- A message in a Discord channel, through a webhook.
local res, err = lsmp.http.post(WEBHOOK_URL, {
  json = { content = "Server restarting in 5 minutes" },
})
if not res then lsmp.warn("webhook: " .. err) end
jsJavaScript
// A message in a Discord channel, through a webhook.
lsmp.http.post(WEBHOOK_URL, { json: { content: 'Server restarting in 5 minutes' } })
  .catch((err) => lsmp.warn(`webhook: ${err.code}`));

Shapes

HttpRequest

An unknown option name raises, with a suggestion when it is close to a real one.

FieldTypeDefaultDescription
urlstringβ€”Required for request. https://... (http:// on the server only). No spaces or control characters.
methodstring"GET"GET, POST, PUT, PATCH, DELETE, HEAD or OPTIONS. request only.
headerstableβ€”Header names to values. A value is a string or a finite number.
querytableβ€”Parameters added to the URL, encoded for you. Values: strings or finite numbers.
bodystring | bytesβ€”Raw request body. Not with json, never on GET/HEAD.
jsonvalueβ€”A value sent as JSON, with Content-Type: application/json unless you set one.
timeoutMsms30000Whole request, 1 to 300000.
responseTypestring"text""text" (a string), "bytes" (JS Uint8Array, Lua string) or "json" (the decoded value).
followRedirectsbooleantrueFollow 3xx redirections.
http3booleanfalseTry HTTP/3 first.
maxBytesint67108864Largest response body accepted (64 MiB at most). Larger: failure limit.

HttpResponse

FieldTypeDefaultDescription
okbooleanβ€”true for a status from 200 to 299.
statusintβ€”The HTTP status.
statusTextstringβ€”The reason phrase sent by the server, possibly empty.
headerstableβ€”Header names in lower case. A repeated header is joined with ", ", except set-cookie, which is a list.
bodystring | bytes | valueβ€”As asked by responseType.
urlstringβ€”The address that was requested (query included).

Good to know

  • Secrets stay on the server. A token written in a client script is readable by every player: call authenticated services from a server script, and let clients ask the server.
  • A response is not a success. Always look at res.ok or res.status before using the body.
  • One request, one answer. There is no streaming: the whole body is received, up to maxBytes, before the call returns.
  • To answer HTTP requests instead of sending them, see HTTP routes.
Shared Β· Lua & JS

Players

Who is connected, what they are called, which account they play with, and where their ped is.

Every connected player has a playerId: a small number for the length of their session. It identifies the player in every function, event and network message. When the player leaves, the number is given to the next player who joins.

To remember a player beyond a session (money, a character, a ban), use their account: the lsmpId. Guests have no account.

IdentifierLivesUse it for
playerIdOne session. Reused after the player leaves.Every API call, events, network messages.
lsmpIdForever. The same on every server.Saved data, bans, permissions. nil/null for a guest.
NameChosen by the player, may change.Display only. Never a key.
⚠
Is the account real?

A player's lsmpId is proven only when the server verifies its players ("Verify players with LS:MP" in the admin panel, see server.cfg). Without verification it is what the client declares: fine for display and statistics, not for anything a cheater would want to steal. See Admission and moderation.

Listing players

lsmp.getPlayers

SharedLua Β· JS
luaLua
lsmp.getPlayers() --> {integer}
jsJavaScript
lsmp.getPlayers(): number[]

Every player, by playerId, in ascending order.

On the server: the connected players. On a client: the players of the session this client knows, the local player included. A new list on each call.

Returns (Lua){integer}: A list of playerIds, possibly empty.
Returns (JavaScript)number[]: A list of playerIds, possibly empty.
Example
luaLua
for _, id in ipairs(lsmp.getPlayers()) do
  lsmp.log(id, lsmp.getPlayerName(id))
end
jsJavaScript
for (const id of lsmp.getPlayers()) {
  lsmp.log(id, lsmp.getPlayerName(id));
}

lsmp.playerExists

SharedLua Β· JS
luaLua
lsmp.playerExists(playerId) --> boolean
jsJavaScript
lsmp.playerExists(playerId: number): boolean

Whether a playerId is in use.

On the server, true while the player is connected; on a client, while the player is in the session. Inside a playerLeave handler it is already false for the leaving player, even though their name and account can still be read.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player to test.
Returnsboolean: true if the player is there.

Name and account

lsmp.getPlayerName

SharedLua Β· JS
luaLua
lsmp.getPlayerName(playerId) --> string?
jsJavaScript
lsmp.getPlayerName(playerId: number): string | null

The name a player connected with.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returns (Lua)string?: The name, or nil/null if the player is unknown.
Returns (JavaScript)string | null: The name, or nil/null if the player is unknown.

lsmp.getPlayerLsmpId

SharedLua Β· JS
luaLua
lsmp.getPlayerLsmpId(playerId) --> integer?
jsJavaScript
lsmp.getPlayerLsmpId(playerId: number): number | null

The LS:MP account of a player, as a number.

The same number on every server and every session: key saved data on it.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returns (Lua)integer?: The account number, or nil/null for a guest or an unknown player.
Returns (JavaScript)number | null: The account number, or nil/null for a guest or an unknown player.
Example
luaLua
lsmp.on("playerJoin", function(playerId, name)
  local account = lsmp.getPlayerLsmpId(playerId)
  if account then
    lsmp.log(name .. " plays with account " .. account)
  else
    lsmp.log(name .. " is a guest")
  end
end)
jsJavaScript
lsmp.on('playerJoin', (playerId, name) => {
  const account = lsmp.getPlayerLsmpId(playerId);
  if (account !== null) lsmp.log(`${name} plays with account ${account}`);
  else lsmp.log(`${name} is a guest`);
});

lsmp.isPlayerGuest

SharedLua Β· JS
luaLua
lsmp.isPlayerGuest(playerId) --> boolean?
jsJavaScript
lsmp.isPlayerGuest(playerId: number): boolean | null

Whether a player has no LS:MP account.

Compare with false to test for a registered player: nil/null means the player is unknown, not registered.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returns (Lua)boolean?: true for a guest, false for a registered player, nil/null if the player is unknown.
Returns (JavaScript)boolean | null: true for a guest, false for a registered player, nil/null if the player is unknown.

lsmp.getLsmpAvatarUrl

SharedLua Β· JS
luaLua
lsmp.getLsmpAvatarUrl(playerId) --> string?
jsJavaScript
lsmp.getLsmpAvatarUrl(playerId: number): string | null

The versioned profile avatar shared by a player.

On the server, reads the reference shared by the connected player. On the client, only the local player can be queried, and the same consent applies. Guests, missing avatars, disconnected players and players who decline sharing return nil/null. A consent change to off clears the reference for the current session. To share again, reconnect. Use a default icon when the result is absent or the image fails to load.

Parameters
ParameterTypeDescription
playerIdplayerIdThe current player handle. On the client, pass the result of lsmp.getLocalPlayer().
Returns (Lua)string?: An absolute HTTPS URL for the current avatar version, or nil/null when unavailable.
Returns (JavaScript)string | null: An absolute HTTPS URL for the current avatar version, or nil/null when unavailable.

lsmp.isPlayerDev

SharedLua Β· JS
luaLua
lsmp.isPlayerDev(playerId) --> boolean?
jsJavaScript
lsmp.isPlayerDev(playerId: number): boolean | null

Whether a player has developer status (DevTools allowed).

On a client, only the local player is known: for anybody else the answer is nil/null. Developer status is given with setPlayerDev.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returns (Lua)boolean?: true or false, or nil/null if the player is unknown.
Returns (JavaScript)boolean | null: true or false, or nil/null if the player is unknown.

lsmp.getPlayerDimension

SharedLua Β· JS
luaLua
lsmp.getPlayerDimension(playerId) --> integer?
jsJavaScript
lsmp.getPlayerDimension(playerId: number): number | null

The dimension a player is in.

A client knows the dimension of every player of its session. Moving players between dimensions is on the Dimensions page.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returns (Lua)integer?: The dimension, or nil/null if the player is unknown.
Returns (JavaScript)number | null: The dimension, or nil/null if the player is unknown.

Identifiers (server)

Identifiers describe how a player connected. lsmp (the account, as a string) and name are always readable. ip (the address of the game connection) and hwid (a fingerprint of the machine) are private: they need the players.identity capability.

lsmp.getPlayerIdentifier

ServerLua Β· JS
luaLua
lsmp.getPlayerIdentifier(playerId, type) --> string?
jsJavaScript
lsmp.getPlayerIdentifier(playerId: number, type: string): string | null

One identifier of a connected player.

Can fail at run time: see error codes.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
typestring"lsmp", "name", "ip" or "hwid".
Returns (Lua)string?: The identifier as a string, or nil/null if the player is unknown, has no such identifier (a guest has no lsmp), or the capability is missing.
Returns (JavaScript)string | null: The identifier as a string, or nil/null if the player is unknown, has no such identifier (a guest has no lsmp), or the capability is missing.
Failure codeWhen
permission"ip" or "hwid" without the players.identity capability.

lsmp.getPlayerIdentifiers

ServerLua Β· JS
luaLua
lsmp.getPlayerIdentifiers(playerId) --> table?
jsJavaScript
lsmp.getPlayerIdentifiers(playerId: number): table | null

Every identifier of a connected player, as one table.

{ lsmp, name, ip, hwid }. A type the player does not have is absent; ip and hwid are absent without the players.identity capability.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returns (Lua)table?: The identifiers, or nil/null if the player is unknown.
Returns (JavaScript)table | null: The identifiers, or nil/null if the player is unknown.
Example
luaLua
local ids = lsmp.getPlayerIdentifiers(source)
if ids then
  for kind, value in pairs(ids) do
    lsmp.log(kind, value)
  end
end
jsJavaScript
const ids = lsmp.getPlayerIdentifiers(source);
if (ids) {
  for (const [kind, value] of Object.entries(ids)) lsmp.log(kind, value);
}

The player's ped

The ped is the character a player walks around with. The server and a client name it differently: the server uses its netId, a client its game handle (what natives take). See Entities and streaming for the difference.

lsmp.getPlayerPed

ServerLua Β· JS
luaLua
lsmp.getPlayerPed(playerId) --> integer?
jsJavaScript
lsmp.getPlayerPed(playerId: number): number | null

The netId of a player's ped.

A player has no ped before their first spawn.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returns (Lua)integer?: The netId, or nil/null if the player has no ped yet or is unknown.
Returns (JavaScript)number | null: The netId, or nil/null if the player has no ped yet or is unknown.
Example
luaLua
local ped = lsmp.getPlayerPed(playerId)
local pos = ped and lsmp.getEntityCoords(ped)
if pos then
  lsmp.log(("player %d is at %.1f, %.1f, %.1f"):format(playerId, pos.x, pos.y, pos.z))
end
jsJavaScript
const ped = lsmp.getPlayerPed(playerId);
const pos = ped !== null ? lsmp.getEntityCoords(ped) : null;
if (pos) lsmp.log(`player ${playerId} is at ${pos.x.toFixed(1)}, ${pos.y.toFixed(1)}, ${pos.z.toFixed(1)}`);

lsmp.getPlayerPed

ClientLua Β· JS
luaLua
lsmp.getPlayerPed(playerId) --> integer?
jsJavaScript
lsmp.getPlayerPed(playerId: number): number | null

The game handle of a player's ped, while it exists on this client.

A player far away is not streamed on this client and has no ped here. For the local player, the native playerPedId() gives the same handle.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returns (Lua)integer?: The game handle, or nil/null while the ped is not on this client.
Returns (JavaScript)number | null: The game handle, or nil/null while the ped is not on this client.

Events

playerJoin and playerLeave fire on both sides when a player arrives and leaves. On a client, playerJoin is not fired for the local player (use lsmp.getLocalPlayer()), and the detail of playerLeave is always nil/null. The events are not replayed: a script that starts while players are connected reads lsmp.getPlayers() once, then follows the events.

luaLua
local online = {}

-- Players already here when the resource starts.
for _, id in ipairs(lsmp.getPlayers()) do
  online[id] = lsmp.getPlayerName(id)
end

lsmp.on("playerJoin", function(playerId, name)
  online[playerId] = name
end)

lsmp.on("playerLeave", function(playerId, name, reason)
  online[playerId] = nil
  lsmp.log(name .. " left (" .. reason .. ")")
end)
jsJavaScript
const online = new Map();

// Players already here when the resource starts.
for (const id of lsmp.getPlayers()) online.set(id, lsmp.getPlayerName(id));

lsmp.on('playerJoin', (playerId, name) => {
  online.set(playerId, name);
});

lsmp.on('playerLeave', (playerId, name, reason) => {
  online.delete(playerId);
  lsmp.log(`${name} left (${reason})`);
});
Shared Β· Lua & JS

Meta (replicated key/values)

Small values attached to players, entities or the session, replicated to every client.

Meta are small key/value pairs attached to a player, an entity, or the whole session (global). The server replicates them to every client: one write, and every script on every machine can read the value. Use them for state that clients display or react to: a job, a team, a vehicle's fuel, a door's lock.

ScopeReadWritten byLives until
playereverywhere, getPlayerMetaserver scripts; a client for its own playerthe player leaves
entityeverywhere, getEntityMetaserver scripts; the client that owns (simulates) the entitythe entity is deleted
globaleverywhere, getGlobalMetaserver scripts onlythe server stops
  • Values are copied: reading returns a new copy, and changing it does nothing until you write it back.
  • Writing the same value again does nothing (no network traffic, no event).
  • Every change fires the metaChange engine event on the server and on clients. Filter it by scope, key and target.
  • Meta are not saved. To keep data across sessions, store it with storage or MySQL and restore it on playerJoin. See Storing data.
  • Keys starting with lsmp: belong to LS:MP: they read as absent and writing them raises.
βœ•
Client writes

A client can write its own player's meta and the meta of entities it simulates. Never trust such values on the server for anything that matters (money, rights): keep authoritative values in server-written meta, and check the source of metaChange.

luaLua
-- server: give a job
lsmp.setPlayerMeta(playerId, "job", { name = "police", grade = 2 })

-- client: react to it
lsmp.on("metaChange", function(scope, target, key, value)
  if value then lsmp.log("job: " .. value.name) end
end, { scope = "player", key = "job" })
jsJavaScript
// server: give a job
lsmp.setPlayerMeta(playerId, "job", { name: "police", grade: 2 });

// client: react to it
lsmp.on("metaChange", (scope, target, key, value) => {
  if (value) lsmp.log(`job: ${value.name}`);
}, { scope: "player", key: "job" });

Reading

lsmp.getPlayerMeta

SharedLua Β· JS
luaLua
lsmp.getPlayerMeta(playerId, key) --> any?
jsJavaScript
lsmp.getPlayerMeta(playerId: number, key: string): Value | null

A player's meta value.

Still readable inside playerLeave handlers for the leaving player.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
keystringKey: 1 to 128 bytes of UTF-8, not starting with lsmp:.
Returns (Lua)any?: The value, or nil/null if absent or if the player is unknown.
Returns (JavaScript)Value | null: The value, or nil/null if absent or if the player is unknown.
Example
luaLua
local job = lsmp.getPlayerMeta(playerId, "job")
if job and job.name == "police" then openArmory(playerId) end
jsJavaScript
const job = lsmp.getPlayerMeta(playerId, "job");
if (job?.name === "police") openArmory(playerId);

lsmp.getEntityMeta

SharedLua Β· JS
luaLua
lsmp.getEntityMeta(netId, key) --> any?
jsJavaScript
lsmp.getEntityMeta(netId: number, key: string): Value | null

An entity's meta value.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
keystringKey: 1 to 128 bytes of UTF-8, not starting with lsmp:.
Returns (Lua)any?: The value, or nil/null if absent or if the entity is unknown.
Returns (JavaScript)Value | null: The value, or nil/null if absent or if the entity is unknown.

lsmp.getGlobalMeta

SharedLua Β· JS
luaLua
lsmp.getGlobalMeta(key) --> any?
jsJavaScript
lsmp.getGlobalMeta(key: string): Value | null

A global meta value.

Parameters
ParameterTypeDescription
keystringKey: 1 to 128 bytes of UTF-8, not starting with lsmp:.
Returns (Lua)any?: The value, or nil/null if absent.
Returns (JavaScript)Value | null: The value, or nil/null if absent.

Writing on the server

lsmp.setPlayerMeta

ServerLua Β· JS
luaLua
lsmp.setPlayerMeta(playerId, key, value) --> boolean
jsJavaScript
lsmp.setPlayerMeta(playerId: number, key: string, value: Value): boolean

Sets or deletes a player's meta value, replicated to every client.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
keystringKey: 1 to 128 bytes of UTF-8, not starting with lsmp:.
valuevalueAny transportable value up to 8192 bytes encoded. nil/null deletes the key.
Returnsboolean: false (not-found) if the player is unknown.

lsmp.setEntityMeta

ServerLua Β· JS
luaLua
lsmp.setEntityMeta(netId, key, value) --> boolean
jsJavaScript
lsmp.setEntityMeta(netId: number, key: string, value: Value): boolean

Sets or deletes an entity's meta value, replicated to every client.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
keystringKey: 1 to 128 bytes of UTF-8, not starting with lsmp:.
valuevalueAny transportable value up to 8192 bytes encoded. nil/null deletes the key.
Returnsboolean: false (not-found) if the entity is unknown.
Example
luaLua
lsmp.setEntityMeta(car, "fuel", 0.75)
lsmp.setEntityMeta(car, "locked", true)
jsJavaScript
lsmp.setEntityMeta(car, "fuel", 0.75);
lsmp.setEntityMeta(car, "locked", true);

lsmp.setGlobalMeta

ServerLua Β· JS
luaLua
lsmp.setGlobalMeta(key, value) --> boolean
jsJavaScript
lsmp.setGlobalMeta(key: string, value: Value): boolean

Sets or deletes a global meta value, replicated to every client.

Parameters
ParameterTypeDescription
keystringKey: 1 to 128 bytes of UTF-8, not starting with lsmp:.
valuevalueAny transportable value up to 8192 bytes encoded. nil/null deletes the key.
Returnsboolean: true when done.
Example
luaLua
lsmp.setGlobalMeta("event:active", "carnival")
jsJavaScript
lsmp.setGlobalMeta("event:active", "carnival");

Writing on a client

A client writes only what it owns. Its writes reach the server and the other clients, and are limited by the server (MetaMaxKeys, MetaMaxBlobBytes, MetaWriteBytesPerSec; see Limits).

lsmp.setPlayerMeta

ClientLua Β· JS
luaLua
lsmp.setPlayerMeta(playerId, key, value) --> boolean
jsJavaScript
lsmp.setPlayerMeta(playerId: number, key: string, value: Value): boolean

Sets or deletes a meta value on the local player.

Parameters
ParameterTypeDescription
playerIdplayerIdMust be the local player.
keystringKey: 1 to 128 bytes of UTF-8, not starting with lsmp:.
valuevalueAny transportable value up to 8192 bytes encoded. nil/null deletes the key.
Returnsboolean: false with disconnected (not in a session) or limit (server budget or rate).

lsmp.setEntityMeta

ClientLua Β· JS
luaLua
lsmp.setEntityMeta(netId, key, value) --> boolean
jsJavaScript
lsmp.setEntityMeta(netId: number, key: string, value: Value): boolean

Sets or deletes a meta value on an entity this client owns.

Parameters
ParameterTypeDescription
netIdnetIdAn entity simulated by this client.
keystringKey: 1 to 128 bytes of UTF-8, not starting with lsmp:.
valuevalueAny transportable value up to 8192 bytes encoded. nil/null deletes the key.
Returnsboolean: false with permission (not the owner), not-found, disconnected or limit.
Shared Β· Lua & JS

Spatial queries

Find the closest player or entity, or every entity within a radius.

Find players and networked entities around a position. On the server the search covers every entity of one dimension (the default world unless you pass dimension). On a client it covers the entities this client knows, which are the ones streamed around the player; the dimension option does not apply there.

Distances are measured in 3D, in meters, from the last synchronized positions.

Options

FieldTypeDefaultDescription
maxRadiusmeters0getClosestPlayer, getClosestEntity: ignore anything farther. 0 means no limit.
typeslist of stringsallgetClosestEntity, getEntitiesInRadius: any of "vehicle", "ped", "object", "playerPed".
dimensiondimension0Server only: the dimension to search.

Functions

lsmp.getClosestPlayer

SharedLua Β· JS
luaLua
lsmp.getClosestPlayer(position [, opts]) --> integer?
jsJavaScript
lsmp.getClosestPlayer(position: Vec3Like, opts?: ClosestOptions): number | null

The player whose ped is closest to a position.

On a client the local player is included: exclude it yourself if needed.

Parameters
ParameterTypeDescription
positionvec3The center of the search.
opts optClosestOptions{ maxRadius, dimension }.
Returns (Lua)integer?: A playerId, or nil/null if none.
Returns (JavaScript)number | null: A playerId, or nil/null if none.
Example
luaLua
local target = lsmp.getClosestPlayer(lsmp.getEntityCoords(lsmp.getPlayerPed(source)), { maxRadius = 3.0 })
jsJavaScript
const target = lsmp.getClosestPlayer(lsmp.getEntityCoords(lsmp.getPlayerPed(source)), { maxRadius: 3 });

lsmp.getClosestEntity

SharedLua Β· JS
luaLua
lsmp.getClosestEntity(position [, opts]) --> integer?
jsJavaScript
lsmp.getClosestEntity(position: Vec3Like, opts?: ClosestOptions): number | null

The networked entity closest to a position.

Parameters
ParameterTypeDescription
positionvec3The center of the search.
opts optClosestOptions{ types, maxRadius, dimension }.
Returns (Lua)integer?: A netId, or nil/null if none.
Returns (JavaScript)number | null: A netId, or nil/null if none.
Example
luaLua
local car = lsmp.getClosestEntity(position, { types = { "vehicle" }, maxRadius = 10.0 })
jsJavaScript
const car = lsmp.getClosestEntity(position, { types: ["vehicle"], maxRadius: 10 });

lsmp.getEntitiesInRadius

SharedLua Β· JS
luaLua
lsmp.getEntitiesInRadius(position, radius [, opts]) --> {integer}
jsJavaScript
lsmp.getEntitiesInRadius(position: Vec3Like, radius: number, opts?: QueryOptions): Uint32Array

Every networked entity within a radius.

Parameters
ParameterTypeDescription
positionvec3The center of the search.
radiusmetersSearch radius.
opts optQueryOptions{ types, dimension }.
Returns (Lua){integer}: The netIds, in no particular order. A Uint32Array in JavaScript: use for...of or Array.from.
Returns (JavaScript)Uint32Array: The netIds, in no particular order. A Uint32Array in JavaScript: use for...of or Array.from.
Example
luaLua
for _, netId in ipairs(lsmp.getEntitiesInRadius(position, 25.0, { types = { "ped" } })) do
  lsmp.setEntityIntent(netId, { type = "flee", target = "nearestPlayer" })
end
jsJavaScript
for (const netId of lsmp.getEntitiesInRadius(position, 25, { types: ["ped"] })) {
  lsmp.setEntityIntent(netId, { type: "flee", target: "nearestPlayer" });
}
Shared Β· Lua & JS

Weather and time

One sky for the whole server: a random weather cycle every player sees the same way, that scripts can override.

The server runs a weather cycle: segments of a few minutes each, chosen at random from a seed, joined by smooth transitions. Every client computes the same cycle, so all players see the same sky at the same moment, without any traffic.

A server script can force a weather for a while, then hand back to the cycle. A client script can give its own player a different sky, for a cutscene or an interior, without changing anybody else's.

The game clock is shared the same way: every player has the same time of day, and it runs on its own (one game day lasts 48 real minutes). Clock natives that set the time have no effect during a session.

β„Ή
One forced weather at a time

The forced weather belongs to the resource that set it. When that resource stops, the weather goes back to what was there before: the weather forced by another resource, or the cycle. A weather forced on the client works the same way, per resource.

Reading the weather

lsmp.weather.get

SharedLua Β· JS
luaLua
lsmp.weather.get() --> WeatherState?
jsJavaScript
lsmp.weather.get(): WeatherState | null

The synchronized weather at this moment.

See WeatherState. On a client, nil/null until the first state arrived from the server, a moment after connecting.

Returns (Lua)WeatherState?: The current state.
Returns (JavaScript)WeatherState | null: The current state.
Example
luaLua
local w = lsmp.weather.get()
if w then
  lsmp.log("weather: " .. w.type .. (w.forced and " (forced)" or ""))
  if w.next then
    lsmp.log(("next: %s in %d s"):format(w.next, w.nextChangeMs // 1000))
  end
end
jsJavaScript
const w = lsmp.weather.get();
if (w) {
  lsmp.log(`weather: ${w.type}${w.forced ? ' (forced)' : ''}`);
  if (w.next) lsmp.log(`next: ${w.next} in ${Math.floor(w.nextChangeMs / 1000)} s`);
}

lsmp.weather.getForecast

SharedLua Β· JS
luaLua
lsmp.weather.getForecast([count]) --> {WeatherForecastEntry}
jsJavaScript
lsmp.weather.getForecast(count: number = 6): WeatherForecastEntry[]

The next changes of the weather cycle.

Each entry is a WeatherForecastEntry. While a weather is forced, the forecast shows the cycle that resumes after it.

Parameters
ParameterTypeDescription
count optintHow many upcoming changes, 1 to 32. Default: 6
Returns (Lua){WeatherForecastEntry}: The upcoming changes, soonest first.
Returns (JavaScript)WeatherForecastEntry[]: The upcoming changes, soonest first.

lsmp.weather.getTypes

SharedLua Β· JS
luaLua
lsmp.weather.getTypes() --> {string}
jsJavaScript
lsmp.weather.getTypes(): string[]

The weather names set and setLocal accept.

For example "EXTRASUNNY", "RAIN", "THUNDER", "SNOW", "XMAS", "HALLOWEEN". Names are upper case.

Returns (Lua){string}: Every weather name.
Returns (JavaScript)string[]: Every weather name.

Forcing the weather (server)

lsmp.weather.set

ServerLua Β· JS
luaLua
lsmp.weather.set(type [, opts]) --> boolean
jsJavaScript
lsmp.weather.set(type: string, opts?: WeatherSetOptions): boolean

Force a weather on every player.

The change fades in over transitionMs. With a durationMs, the cycle resumes on its own after that time (with the same fade); without, the weather stays until a script changes it or the resource stops. Clients receive the new weather in the same second.

Needs the world.weather capability.

Parameters
ParameterTypeDescription
typestringA name from getTypes.
opts optWeatherSetOptionsSee WeatherSetOptions.
Returnsboolean: true if the weather was set.
Failure codeWhen
permissionThe resource does not hold world.weather.
Example
luaLua
-- /storm: one thunderstorm, fading in over 30 s, for 10 minutes.
lsmp.registerCommand("storm", { help = "Ten minutes of thunderstorm" }, function()
  lsmp.weather.set("THUNDER", { transitionMs = 30000, durationMs = 600000 })
end)
jsJavaScript
// /storm: one thunderstorm, fading in over 30 s, for 10 minutes.
lsmp.registerCommand('storm', { help: 'Ten minutes of thunderstorm' }, () => {
  lsmp.weather.set('THUNDER', { transitionMs: 30000, durationMs: 600000 });
});

lsmp.weather.resumeCycle

ServerLua Β· JS
luaLua
lsmp.weather.resumeCycle([opts]) --> boolean
jsJavaScript
lsmp.weather.resumeCycle(opts?: WeatherTransitionOptions): boolean

Stop forcing the weather and go back to the cycle.

Needs the world.weather capability.

Parameters
ParameterTypeDescription
opts optWeatherTransitionOptions{ transitionMs }: the fade back, 0 to 3600000 ms.
Returnsboolean: true if a forced weather was lifted, false if the cycle was already running.
Failure codeWhen
permissionThe resource does not hold world.weather.

lsmp.weather.setSeed

ServerLua Β· JS
luaLua
lsmp.weather.setSeed(seed) --> boolean
jsJavaScript
lsmp.weather.setSeed(seed: number): boolean

Choose the seed of the weather cycle.

The same seed gives the same sequence of weathers. Changing it changes the coming segments for everybody; the current one finishes first.

Needs the world.weather capability.

Parameters
ParameterTypeDescription
seeduintAny integer from 0 to 4294967295.
Returnsboolean: true if the seed was set.
Failure codeWhen
permissionThe resource does not hold world.weather.

A sky of your own (client)

lsmp.weather.setLocal

ClientLua Β· JS
luaLua
lsmp.weather.setLocal(type [, opts]) --> boolean
jsJavaScript
lsmp.weather.setLocal(type: string, opts?: WeatherTransitionOptions): boolean

Show this player a different weather.

Only the local player sees it; the shared weather goes on for everybody else, and comes back with clearLocal. When several resources set one, the last call wins; each is removed when its resource stops.

Parameters
ParameterTypeDescription
typestringA name from getTypes.
opts optWeatherTransitionOptions{ transitionMs }: the fade, 0 to 3600000 ms.
Returnsboolean: true if the weather was applied.
Example
luaLua
-- Clear sky inside the arena, whatever the weather outside.
lsmp.on("arena:enter", function()
  lsmp.weather.setLocal("EXTRASUNNY", { transitionMs = 2000 })
end)
lsmp.on("arena:leave", function()
  lsmp.weather.clearLocal({ transitionMs = 2000 })
end)
jsJavaScript
// Clear sky inside the arena, whatever the weather outside.
lsmp.on('arena:enter', () => lsmp.weather.setLocal('EXTRASUNNY', { transitionMs: 2000 }));
lsmp.on('arena:leave', () => lsmp.weather.clearLocal({ transitionMs: 2000 }));

lsmp.weather.clearLocal

ClientLua Β· JS
luaLua
lsmp.weather.clearLocal([opts]) --> boolean
jsJavaScript
lsmp.weather.clearLocal(opts?: WeatherTransitionOptions): boolean

Remove this resource's local weather.

Parameters
ParameterTypeDescription
opts optWeatherTransitionOptions{ transitionMs }: the fade back to the shared weather.
Returnsboolean: true if this resource had a local weather.

lsmp.weather.getState

ClientLua Β· JS
luaLua
lsmp.weather.getState() --> WeatherMix
jsJavaScript
lsmp.weather.getState(): WeatherMix

The weather the game is drawing at this moment.

During a transition the game blends two weathers: { type1, type2, percent }, with the weathers as hashes and percent from 0 (all type1) to 1 (all type2). Useful to match an effect to what the player sees.

ReturnsWeatherMix: The blend being drawn.

Event

weatherChange (type, previous, transitionMs) fires on both sides when a new weather starts fading in, whether the cycle moved on or a script forced it. previous is nil/null when unknown.

Shapes

WeatherState

FieldTypeDefaultDescription
typestringβ€”The weather fading in, or in place.
previousstring?β€”The weather it replaces while a transition runs.
transitionMsmsβ€”Total length of the transition in progress (0 when none).
transitionTimeMsmsβ€”Time already elapsed in that transition.
forcedbooleanβ€”true while a script forces the weather.
forcedTimeLeftMsms?β€”Time before the cycle resumes; absent when forced with no duration, or not forced.
nextstring?β€”The next weather of the cycle.
nextChangeMsms?β€”Time before that change.
seeduintβ€”The seed of the cycle.
localOverridestring?β€”Client only: the local weather set with setLocal, if any.

WeatherForecastEntry

FieldTypeDefaultDescription
typestringβ€”The weather of that segment.
atMsepochMsβ€”When it starts fading in (Unix time, milliseconds).
durationMsms?β€”How long the segment lasts, when known.
transitionMsmsβ€”Length of its fade-in.

WeatherSetOptions

FieldTypeDefaultDescription
transitionMsms0Fade from the current weather, 0 to 3600000.
durationMsms0How long to keep it before the cycle resumes. 0: until changed.
Shared Β· Lua & JS

Permissions

Decide who may do what: groups, rules and identities, checked on the server and mirrored to each player's client.

A permission is a dotted, lower-case name such as vehicle.spawn. Your scripts decide which permissions exist and check them; the server owner decides who holds them, in the admin panel (Permissions tab) or in perms.json next to the server. Scripts can manage them too.

The server is the only place where a permission protects anything. Each client receives a read-only copy of its own player's permissions, resolved the same way, so that an interface can show or hide what the player may use without asking.

How a permission is decided

  1. Rules. A rule allows or denies a name, and covers everything below it: a rule on vehicle covers vehicle.spawn.tank. * covers everything; vehicle.* means the same as vehicle.
  2. Sources. A player gets rules from, in this order: rules a script set for their session, rules attached to their identity, then their groups from the highest priority down. The first source with a rule covering the permission decides; the others are not consulted.
  3. Within a source, the most precise rule wins (vehicle.tank before vehicle, before *). A group inherits the rules of its parent; its own rule wins over the parent's at the same precision.
  4. Ties. Two sources of the same priority that disagree: the denial wins.
  5. No rule at all means no. A permission is never held by default.

Every server starts with two groups: default, which every player is in, and admin, which allows *.

Identities

Rules and memberships that must last are attached to an identity, written type:value: lsmp:380201629467 (an account, the base62 form of the id is accepted too) or ip:203.0.113.7. An lsmp identity counts only when the server verifies its players, unless the owner sets PermsTrustDeclaredIds (server.cfg): an account id is public, and without verification anyone could claim one.

A playerId given as a target sets rules or groups for the current session only. Nothing is saved, it is gone when the player leaves, and it applies whatever the verification.

β„Ή
Who may change permissions

Every function that writes (groups, rules, memberships) needs the perms.manage capability. Without it, the call returns false and lsmp.getLastError() gives permission.

Checking a player (server)

lsmp.perms.has

ServerLua Β· JS
luaLua
lsmp.perms.has(playerId, permission) --> boolean
jsJavaScript
lsmp.perms.has(playerId: number, permission: string): boolean

Whether a player holds a permission.

The answer is cached and costs next to nothing: call it on every request a player makes.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
permissionstringA permission name, without wildcard.
Returnsboolean: true if a rule allows it; false otherwise, and for an unknown player.
Example
luaLua
lsmp.onClient("garage:spawnTank", function(source)
  if not lsmp.perms.has(source, "vehicle.spawn.tank") then
    lsmp.emitClient(source, "chat:message", { name = "", text = "Not allowed.", system = true })
    return
  end
  -- spawn the tank
end)
jsJavaScript
lsmp.onClient('garage:spawnTank', (source) => {
  if (!lsmp.perms.has(source, 'vehicle.spawn.tank')) {
    lsmp.emitClient(source, 'chat:message', { name: '', text: 'Not allowed.', system: true });
    return;
  }
  // spawn the tank
});

lsmp.perms.explain

ServerLua Β· JS
luaLua
lsmp.perms.explain(playerId, permission) --> PermExplain?
jsJavaScript
lsmp.perms.explain(playerId: number, permission: string): PermExplain | null

Why a player holds a permission, or not.

See PermExplain. Useful in a command that answers "why can't I...".

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
permissionstringA permission name.
Returns (Lua)PermExplain?: The explanation, or nil/null for an unknown player.
Returns (JavaScript)PermExplain | null: The explanation, or nil/null for an unknown player.

lsmp.perms.getPlayerGroups

ServerLua Β· JS
luaLua
lsmp.perms.getPlayerGroups(playerId [, opts]) --> {PermGroupRef}?
jsJavaScript
lsmp.perms.getPlayerGroups(playerId: number, opts?: InheritOptions): PermGroupRef[] | null

The groups of a player, from the highest priority down.

Each entry is a PermGroupRef. default is always there.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
opts optInheritOptions{ inherited }: include the groups held only through a parent (default true).
Returns (Lua){PermGroupRef}?: The groups, or nil/null for an unknown player.
Returns (JavaScript)PermGroupRef[] | null: The groups, or nil/null for an unknown player.

lsmp.perms.inGroup

ServerLua Β· JS
luaLua
lsmp.perms.inGroup(playerId, group [, opts]) --> boolean?
jsJavaScript
lsmp.perms.inGroup(playerId: number, group: string, opts?: InheritOptions): boolean | null

Whether a player is in a group.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
groupstringThe group id.
opts optInheritOptions{ inherited }: count membership through a parent (default true).
Returns (Lua)boolean?: true or false, or nil/null for an unknown player.
Returns (JavaScript)boolean | null: true or false, or nil/null for an unknown player.

lsmp.perms.getPlayerIdentities

ServerLua Β· JS
luaLua
lsmp.perms.getPlayerIdentities(playerId) --> {string}?
jsJavaScript
lsmp.perms.getPlayerIdentities(playerId: number): string[] | null

The identities of a connected player.

For example { "lsmp:380201629467", "ip:203.0.113.7" }. ip: identities need the players.identity capability; without it they are left out.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returns (Lua){string}?: The identities, or nil/null for an unknown player.
Returns (JavaScript)string[] | null: The identities, or nil/null for an unknown player.

lsmp.perms.getPlayerIdentity

ServerLua Β· JS
luaLua
lsmp.perms.getPlayerIdentity(playerId [, type]) --> string?
jsJavaScript
lsmp.perms.getPlayerIdentity(playerId: number, type: string = "lsmp"): string | null

One identity of a connected player, ready to use as a target.

Pass the result to addToGroup or allow to make a change last beyond the session.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
type optstring"lsmp" or "ip". Default: "lsmp"
Returns (Lua)string?: The identity, or nil/null if the player is unknown or has none of that type (a guest has no lsmp identity).
Returns (JavaScript)string | null: The identity, or nil/null if the player is unknown or has none of that type (a guest has no lsmp identity).
Failure codeWhen
permission"ip" without the players.identity capability.

Reading groups and identities (server)

lsmp.perms.getGroups

ServerLua Β· JS
luaLua
lsmp.perms.getGroups() --> {PermGroup}
jsJavaScript
lsmp.perms.getGroups(): PermGroup[]

Every group of the server.

Each entry is a PermGroup, without its rules.

Returns (Lua){PermGroup}: The groups.
Returns (JavaScript)PermGroup[]: The groups.

lsmp.perms.getGroup

ServerLua Β· JS
luaLua
lsmp.perms.getGroup(id) --> PermGroup?
jsJavaScript
lsmp.perms.getGroup(id: string): PermGroup | null

One group, with its rules.

A PermGroup with rules: a table of permission patterns to true (allow) or false (deny).

Parameters
ParameterTypeDescription
idstringThe group id.
Returns (Lua)PermGroup?: The group, or nil/null if it does not exist.
Returns (JavaScript)PermGroup | null: The group, or nil/null if it does not exist.

lsmp.perms.getGroupMembers

ServerLua Β· JS
luaLua
lsmp.perms.getGroupMembers(id) --> {PermMember}?
jsJavaScript
lsmp.perms.getGroupMembers(id: string): PermMember[] | null

The identities that are members of a group.

Each entry is { identity, label, untilMs, note }: untilMs is the end of a temporary membership (nil/null when permanent). Session memberships set with a playerId are not listed. ip: identities need the players.identity capability.

Parameters
ParameterTypeDescription
idstringThe group id.
Returns (Lua){PermMember}?: The members, or nil/null if the group does not exist.
Returns (JavaScript)PermMember[] | null: The members, or nil/null if the group does not exist.

lsmp.perms.getIdentity

ServerLua Β· JS
luaLua
lsmp.perms.getIdentity(identity) --> PermIdentity?
jsJavaScript
lsmp.perms.getIdentity(identity: string): PermIdentity | null

What is attached to an identity.

{ identity, label, lastSeenMs, groups, rules }: groups lists { group, untilMs, note }, rules maps patterns to true or false.

Parameters
ParameterTypeDescription
identitystringAn identity such as "lsmp:380201629467".
Returns (Lua)PermIdentity?: The identity, or nil/null if nothing is attached to it.
Returns (JavaScript)PermIdentity | null: The identity, or nil/null if nothing is attached to it.
Failure codeWhen
permissionAn ip: identity without the players.identity capability.

Declaring permissions

lsmp.perms.declare

ServerLua Β· JS
luaLua
lsmp.perms.declare(permission [, description])
jsJavaScript
lsmp.perms.declare(permission: string, description?: string): void

List a permission this resource checks, with a description.

Optional, and only for the server owner: the admin panel suggests declared permissions while they write a rule. Declarations go away when the resource stops. Declaring changes nobody's rights.

Parameters
ParameterTypeDescription
permissionstringThe permission name.
description optstringOne sentence shown in the panel.
Example
luaLua
lsmp.perms.declare("garage.tank", "Spawn a tank from the garage")
jsJavaScript
lsmp.perms.declare('garage.tank', 'Spawn a tank from the garage');

Changing permissions (server)

Changes are saved to perms.json at once (except session targets) and reach the players concerned within a moment: their checks change, their client receives a new copy, and playerPermsChange fires.

lsmp.perms.createGroup

ServerLua Β· JS
luaLua
lsmp.perms.createGroup(id [, opts]) --> boolean
jsJavaScript
lsmp.perms.createGroup(id: string, opts?: PermGroupOptions): boolean

Create a group.

An existing group is left untouched: the call returns false with the code exists. That makes it safe at the top of a script: once the group exists, the server owner may rename it, recolor it or change its rules, and a restart does not undo that. Add rules with allow right after a successful creation.

Needs the perms.manage capability.

Parameters
ParameterTypeDescription
idstringThe group id: lower case, 32 characters at most.
opts optPermGroupOptionsSee PermGroupOptions.
Returnsboolean: true if the group was created.
Failure codeWhen
existsA group with this id exists.
permissionThe resource does not hold perms.manage.
Example
luaLua
if lsmp.perms.createGroup("vip", { label = "VIP", color = "#f1c40f", priority = 20 }) then
  lsmp.perms.allow("group:vip", "garage.tank")
end
jsJavaScript
if (lsmp.perms.createGroup('vip', { label: 'VIP', color: '#f1c40f', priority: 20 })) {
  lsmp.perms.allow('group:vip', 'garage.tank');
}

lsmp.perms.updateGroup

ServerLua Β· JS
luaLua
lsmp.perms.updateGroup(id, patch) --> boolean
jsJavaScript
lsmp.perms.updateGroup(id: string, patch: PermGroupOptions): boolean

Change the label, color, priority or parent of a group.

Only the fields given change.

Needs the perms.manage capability.

Parameters
ParameterTypeDescription
idstringThe group id.
patchPermGroupOptionsSee PermGroupOptions.
Returnsboolean: true if the group was changed.
Failure codeWhen
not-foundNo such group.
permissionThe resource does not hold perms.manage.

lsmp.perms.renameGroup

ServerLua Β· JS
luaLua
lsmp.perms.renameGroup(id, newId) --> boolean
jsJavaScript
lsmp.perms.renameGroup(id: string, newId: string): boolean

Change the id of a group.

Memberships, parents and rules that name the group follow the new id.

Needs the perms.manage capability.

Parameters
ParameterTypeDescription
idstringThe current id.
newIdstringThe new id.
Returnsboolean: true if the group was renamed.
Failure codeWhen
not-foundNo such group.
existsnewId is taken.
permissionThe resource does not hold perms.manage.

lsmp.perms.deleteGroup

ServerLua Β· JS
luaLua
lsmp.perms.deleteGroup(id) --> boolean
jsJavaScript
lsmp.perms.deleteGroup(id: string): boolean

Delete a group and its memberships.

The default group cannot be deleted.

Needs the perms.manage capability.

Parameters
ParameterTypeDescription
idstringThe group id.
Returnsboolean: true if the group was deleted.
Failure codeWhen
not-foundNo such group.
permissionThe resource does not hold perms.manage.

lsmp.perms.allow

ServerLua Β· JS
luaLua
lsmp.perms.allow(target, rule) --> boolean
jsJavaScript
lsmp.perms.allow(target: number | string, rule: string): boolean

Add a rule that allows a permission.

An existing rule on the same pattern for the same target is replaced.

Needs the perms.manage capability.

Parameters
ParameterTypeDescription
targetplayerId|stringA playerId (this session only), "group:<id>", or an identity such as "lsmp:380201629467".
rulestringA permission name, name.* or *.
Returnsboolean: true if the rule was written.
Failure codeWhen
permissionThe resource does not hold perms.manage.

lsmp.perms.deny

ServerLua Β· JS
luaLua
lsmp.perms.deny(target, rule) --> boolean
jsJavaScript
lsmp.perms.deny(target: number | string, rule: string): boolean

Add a rule that denies a permission.

Useful to carve an exception: allow vehicle and deny vehicle.tank.

Needs the perms.manage capability.

Parameters
ParameterTypeDescription
targetplayerId|stringA playerId (this session only), "group:<id>", or an identity such as "lsmp:380201629467".
rulestringA permission name, name.* or *.
Returnsboolean: true if the rule was written.
Failure codeWhen
permissionThe resource does not hold perms.manage.

lsmp.perms.unset

ServerLua Β· JS
luaLua
lsmp.perms.unset(target, rule) --> boolean
jsJavaScript
lsmp.perms.unset(target: number | string, rule: string): boolean

Remove a rule, whether it allowed or denied.

Needs the perms.manage capability.

Parameters
ParameterTypeDescription
targetplayerId|stringA playerId (this session only), "group:<id>", or an identity such as "lsmp:380201629467".
rulestringThe pattern of the rule.
Returnsboolean: true if a rule was removed.
Failure codeWhen
permissionThe resource does not hold perms.manage.

lsmp.perms.addToGroup

ServerLua Β· JS
luaLua
lsmp.perms.addToGroup(target, group [, opts]) --> boolean
jsJavaScript
lsmp.perms.addToGroup(target: number | string, group: string, opts?: MembershipOptions): boolean

Put a player or an identity in a group, possibly for a limited time.

With a playerId the membership lasts for the session, and takes no end date. With an identity it is saved, and lasts until removed or until its end (durationMs or untilMs). Every player is already in default.

Needs the perms.manage capability.

Parameters
ParameterTypeDescription
targetplayerId|stringA playerId (this session only) or an identity.
groupstringThe group id.
opts optMembershipOptionsSee MembershipOptions.
Returnsboolean: true once the target is in the group (also when it already was).
Failure codeWhen
not-foundNo such group, or the player is unknown.
permissionThe resource does not hold perms.manage.
Example
luaLua
-- A month of VIP for a player's account.
local identity = lsmp.perms.getPlayerIdentity(playerId)
if identity then
  lsmp.perms.addToGroup(identity, "vip", { durationMs = 30 * 86400000, note = "Event winner" })
end
jsJavaScript
// A month of VIP for a player's account.
const identity = lsmp.perms.getPlayerIdentity(playerId);
if (identity) lsmp.perms.addToGroup(identity, 'vip', { durationMs: 30 * 86400000, note: 'Event winner' });

lsmp.perms.removeFromGroup

ServerLua Β· JS
luaLua
lsmp.perms.removeFromGroup(target, group) --> boolean
jsJavaScript
lsmp.perms.removeFromGroup(target: number | string, group: string): boolean

Take a player or an identity out of a group.

Needs the perms.manage capability.

Parameters
ParameterTypeDescription
targetplayerId|stringA playerId (session membership) or an identity.
groupstringThe group id.
Returnsboolean: true if a membership was removed.
Failure codeWhen
permissionThe resource does not hold perms.manage.

lsmp.perms.deleteIdentity

ServerLua Β· JS
luaLua
lsmp.perms.deleteIdentity(identity) --> boolean
jsJavaScript
lsmp.perms.deleteIdentity(identity: string): boolean

Forget every rule and membership of an identity.

Needs the perms.manage capability.

Parameters
ParameterTypeDescription
identitystringThe identity.
Returnsboolean: true if something was removed.
Failure codeWhen
permissionThe resource does not hold perms.manage.

The resource's own capabilities

Capabilities are what a resource may do with sensitive functions (kick, ban, change permissions...), granted by the server owner per resource. They are described on Resource capabilities and sandbox.

lsmp.perms.getCapabilities

ServerLua Β· JS
luaLua
lsmp.perms.getCapabilities() --> {string}
jsJavaScript
lsmp.perms.getCapabilities(): string[]

The capabilities this resource holds.

Returns (Lua){string}: Capability ids, such as "players.kick".
Returns (JavaScript)string[]: Capability ids, such as "players.kick".

lsmp.perms.hasCapability

ServerLua Β· JS
luaLua
lsmp.perms.hasCapability(capability) --> boolean
jsJavaScript
lsmp.perms.hasCapability(capability: string): boolean

Whether this resource holds a capability.

To adapt a feature before calling a function that would fail with permission.

Parameters
ParameterTypeDescription
capabilitystringA capability id.
Returnsboolean: true if the resource holds it; false otherwise, and for an unknown id.

On the client

Each client holds a copy of its own player's effective permissions, sent by the server when the player joins and again each time they change. The checks below read that copy; they never ask the server.

⚠
Display only

A modified client can grant itself anything in its copy. Use these functions to show or hide interface elements, and check again on the server before acting.

lsmp.perms.has

ClientLua Β· JS
luaLua
lsmp.perms.has(permission) --> boolean
jsJavaScript
lsmp.perms.has(permission: string): boolean

Whether the local player holds a permission.

Parameters
ParameterTypeDescription
permissionstringA permission name.
Returnsboolean: true if allowed; false otherwise, and before the copy arrived.
Example
luaLua
if lsmp.perms.has("garage.tank") then
  lsmp.log("tanks are available in your garage")
end
jsJavaScript
if (lsmp.perms.has('garage.tank')) lsmp.log('tanks are available in your garage');

lsmp.perms.explain

ClientLua Β· JS
luaLua
lsmp.perms.explain(permission) --> PermExplain
jsJavaScript
lsmp.perms.explain(permission: string): PermExplain

Why the local player holds a permission, or not.

See PermExplain.

Parameters
ParameterTypeDescription
permissionstringA permission name.
ReturnsPermExplain: The explanation.

lsmp.perms.getGroups

ClientLua Β· JS
luaLua
lsmp.perms.getGroups([opts]) --> {PermGroupRef}
jsJavaScript
lsmp.perms.getGroups(opts?: InheritOptions): PermGroupRef[]

The groups of the local player.

Parameters
ParameterTypeDescription
opts optInheritOptions{ inherited }: include the groups held through a parent (default true).
Returns (Lua){PermGroupRef}: A list of PermGroupRef, empty before the copy arrived.
Returns (JavaScript)PermGroupRef[]: A list of PermGroupRef, empty before the copy arrived.

lsmp.perms.inGroup

ClientLua Β· JS
luaLua
lsmp.perms.inGroup(group [, opts]) --> boolean
jsJavaScript
lsmp.perms.inGroup(group: string, opts?: InheritOptions): boolean

Whether the local player is in a group.

Parameters
ParameterTypeDescription
groupstringThe group id.
opts optInheritOptions{ inherited } (default true).
Returnsboolean: true or false.

lsmp.perms.isReady

ClientLua Β· JS
luaLua
lsmp.perms.isReady() --> boolean
jsJavaScript
lsmp.perms.isReady(): boolean

Whether the copy of the permissions has arrived.

It usually arrives before client scripts start. Until then every check answers false.

Returnsboolean: true once the copy is there.

lsmp.perms.isComplete

ClientLua Β· JS
luaLua
lsmp.perms.isComplete() --> boolean
jsJavaScript
lsmp.perms.isComplete(): boolean

Whether the copy holds everything.

A player with an extremely large set of rules receives an empty copy marked incomplete instead of a partial one: every check then answers false on the client. The server checks are not affected.

Returnsboolean: false when the copy was too large to send.

playerPermsChange fires on the client when a new copy arrives, and on the server when a player's effective permissions change.

Shapes

PermExplain

FieldTypeDefaultDescription
allowedbooleanβ€”The answer.
matchedbooleanβ€”false when no rule covers the permission (refused by default).
sourcestringβ€”Where the deciding rule comes from: "session", "identity" or "group"; "none" when no rule matched.
groupstring?β€”The group of the deciding rule.
rulestring?β€”The pattern of the deciding rule.
permissionstringβ€”The permission asked about, normalized.

PermGroupRef

FieldTypeDefaultDescription
idstringβ€”The group id.
labelstringβ€”Its display name.
colorstring?β€”"#rrggbb".
priorityintβ€”Higher wins.
directbooleanβ€”false when held only through a parent.

PermGroup

FieldTypeDefaultDescription
idstringβ€”The group id.
labelstringβ€”Its display name.
colorstring?β€”"#rrggbb".
priorityintβ€”Higher wins.
parentstring?β€”The group it inherits from.
builtinbooleanβ€”true for default.
membersintβ€”How many saved identities are members.
rulestableβ€”getGroup only: patterns to true (allow) or false (deny).

PermGroupOptions

FieldTypeDefaultDescription
labelstringthe idDisplay name, 64 bytes at most.
colorcolorβ€”Any color form.
priorityint0Higher wins when sources disagree.
parentstringβ€”A group to inherit rules from.

MembershipOptions

FieldTypeDefaultDescription
durationMsmsβ€”Ends this long after the call.
untilMsepochMsβ€”Ends at this time. Not with durationMs.
notestringβ€”Shown in the admin panel.
Shared Β· Lua & JS

Voice

Proximity chat, radios, team channels: the server decides who hears whom, each client shapes its own microphone and mix.

LS:MP has no voice chat by default. Two players hear each other only when a server script has created a channel and put them both on it. Until then nothing is relayed, and each client keeps its microphone closed.

The server decides everything about who hears whom: channels, roles, ranges and mutes. A client cannot put itself on a channel, widen its range or notice that it is muted. The client side only shapes the local microphone and what the player hears.

βœ“
Start from voice-mgr

The bundled voice-mgr resource is a complete setup: one 3D channel for the whole server with whisper, normal and shout ranges, and radio frequencies joined with /radio <frequency>. Keep it, tune its configuration, or write your own. See Bundled example resources.

Channels and roles

KindOptionHeard
Flatspatial: false (default)At the same level everywhere: a radio, a phone call, a team channel.
3Dspatial: trueFrom the speaker's ped, up to range metres, fading with the distance.
  • A player speaks on a channel where their role is "talk" or "both", and hears a channel where it is "listen" or "both". A listen-only admin channel or a receive-only broadcast needs nothing more.
  • On a 3D channel, the listener must be within the speaker's range: the range belongs to the speaker, which is what makes whisper, normal and shout one number on one channel.
  • When several channels join the same speaker to the same listener, one is used: the highest priority, then 3D before flat (a radio mate standing next to you is heard where they stand), then the longest range.
  • Voice stops at the edge of a dimension: two players on the same channel in different dimensions do not hear each other.
  • A client opens its microphone only once its player has the talk role on at least one channel.
β„Ή
Channels belong to their resource

A channel is owned by the resource that created it and is destroyed, with its memberships, when that resource stops. Create the channels when the resource starts (see the example below).

β„Ή
Capability

Every function that changes voice (channels, memberships, ranges, mutes) needs the voice.manage capability. Without it the call returns false and lsmp.getLastError() gives permission. Reading works without it.

lsmp.VoiceRole

ServerLua Β· JS
luaLua
lsmp.VoiceRole
jsJavaScript
lsmp.VoiceRole

The roles a player can have on a channel.

lsmp.VoiceRole.Listen = "listen" Β· lsmp.VoiceRole.Talk = "talk" Β· lsmp.VoiceRole.Both = "both"

Every function that takes a channel accepts its name or its hash (see getChannelId).

Channels (server)

lsmp.voice.createChannel

ServerLua Β· JS
luaLua
lsmp.voice.createChannel(channel [, opts]) --> boolean
jsJavaScript
lsmp.voice.createChannel(channel: string | number, opts?: VoiceChannelOptions): boolean

Create a channel owned by this resource.

An existing channel is left as it is: the call returns false with the code exists; change it with setChannelOptions. Options not given take their default (VoiceChannelOptions).

Needs the voice.manage capability.

Parameters
ParameterTypeDescription
channelstring|hashOutA name (or a hash).
opts optVoiceChannelOptionsSee VoiceChannelOptions.
Returnsboolean: true if the channel was created.
Failure codeWhen
existsThe channel exists.
limitThe server holds 4096 channels.
permissionThe resource does not hold voice.manage.
Example
luaLua
-- One 3D channel for everybody, created when the resource starts.
local PROXIMITY = "proximity"
if not lsmp.voice.createChannel(PROXIMITY, { spatial = true, range = 20 }) then
  lsmp.voice.setChannelOptions(PROXIMITY, { spatial = true, range = 20 })
end

for _, id in ipairs(lsmp.getPlayers()) do
  lsmp.voice.setPlayerChannel(id, PROXIMITY, lsmp.VoiceRole.Both)
end
lsmp.on("playerJoin", function(playerId)
  lsmp.voice.setPlayerChannel(playerId, PROXIMITY, lsmp.VoiceRole.Both)
end)
jsJavaScript
// One 3D channel for everybody, created when the resource starts.
const PROXIMITY = 'proximity';
if (!lsmp.voice.createChannel(PROXIMITY, { spatial: true, range: 20 }))
  lsmp.voice.setChannelOptions(PROXIMITY, { spatial: true, range: 20 });

for (const id of lsmp.getPlayers()) lsmp.voice.setPlayerChannel(id, PROXIMITY, lsmp.VoiceRole.Both);
lsmp.on('playerJoin', (playerId) => {
  lsmp.voice.setPlayerChannel(playerId, PROXIMITY, lsmp.VoiceRole.Both);
});

lsmp.voice.setChannelOptions

ServerLua Β· JS
luaLua
lsmp.voice.setChannelOptions(channel, opts) --> boolean
jsJavaScript
lsmp.voice.setChannelOptions(channel: string | number, opts: VoiceChannelOptions): boolean

Change some options of a channel.

The options not given keep their value. The change applies at once to everybody on the channel.

Needs the voice.manage capability.

Parameters
ParameterTypeDescription
channelstring|hashOutA name or a hash.
optsVoiceChannelOptionsSee VoiceChannelOptions.
Returnsboolean: true if the channel was changed.
Failure codeWhen
not-foundNo such channel.
permissionThe resource does not hold voice.manage.

lsmp.voice.getChannelOptions

ServerLua Β· JS
luaLua
lsmp.voice.getChannelOptions(channel) --> VoiceChannelOptions?
jsJavaScript
lsmp.voice.getChannelOptions(channel: string | number): VoiceChannelOptions | null

The options in force on a channel.

Every field is filled in, with the values the server applies after clamping.

Parameters
ParameterTypeDescription
channelstring|hashOutA name or a hash.
Returns (Lua)VoiceChannelOptions?: The options, or nil/null if the channel does not exist.
Returns (JavaScript)VoiceChannelOptions | null: The options, or nil/null if the channel does not exist.

lsmp.voice.destroyChannel

ServerLua Β· JS
luaLua
lsmp.voice.destroyChannel(channel) --> boolean
jsJavaScript
lsmp.voice.destroyChannel(channel: string | number): boolean

Destroy a channel and take every player off it.

Worth doing for channels created on demand, such as a radio frequency nobody is on any more.

Needs the voice.manage capability.

Parameters
ParameterTypeDescription
channelstring|hashOutA name or a hash.
Returnsboolean: true if the channel was destroyed.
Failure codeWhen
not-foundNo such channel.
permissionThe resource does not hold voice.manage.

lsmp.voice.channelExists

ServerLua Β· JS
luaLua
lsmp.voice.channelExists(channel) --> boolean
jsJavaScript
lsmp.voice.channelExists(channel: string | number): boolean

Whether a channel exists.

Parameters
ParameterTypeDescription
channelstring|hashOutA name or a hash.
Returnsboolean: true if it exists.

lsmp.voice.getChannels

ServerLua Β· JS
luaLua
lsmp.voice.getChannels() --> {integer}
jsJavaScript
lsmp.voice.getChannels(): number[]

Every channel of the server, as hashes.

The channels of every resource. getChannelName gives a channel's name back.

Returns (Lua){integer}: The channel hashes.
Returns (JavaScript)number[]: The channel hashes.

lsmp.voice.getChannelName

ServerLua Β· JS
luaLua
lsmp.voice.getChannelName(channel) --> string?
jsJavaScript
lsmp.voice.getChannelName(channel: string | number): string | null

The name a channel was created with.

Parameters
ParameterTypeDescription
channelstring|hashOutA name or a hash.
Returns (Lua)string?: The name, or nil/null if the channel does not exist or was created from a hash.
Returns (JavaScript)string | null: The name, or nil/null if the channel does not exist or was created from a hash.

lsmp.voice.getChannelPlayers

ServerLua Β· JS
luaLua
lsmp.voice.getChannelPlayers(channel) --> {VoiceMember}
jsJavaScript
lsmp.voice.getChannelPlayers(channel: string | number): VoiceMember[]

The players on a channel.

Parameters
ParameterTypeDescription
channelstring|hashOutA name or a hash.
Returns (Lua){VoiceMember}: A list of { playerId, role }, empty for a channel that does not exist.
Returns (JavaScript)VoiceMember[]: A list of { playerId, role }, empty for a channel that does not exist.

lsmp.voice.getChannelId

SharedLua Β· JS
luaLua
lsmp.voice.getChannelId(name) --> integer
jsJavaScript
lsmp.voice.getChannelId(name: string): number

The hash of a channel name.

The same on the server and on every client, so both sides agree on a channel. Every function already accepts a name: compute the hash only to store it, or in a loop that runs every frame.

Parameters
ParameterTypeDescription
namestringThe channel name.
Returns (Lua)integer: The hash.
Returns (JavaScript)number: The hash.

Players on channels (server)

lsmp.voice.setPlayerChannel

ServerLua Β· JS
luaLua
lsmp.voice.setPlayerChannel(playerId, channel, role) --> boolean
jsJavaScript
lsmp.voice.setPlayerChannel(playerId: number, channel: string | number, role: string): boolean

Put a player on a channel with a role, or change their role.

The channel must exist: a mistyped name returns false instead of creating a channel nobody else is on. Changing the role keeps the player's range on that channel. A player can be on 8 channels at most.

Needs the voice.manage capability.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
channelstring|hashOutA name or a hash.
rolestring"listen", "talk" or "both" (lsmp.VoiceRole).
Returnsboolean: true if the membership was set.
Failure codeWhen
not-foundUnknown player or channel.
limitThe player is on 8 channels.
permissionThe resource does not hold voice.manage.

lsmp.voice.removePlayerChannel

ServerLua Β· JS
luaLua
lsmp.voice.removePlayerChannel(playerId, channel) --> boolean
jsJavaScript
lsmp.voice.removePlayerChannel(playerId: number, channel: string | number): boolean

Take a player off a channel.

Needs the voice.manage capability.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
channelstring|hashOutA name or a hash.
Returnsboolean: true if the player was on the channel.
Failure codeWhen
not-foundThe player was not on the channel.
permissionThe resource does not hold voice.manage.

lsmp.voice.getPlayerChannel

ServerLua Β· JS
luaLua
lsmp.voice.getPlayerChannel(playerId, channel) --> string?
jsJavaScript
lsmp.voice.getPlayerChannel(playerId: number, channel: string | number): string | null

A player's role on one channel.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
channelstring|hashOutA name or a hash.
Returns (Lua)string?: "listen", "talk" or "both", or nil/null if the player is not on the channel.
Returns (JavaScript)string | null: "listen", "talk" or "both", or nil/null if the player is not on the channel.

lsmp.voice.getPlayerChannels

ServerLua Β· JS
luaLua
lsmp.voice.getPlayerChannels(playerId) --> {VoiceMembership}?
jsJavaScript
lsmp.voice.getPlayerChannels(playerId: number): VoiceMembership[] | null

Every channel a player is on.

Each entry is { channel, role }, with channel as a hash.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returns (Lua){VoiceMembership}?: The memberships, or nil/null for an unknown player.
Returns (JavaScript)VoiceMembership[] | null: The memberships, or nil/null for an unknown player.

lsmp.voice.clearPlayerChannels

ServerLua Β· JS
luaLua
lsmp.voice.clearPlayerChannels(playerId) --> boolean
jsJavaScript
lsmp.voice.clearPlayerChannels(playerId: number): boolean

Take a player off every channel.

The player then hears nobody and is heard by nobody, and their microphone closes, until a script puts them back on a channel.

Needs the voice.manage capability.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returnsboolean: true if the player is known.
Failure codeWhen
not-foundUnknown player.
permissionThe resource does not hold voice.manage.

lsmp.voice.setPlayerRange

ServerLua Β· JS
luaLua
lsmp.voice.setPlayerRange(playerId, channel, meters) --> boolean
jsJavaScript
lsmp.voice.setPlayerRange(playerId: number, channel: string | number, meters: number): boolean

How far a player's voice carries on a 3D channel.

Replaces the channel's range for this player's voice only; the other options of the channel still apply. No effect on a flat channel.

Needs the voice.manage capability.

Parameters
ParameterTypeDescription
playerIdplayerIdThe speaker.
channelstring|hashOutA name or a hash.
metersmetersThe range, 0 or more (500 at most is used). 0 goes back to the channel's range.
Returnsboolean: true if the player is on the channel.
Failure codeWhen
not-foundThe player is not on the channel.
permissionThe resource does not hold voice.manage.
Example
luaLua
-- Whisper, normal, shout: one number on the same channel.
local RANGES = { whisper = 3, normal = 0, shout = 45 }

lsmp.onCall("voice:setRange", function(source, mode)
  local meters = RANGES[mode]
  if not meters then return false end
  return lsmp.voice.setPlayerRange(source, "proximity", meters)
end)
jsJavaScript
// Whisper, normal, shout: one number on the same channel.
const RANGES = { whisper: 3, normal: 0, shout: 45 };

lsmp.onCall('voice:setRange', (source, mode) => {
  if (!Object.hasOwn(RANGES, mode)) return false;
  return lsmp.voice.setPlayerRange(source, 'proximity', RANGES[mode]);
});

lsmp.voice.getPlayerRange

ServerLua Β· JS
luaLua
lsmp.voice.getPlayerRange(playerId, channel) --> number?
jsJavaScript
lsmp.voice.getPlayerRange(playerId: number, channel: string | number): number | null

The range a player's voice carries on a 3D channel.

Their own range if one was set, otherwise the channel's.

Parameters
ParameterTypeDescription
playerIdplayerIdThe speaker.
channelstring|hashOutA name or a hash.
Returns (Lua)number?: The range in metres, or nil/null if the player is not on the channel.
Returns (JavaScript)number | null: The range in metres, or nil/null if the player is not on the channel.

Moderation and activity (server)

lsmp.voice.setPlayerMuted

ServerLua Β· JS
luaLua
lsmp.voice.setPlayerMuted(playerId, muted) --> boolean
jsJavaScript
lsmp.voice.setPlayerMuted(playerId: number, muted: boolean): boolean

Silence a player on every channel, or give their voice back.

Nothing from a muted player is relayed. Their client is not told. To lower one speaker for one listener instead, see the client's volume settings below.

Needs the voice.manage capability.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
mutedbooleantrue to mute, false to unmute.
Returnsboolean: true if the player is known.
Failure codeWhen
not-foundUnknown player.
permissionThe resource does not hold voice.manage.

lsmp.voice.isPlayerMuted

ServerLua Β· JS
luaLua
lsmp.voice.isPlayerMuted(playerId) --> boolean?
jsJavaScript
lsmp.voice.isPlayerMuted(playerId: number): boolean | null

Whether a player is muted by the server.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returns (Lua)boolean?: true or false, or nil/null for an unknown player.
Returns (JavaScript)boolean | null: true or false, or nil/null for an unknown player.

lsmp.voice.isPlayerTalking

SharedLua Β· JS
luaLua
lsmp.voice.isPlayerTalking(playerId) --> boolean
jsJavaScript
lsmp.voice.isPlayerTalking(playerId: number): boolean

Whether a player is transmitting.

Ends at once when the player releases their key, otherwise after a short silence. A muted player, or a player with no talk role, is never talking: nobody hears them. For changes rather than polling, listen to voiceStart and voiceStop.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returnsboolean: true while the player transmits.

Events

voiceStart (playerId) and voiceStop (playerId) fire on both sides when a player starts and stops transmitting. A client is told about the speakers it hears.

VoiceChannelOptions

FieldTypeDefaultDescription
spatialbooleanfalsetrue for a 3D channel. Only volume and priority apply to a flat channel.
rangemeters20How far a voice carries, up to 500.
refDistancemeters2Full volume up to this distance.
rolloffnumber0.6How fast the volume falls beyond refDistance, 0 to 10.
distanceModelstring"inverse""inverse" (natural), "linear" (straight down to silence at the range) or "exponential".
volumenumber1Channel gain, 0 to 4.
directionalbooleantrueLeft/right panning from where the speaker stands.
mufflebooleantrueA muffled sound from far away or from behind.
priorityint0Which channel wins when several join the same two players (highest first).

Limits

  • A player is on 8 channels at most; the server holds 4096.
  • A speaker is relayed to 64 listeners at most: the nearest ones on 3D channels, with room kept for flat-channel listeners.
  • A client plays 24 speakers at once.
  • A player who turned voice chat off in their settings receives nothing.

On the client

The client shapes the local microphone and mix. The player's own settings in the LS:MP menu (Settings > Voice) always win: a script can restrict the microphone, never open it against the player's choice.

lsmp.VoiceInputMode

ClientLua Β· JS
luaLua
lsmp.VoiceInputMode
jsJavaScript
lsmp.VoiceInputMode

How the local microphone opens.

lsmp.VoiceInputMode.Off = "off" Β· lsmp.VoiceInputMode.PushToTalk = "pushToTalk" Β· lsmp.VoiceInputMode.VoiceActivity = "voiceActivity"

β„Ή
Owned settings

Every setter below changes a setting owned by the calling resource: the last writer wins, and the value comes back when that resource stops.

lsmp.voice.setInputMode

ClientLua Β· JS
luaLua
lsmp.voice.setInputMode(mode)
jsJavaScript
lsmp.voice.setInputMode(mode: string): void

Restrict how the microphone opens.

The mode in force is the stricter of this one and the player's own setting: a script can turn push-to-talk on, or the microphone off, but never open it against the player's choice.

Parameters
ParameterTypeDescription
modestring"off", "pushToTalk" or "voiceActivity" (lsmp.VoiceInputMode).

lsmp.voice.getInputMode

ClientLua Β· JS
luaLua
lsmp.voice.getInputMode() --> string
jsJavaScript
lsmp.voice.getInputMode(): string

The microphone mode in force.

Returnsstring: "off", "pushToTalk" or "voiceActivity".

lsmp.voice.setTalking

ClientLua Β· JS
luaLua
lsmp.voice.setTalking(talking)
jsJavaScript
lsmp.voice.setTalking(talking: boolean): void

Hold the push-to-talk open or closed.

For a radio key or a phone call driven by your script. It opens the microphone only for players who allowed servers to do so in their settings; the others hold their own push-to-talk key.

Parameters
ParameterTypeDescription
talkingbooleantrue to transmit, false to stop.
Example
luaLua
local RADIO_KEY = 171   -- Caps Lock on a default layout
local held = false

lsmp.onTick(function()
  local now = isControlPressed(0, RADIO_KEY)
  if now ~= held then
    held = now
    lsmp.voice.setTalking(now)
  end
end)
jsJavaScript
const RADIO_KEY = 171;   // Caps Lock on a default layout
let held = false;

lsmp.onTick(() => {
  const now = isControlPressed(0, RADIO_KEY);
  if (now !== held) {
    held = now;
    lsmp.voice.setTalking(now);
  }
});

lsmp.voice.isTransmitting

ClientLua Β· JS
luaLua
lsmp.voice.isTransmitting() --> boolean
jsJavaScript
lsmp.voice.isTransmitting(): boolean

Whether the local microphone is sending.

For a microphone indicator. false while the player has no talk role on any channel.

Returnsboolean: true while sending.

lsmp.voice.getMicLevel

ClientLua Β· JS
luaLua
lsmp.voice.getMicLevel() --> number
jsJavaScript
lsmp.voice.getMicLevel(): number

The loudness of the local microphone.

For a level meter, or to help the player pick a threshold.

Returnsnumber: The level, 0 to 1.

lsmp.voice.setMicGain

ClientLua Β· JS
luaLua
lsmp.voice.setMicGain(gain)
jsJavaScript
lsmp.voice.setMicGain(gain: number): void

Amplify or soften the local microphone.

Parameters
ParameterTypeDescription
gainnumber0 to 4; 1 leaves it unchanged.

lsmp.voice.setThreshold

ClientLua Β· JS
luaLua
lsmp.voice.setThreshold(rms)
jsJavaScript
lsmp.voice.setThreshold(rms: number): void

How loud the player must speak to transmit in voice activity mode.

Parameters
ParameterTypeDescription
rmsnumberThe level, 0 to 1, compared with getMicLevel.

lsmp.voice.setVolume

ClientLua Β· JS
luaLua
lsmp.voice.setVolume(volume)
jsJavaScript
lsmp.voice.setVolume(volume: number): void

The volume of every voice this player hears.

Parameters
ParameterTypeDescription
volumenumber0 to 4; 1 is normal.

lsmp.voice.setPlayerVolume

ClientLua Β· JS
luaLua
lsmp.voice.setPlayerVolume(playerId, volume)
jsJavaScript
lsmp.voice.setPlayerVolume(playerId: number, volume: number): void

The volume of one speaker, for this player only.

A listener's preference: the speaker and the other players are not affected. To silence a player for everybody, the server uses setPlayerMuted.

Parameters
ParameterTypeDescription
playerIdplayerIdThe speaker.
volumenumber0 to 4; 0 silences them.

lsmp.voice.setChannelVolume

ClientLua Β· JS
luaLua
lsmp.voice.setChannelVolume(channel, volume)
jsJavaScript
lsmp.voice.setChannelVolume(channel: string | number, volume: number): void

The volume of one channel, for this player only.

For example, a quieter radio than the voices around.

Parameters
ParameterTypeDescription
channelstring|hashOutA channel name or hash.
volumenumber0 to 4.

Server API

Server Β· Lua & JS

Entities and pickups

Create, read and delete networked vehicles, peds, objects and pickups from the server.

The server creates and tracks networked entities: vehicles, peds and objects that every player in range sees. Each has a netId, the same number on the server and on every client. On a client, turn it into a game handle with lsmp.getEntityFromNetId and use the game natives (see Client entities).

The server does not run the game simulation: a player's client simulates each entity (its owner) and sends its state. The server knows position, model, type, owner, dimension and seats; for anything else (health, damage, appearance) ask the owner's client. Who simulates what is explained in Ownership and AI intents.

  • Entities a resource creates belong to it. Acting on others (deleting, changing policies, intents, pickup collectors) needs the entities.foreign capability.
  • When the resource stops, its entities and pickups are deleted, except those with lifePolicy = "keep".
  • A netId is reused after its entity is deleted: if you keep netIds for a long time, check entityExists and the model before acting.

Creating and deleting

lsmp.createEntity

ServerLua Β· JS
luaLua
lsmp.createEntity(type, model, position [, opts]) --> integer?
jsJavaScript
lsmp.createEntity(type: string, model: number|string, position: Vec3Like, opts?: CreateEntityOptions): number | null

Creates a networked vehicle, ped or object, owned by the calling resource.

The entity is created with no owner unless owner is given; the nearest capable player adopts it (see Ownership). Its default life policy is "whileRelevant": it is deleted when no player is in range any more. Use lifePolicy = "keep" for entities that must stay.

Parameters
ParameterTypeDescription
typestring"vehicle", "ped" or "object".
modelhashModel name or hash (not 0).
positionvec3Where to create it.
opts optCreateEntityOptionsSee the table below.
Returns (Lua)integer?: The netId, or nil/null on failure: limit (no free netId), permission (client entities disabled in that dimension), not-found (owner not connected), invalid (owner in another dimension).
Returns (JavaScript)number | null: The netId, or nil/null on failure: limit (no free netId), permission (client entities disabled in that dimension), not-found (owner not connected), invalid (owner in another dimension).
OptionTypeDefaultDescription
headingdegrees0Facing (yaw). Exclusive with rotation.
rotationrotationβ€”Full rotation {x, y, z} in degrees (pitch, roll, yaw).
ownerplayerIdβ€”The player who simulates it first. Its dimension is used when dimension is not given.
dimensiondimension0The dimension to create it in.
ownerPolicystring"auto"Who may simulate it: see owner policies.
lifePolicystring"whileRelevant"When it is deleted: see life policies.
Example
luaLua
local car = lsmp.createEntity("vehicle", "adder", { x = -75.0, y = -818.0, z = 326.0 }, {
  heading = 90.0,
  lifePolicy = "keep",
})
if car then lsmp.setEntityMeta(car, "owner", "Ada") end
jsJavaScript
const car = lsmp.createEntity("vehicle", "adder", { x: -75, y: -818, z: 326 }, {
  heading: 90,
  lifePolicy: "keep",
});
if (car !== null) lsmp.setEntityMeta(car, "owner", "Ada");

lsmp.deleteEntity

ServerLua Β· JS
luaLua
lsmp.deleteEntity(netId) --> boolean
jsJavaScript
lsmp.deleteEntity(netId: number): boolean

Deletes an entity.

Entities created by another resource or by a client need the entities.foreign capability. A player's ped cannot be deleted.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
Returnsboolean: false with not-found, permission, or invalid (a player's ped).

lsmp.entityExists

ServerLua Β· JS
luaLua
lsmp.entityExists(netId) --> boolean
jsJavaScript
lsmp.entityExists(netId: number): boolean

Whether a netId designates a live entity.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
Returnsboolean

Reading

These read what the server knows: the last state sent by the owner. Positions are fresh to a few tens of milliseconds for a simulated entity. To read several fields at the same instant, prefer getEntityState.

lsmp.getEntityCoords

ServerLua Β· JS
luaLua
lsmp.getEntityCoords(netId) --> Vector3?
jsJavaScript
lsmp.getEntityCoords(netId: number): Vec3 | null

The last synchronized position.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
Returns (Lua)Vector3?: nil/null if the entity is unknown.
Returns (JavaScript)Vec3 | null: nil/null if the entity is unknown.

lsmp.getEntityModel

ServerLua Β· JS
luaLua
lsmp.getEntityModel(netId) --> integer?
jsJavaScript
lsmp.getEntityModel(netId: number): number | null

The model hash, unsigned.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
Returns (Lua)integer?: nil/null if unknown.
Returns (JavaScript)number | null: nil/null if unknown.

lsmp.getEntityType

ServerLua Β· JS
luaLua
lsmp.getEntityType(netId) --> string?
jsJavaScript
lsmp.getEntityType(netId: number): string | null

The entity type.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
Returns (Lua)string?: "vehicle", "ped", "object" or "playerPed"; nil/null if unknown.
Returns (JavaScript)string | null: "vehicle", "ped", "object" or "playerPed"; nil/null if unknown.

lsmp.getEntityState

ServerLua Β· JS
luaLua
lsmp.getEntityState(netId) --> EntityState?
jsJavaScript
lsmp.getEntityState(netId: number): EntityState | null

A consistent snapshot of what the server knows about an entity.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
Returns (Lua)EntityState?: See the table; nil/null if unknown.
Returns (JavaScript)EntityState | null: See the table; nil/null if unknown.
FieldTypeDescription
coordsVector3Position.
modelhashModel, unsigned.
typestringEntity type.
ownerplayerId?Player simulating it; absent when orphan.
dimensiondimensionIts dimension.
lastSyncMsms?Age of the last update; absent if never synchronized.
vehiclenetId?For a ped: the vehicle it is in.
seatinteger?For a ped in a vehicle: its seat (0 = driver).
Example
luaLua
local s = lsmp.getEntityState(netId)
if s and s.type == "ped" and s.vehicle then
  lsmp.log("in vehicle " .. s.vehicle .. ", seat " .. s.seat)
end
jsJavaScript
const s = lsmp.getEntityState(netId);
if (s?.type === "ped" && s.vehicle !== null) lsmp.log(`in vehicle ${s.vehicle}, seat ${s.seat}`);

lsmp.getEntities

ServerLua Β· JS
luaLua
lsmp.getEntities([opts]) --> {integer}
jsJavaScript
lsmp.getEntities(opts?: QueryOptions): Uint32Array

The netIds of all networked entities, optionally filtered.

Parameters
ParameterTypeDescription
opts optQueryOptions{ types, dimension }: a list of entity types (default all) and one dimension (default all).
Returns (Lua){integer}: The netIds.
Returns (JavaScript)Uint32Array: The netIds.
Example
luaLua
local vehicles = lsmp.getEntities({ types = { "vehicle" }, dimension = 0 })
lsmp.log(#vehicles .. " vehicles in the main world")
jsJavaScript
const vehicles = lsmp.getEntities({ types: ["vehicle"], dimension: 0 });
lsmp.log(`${vehicles.length} vehicles in the main world`);

To search around a position, see Spatial queries.

Vehicles and seats

lsmp.getVehicleOccupants

ServerLua Β· JS
luaLua
lsmp.getVehicleOccupants(vehicle) --> {SeatOccupant}?
jsJavaScript
lsmp.getVehicleOccupants(vehicle: number): SeatOccupant[] | null

The occupied seats of a vehicle.

Parameters
ParameterTypeDescription
vehiclenetIdThe vehicle.
Returns (Lua){SeatOccupant}?: A list of { seat, ped } (seat 0 = driver), or nil/null if it is not a known vehicle.
Returns (JavaScript)SeatOccupant[] | null: A list of { seat, ped } (seat 0 = driver), or nil/null if it is not a known vehicle.
Example
luaLua
for _, o in ipairs(lsmp.getVehicleOccupants(car) or {}) do
  lsmp.log("seat " .. o.seat .. ": ped " .. o.ped)
end
jsJavaScript
for (const { seat, ped } of lsmp.getVehicleOccupants(car) ?? []) lsmp.log(`seat ${seat}: ped ${ped}`);

lsmp.getPedInVehicleSeat

ServerLua Β· JS
luaLua
lsmp.getPedInVehicleSeat(vehicle, seat) --> integer?
jsJavaScript
lsmp.getPedInVehicleSeat(vehicle: number, seat: number): number | null

The ped in one seat of a vehicle.

Parameters
ParameterTypeDescription
vehiclenetIdThe vehicle.
seatinteger0 = driver, 1 and up = passengers.
Returns (Lua)integer?: The ped's netId, or nil/null if the seat is empty or the vehicle unknown.
Returns (JavaScript)number | null: The ped's netId, or nil/null if the seat is empty or the vehicle unknown.

lsmp.getVehiclePedIsIn

ServerLua Β· JS
luaLua
lsmp.getVehiclePedIsIn(ped) --> integer?
jsJavaScript
lsmp.getVehiclePedIsIn(ped: number): number | null

The vehicle a ped is in.

Parameters
ParameterTypeDescription
pednetIdThe ped (a player's ped too: see lsmp.getPlayerPed).
Returns (Lua)integer?: The vehicle's netId, or nil/null.
Returns (JavaScript)number | null: The vehicle's netId, or nil/null.

Pickups

A server pickup is a networked pickup the server grants: when a player collects it, the server fires pickupCollect with serverCreated = true.

lsmp.createPickup

ServerLua Β· JS
luaLua
lsmp.createPickup(pickupHash, position [, opts]) --> integer?
jsJavaScript
lsmp.createPickup(pickupHash: number|string, position: Vec3Like, opts?: PickupOptions): number | null

Creates a pickup owned by the calling resource.

Parameters
ParameterTypeDescription
pickupHashhashPickup type: a PICKUP_* name or its hash.
positionvec3Where to place it.
opts optPickupOptionsSee the table below.
Returns (Lua)integer?: The pickup's netId, or nil/null with limit or permission (client entities disabled in that dimension).
Returns (JavaScript)number | null: The pickup's netId, or nil/null with limit or permission (client entities disabled in that dimension).
OptionTypeDefaultDescription
amountinteger0Amount granted (money, ammo...).
dimensiondimension0Dimension.
lifetimeMsms0Removed after this time (at most 24 h); 0 never expires. Removal happens within one second after the deadline.
modelhashthe type's modelAnother model to show.
collectorslist of playerIdanyoneOnly these players (at most 64) may collect it.
Example
luaLua
local id = lsmp.createPickup("PICKUP_MONEY_CASE", position, { amount = 500, lifetimeMs = 60000 })
lsmp.on("pickupCollect", function(playerId, netId, pickupHash, amount, serverCreated)
  if netId == id then giveMoney(playerId, amount) end
end)
jsJavaScript
const id = lsmp.createPickup("PICKUP_MONEY_CASE", position, { amount: 500, lifetimeMs: 60000 });
lsmp.on("pickupCollect", (playerId, netId, pickupHash, amount, serverCreated) => {
  if (netId === id) giveMoney(playerId, amount);
});

lsmp.setPickupCollectors

ServerLua Β· JS
luaLua
lsmp.setPickupCollectors(netId, players) --> boolean
jsJavaScript
lsmp.setPickupCollectors(netId: number, players: number[] | null): boolean

Restricts who may collect a pickup.

Parameters
ParameterTypeDescription
netIdnetIdThe pickup.
playerslist | nilUp to 64 playerIds; nil/null lets anyone collect it.
Returnsboolean: false with not-found or permission (pickup of another resource without entities.foreign).

Constant

lsmp.EntityType

SharedLua Β· JS
luaLua
lsmp.EntityType
jsJavaScript
lsmp.EntityType

Entity type strings.

lsmp.EntityType.Vehicle = "vehicle" Β· lsmp.EntityType.Ped = "ped" Β· lsmp.EntityType.Object = "object" Β· lsmp.EntityType.PlayerPed = "playerPed"

Server Β· Lua & JS

Ownership and AI intents

Which player simulates an entity, how long it lives, and AI orders that survive ownership changes.

Every networked entity is simulated by one player's game: its owner. The owner runs the physics and the AI, and sends the result to the server, which relays it to the others. By default LS:MP picks the owner for you: the nearest player who can simulate the entity adopts it, and ownership migrates when another player is much closer or when the owner leaves.

An entity without owner is orphan: it is frozen until someone adopts it. The entityOwnerChange event reports every change.

ReasonMeaning
"adopt"An orphan entity was taken by a nearby player.
"migrate"A clearly closer player took over.
"leaseExpired"The owner stopped sending updates.
"disconnect"The owner left.
"demand"A player took it on demand (for example by damaging an orphan entity).
"script"A script decided it (setEntityOwner).
"release"Nobody can take it: it becomes orphan.

Who owns it

lsmp.getEntityOwner

SharedLua Β· JS
luaLua
lsmp.getEntityOwner(netId) --> integer?
jsJavaScript
lsmp.getEntityOwner(netId: number): number | null

The player simulating an entity.

On the server, tell an orphan entity from an unknown one with lsmp.entityExists.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
Returns (Lua)integer?: A playerId; nil/null if the entity is orphan or unknown.
Returns (JavaScript)number | null: A playerId; nil/null if the entity is orphan or unknown.

lsmp.setEntityOwner

ServerLua Β· JS
luaLua
lsmp.setEntityOwner(netId, playerId) --> boolean
jsJavaScript
lsmp.setEntityOwner(netId: number, playerId: number | null): boolean

Gives the simulation of an entity to a player, or makes it orphan.

With the default "auto" policy, ownership can migrate again afterwards: set the policy to "pinned" to keep it on that player.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
playerIdplayerId?The new owner, in the same dimension as the entity; nil/null makes it orphan.
Returnsboolean: false with not-found (entity or player), invalid (other dimension, or the policy forbids it) or permission.

Owner policies

PolicyWho simulates
"auto" (default)The nearest capable player; ownership migrates freely.
"pinned"One player, set with setEntityOwner or owner at creation. No automatic migration; when that player leaves, the life policy decides.
"server"Nobody: the entity is never adopted and has no game AI. Use it for entities a server script moves itself.
"frozen"Nobody, and the entity is never synchronized: static scenery.

lsmp.setEntityOwnerPolicy

ServerLua Β· JS
luaLua
lsmp.setEntityOwnerPolicy(netId, policy) --> boolean
jsJavaScript
lsmp.setEntityOwnerPolicy(netId: number, policy: string): boolean

Sets how ownership of an entity may change.

Switching to "server" or "frozen" removes the current owner at once.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
policystring"auto", "pinned", "server" or "frozen".
Returnsboolean: false with not-found, or permission (entity of another resource without entities.foreign).
Example
luaLua
local car = lsmp.createEntity("vehicle", "police", position, { owner = playerId })
lsmp.setEntityOwnerPolicy(car, "pinned") -- stays on this player
jsJavaScript
const car = lsmp.createEntity("vehicle", "police", position, { owner: playerId });
lsmp.setEntityOwnerPolicy(car, "pinned"); // stays on this player

Life policies

PolicyWhen the entity is deleted
"whileRelevant" (default)When no player has it in range any more.
"keep"Never automatically. It also survives the stop of the resource that created it.
"withCreator"When its creator goes away: the player who created it leaves, or the resource that created it stops.

lsmp.setEntityLifePolicy

ServerLua Β· JS
luaLua
lsmp.setEntityLifePolicy(netId, policy) --> boolean
jsJavaScript
lsmp.setEntityLifePolicy(netId: number, policy: string): boolean

Sets when the engine may delete an entity.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
policystring"whileRelevant", "keep" or "withCreator".
Returnsboolean: false with not-found, or permission (entity of another resource without entities.foreign).

AI intents

Game AI tasks live in the owner's game, so they are lost when ownership migrates. An intent is a server-side order that travels with the entity and that every successive owner applies again: a wandering ped keeps wandering after its owner left. Set it once on the server; LS:MP does the rest.

FieldTypeDescription
typestring"idle" (stay in place), "wander" (around position within radius), "goTo" (go to position and stop), "follow", "flee", "combat" (relative to target), "guard" (stay within radius of position and attack what comes close), "custom" (see below), "none" (no order).
targetnetId or stringFor follow, flee, combat: a netId, "nearestPlayer" or "owner" (the owner's ped). The strings are resolved again by each owner.
positionvec3Anchor or destination.
radiusmetersWander radius, follow distance, guard radius.
grouphashRelationship group.
accuracyintegerShooting accuracy, 0..100.
keepTaskbooleanKeep the task even when the game would replace it (recommended for any lasting AI).
missionbooleanMark as a mission entity: not cleaned up with the ambient population.
runbooleanRun instead of walk.
hatesPlayersbooleanHostile to players.

With "custom", LS:MP applies no task: the new owner's client receives entityAdopt and your client script gives the orders itself. A complete example is in Recipe: server-spawned AI.

lsmp.setEntityIntent

ServerLua Β· JS
luaLua
lsmp.setEntityIntent(netId, intent) --> boolean
jsJavaScript
lsmp.setEntityIntent(netId: number, intent: EntityIntent): boolean

Sets the replicated AI intent of a ped.

A mistyped or out-of-range field raises.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
intentEntityIntentSee the table above.
Returnsboolean: false with not-found, or permission (entity of another resource without entities.foreign).
Example
luaLua
local ped = lsmp.createEntity("ped", "s_m_y_cop_01", position, { lifePolicy = "keep" })
lsmp.setEntityIntent(ped, {
  type = "guard", position = position, radius = 15.0,
  accuracy = 60, keepTask = true, mission = true, hatesPlayers = true,
})
jsJavaScript
const ped = lsmp.createEntity("ped", "s_m_y_cop_01", position, { lifePolicy: "keep" });
lsmp.setEntityIntent(ped, {
  type: "guard", position, radius: 15,
  accuracy: 60, keepTask: true, mission: true, hatesPlayers: true,
});

lsmp.clearEntityIntent

ServerLua Β· JS
luaLua
lsmp.clearEntityIntent(netId) --> boolean
jsJavaScript
lsmp.clearEntityIntent(netId: number): boolean

Removes the intent of a ped.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
Returnsboolean: false with not-found, or permission (entity of another resource without entities.foreign).

Constants

lsmp.OwnerChangeReason

ServerLua Β· JS
luaLua
lsmp.OwnerChangeReason
jsJavaScript
lsmp.OwnerChangeReason

The reason values of entityOwnerChange.

lsmp.OwnerChangeReason.Adopt = "adopt" Β· lsmp.OwnerChangeReason.Migrate = "migrate" Β· lsmp.OwnerChangeReason.LeaseExpired = "leaseExpired" Β· lsmp.OwnerChangeReason.Disconnect = "disconnect" Β· lsmp.OwnerChangeReason.Demand = "demand" Β· lsmp.OwnerChangeReason.Script = "script" Β· lsmp.OwnerChangeReason.Release = "release"

lsmp.OwnerPolicy

ServerLua Β· JS
luaLua
lsmp.OwnerPolicy
jsJavaScript
lsmp.OwnerPolicy

Owner policies.

lsmp.OwnerPolicy.Auto = "auto" Β· lsmp.OwnerPolicy.Pinned = "pinned" Β· lsmp.OwnerPolicy.Server = "server" Β· lsmp.OwnerPolicy.Frozen = "frozen"

lsmp.LifePolicy

ServerLua Β· JS
luaLua
lsmp.LifePolicy
jsJavaScript
lsmp.LifePolicy

Life policies.

lsmp.LifePolicy.WhileRelevant = "whileRelevant" Β· lsmp.LifePolicy.Keep = "keep" Β· lsmp.LifePolicy.WithCreator = "withCreator"

Server Β· Lua & JS

Dimensions

Separate copies of the world on one server: instances, arenas, interiors.

A dimension is a separate copy of the world on the same server. Players and entities only see, hear and synchronize with players and entities of their own dimension. Dimension 0 is the default world; every player starts there. Use dimensions for instances: an apartment interior, a race, a deathmatch arena, a tutorial.

  • Moving players and entities and changing dimension settings needs the dimensions.manage capability (granted by default; the operator can refuse it).
  • Moving a player does not move their vehicle or anything else: move entities with lsmp.setEntityDimension. A player's ped always follows its player.
  • Dimension settings (population, client entities) are not restored when the resource that changed them stops, and changing them fires no event.
  • The current dimension of a player is given by lsmp.getPlayerDimension.

Moving players and entities

lsmp.setPlayerDimension

ServerLua Β· JS
luaLua
lsmp.setPlayerDimension(playerId, dimension) --> boolean
jsJavaScript
lsmp.setPlayerDimension(playerId: number, dimension: number): boolean

Moves a player (and their ped) to another dimension.

The move is applied asynchronously: true means the request was accepted. playerDimensionChange fires on the server and on that player's client once it is done.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
dimensiondimensionThe dimension, 0..65535.
Returnsboolean: false with not-found or permission.
Example
luaLua
local function enterArena(playerId, arena)
  local car = lsmp.getVehiclePedIsIn(lsmp.getPlayerPed(playerId))
  lsmp.setPlayerDimension(playerId, arena)
  if car then lsmp.setEntityDimension(car, arena) end
end
jsJavaScript
function enterArena(playerId, arena) {
  const car = lsmp.getVehiclePedIsIn(lsmp.getPlayerPed(playerId));
  lsmp.setPlayerDimension(playerId, arena);
  if (car !== null) lsmp.setEntityDimension(car, arena);
}

lsmp.setEntityDimension

ServerLua Β· JS
luaLua
lsmp.setEntityDimension(netId, dimension) --> boolean
jsJavaScript
lsmp.setEntityDimension(netId: number, dimension: number): boolean

Moves an entity to another dimension.

A player's ped cannot be moved alone: move the player.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
dimensiondimensionThe dimension, 0..65535.
Returnsboolean: false with not-found, invalid (a player's ped) or permission.

lsmp.getEntityDimension

ServerLua Β· JS
luaLua
lsmp.getEntityDimension(netId) --> integer?
jsJavaScript
lsmp.getEntityDimension(netId: number): number | null

The dimension of an entity.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
Returns (Lua)integer?: nil/null if the entity is unknown.
Returns (JavaScript)number | null: nil/null if the entity is unknown.

lsmp.getPlayersInDimension

ServerLua Β· JS
luaLua
lsmp.getPlayersInDimension(dimension) --> {integer}
jsJavaScript
lsmp.getPlayersInDimension(dimension: number): number[]

The players currently in a dimension.

Parameters
ParameterTypeDescription
dimensiondimensionThe dimension, 0..65535.
Returns (Lua){integer}: A list of playerIds, possibly empty.
Returns (JavaScript)number[]: A list of playerIds, possibly empty.

Dimension settings

SettingDefaultEffect
populationon in dimension 0Ambient pedestrians and traffic. Turning it off stops the games of the players in the dimension from creating them.
client entitieson (server.cfg DefaultDimensionClientEntities)Whether the games of the players in the dimension may create their own networked entities (ambient and scripted). Off: only server scripts create entities there.

lsmp.setDimensionPopulation

ServerLua Β· JS
luaLua
lsmp.setDimensionPopulation(dimension, enabled) --> boolean
jsJavaScript
lsmp.setDimensionPopulation(dimension: number, enabled: boolean): boolean

Turns ambient population on or off in a dimension.

Parameters
ParameterTypeDescription
dimensiondimensionThe dimension, 0..65535.
enabledbooleanRequired: true or false.
Returnsboolean: false with permission.
Example
luaLua
lsmp.setDimensionPopulation(12, false)
lsmp.setDimensionClientEntities(12, false)
jsJavaScript
lsmp.setDimensionPopulation(12, false);
lsmp.setDimensionClientEntities(12, false);

lsmp.isDimensionPopulationEnabled

SharedLua Β· JS
luaLua
lsmp.isDimensionPopulationEnabled(dimension) --> boolean?
jsJavaScript
lsmp.isDimensionPopulationEnabled(dimension: number): boolean | null

Whether ambient population runs in a dimension.

On a client, only the local player's dimension is known: other dimensions return nil/null.

Parameters
ParameterTypeDescription
dimensiondimensionThe dimension, 0..65535.
Returns (Lua)boolean?
Returns (JavaScript)boolean | null

lsmp.setDimensionClientEntities

ServerLua Β· JS
luaLua
lsmp.setDimensionClientEntities(dimension, enabled) --> boolean
jsJavaScript
lsmp.setDimensionClientEntities(dimension: number, enabled: boolean): boolean

Lets the players' games create their own networked entities in a dimension, or not.

On by default. Off, every entity a client tries to create in the dimension (ambient traffic and pedestrians, and entities created by client scripts) is refused: only server scripts create entities there. Useful for instanced missions and arenas.

Parameters
ParameterTypeDescription
dimensiondimensionThe dimension, 0..65535.
enabledbooleanRequired: true or false.
Returnsboolean: false with permission.

lsmp.isDimensionClientEntitiesEnabled

ServerLua Β· JS
luaLua
lsmp.isDimensionClientEntitiesEnabled(dimension) --> boolean
jsJavaScript
lsmp.isDimensionClientEntitiesEnabled(dimension: number): boolean

Whether clients may create entities in a dimension.

Parameters
ParameterTypeDescription
dimensiondimensionThe dimension, 0..65535.
Returnsboolean: true by default.
Server Β· Lua & JS

Admission and moderation

Decide who may join, then kick, ban and whitelist from a script.

Admission

When somebody asks to join, the server first runs its own checks (bans, whitelist, player verification). Then playerPreConnection gives every resource a say, before the player downloads anything: refusing here costs them one round trip, refusing later costs them the whole download.

The handler receives one object, p:

FieldTypeDescription
namestringThe name they connect with.
lsmpIdint?Their account, nil/null for a guest.
guestbooleantrue for a guest.
verifiedbooleantrue when the LS:MP network confirmed the account; otherwise it is only what the client says.
ipstring?The address of the connection. Needs the players.identity capability.
hwidstring?This server's view of the player's machine (64 hex): stable on this server, different on every other one. Needs players.identity.
deny(reason)functionRefuse, with the sentence the player reads (256 bytes at most).
  • Any refusal wins. A handler that returns without calling p.deny lets the player in, and so does a handler that throws (it is logged).
  • A handler may be asynchronous (a database lookup): the verdict waits for every handler, up to PreConnectionTimeoutMs (server.cfg, 10 s by default). A handler still running then counts as a refusal: put a shorter timeout on your own queries.
luaLua
lsmp.on("playerPreConnection", function(p)
  if MAINTENANCE and not STAFF[p.lsmpId] then
    p.deny("The server is under maintenance. Come back in a few minutes.")
    return
  end
  if REQUIRE_ACCOUNT and p.guest then
    p.deny("This server needs an LS:MP account.")
  end
end)
jsJavaScript
lsmp.on('playerPreConnection', (p) => {
  if (MAINTENANCE && !STAFF.has(p.lsmpId)) {
    p.deny('The server is under maintenance. Come back in a few minutes.');
    return;
  }
  if (REQUIRE_ACCOUNT && p.guest) p.deny('This server needs an LS:MP account.');
});
⚠
Unverified accounts

Without player verification ("Verify players with LS:MP" in the admin panel), lsmpId is what the client declares. A staff list or a ban list keyed on it can then be bypassed by a modified client. Check p.verified when it matters.

β„Ή
Refusing every guest

No script is needed: turn off "Allow guest players" in the Identity & protection card of the admin panel (AllowGuests in server.cfg). It applies at once, and guests are refused before this event fires.

Removing players

lsmp.kickPlayer

ServerLua Β· JS
luaLua
lsmp.kickPlayer(playerId [, reason]) --> boolean
jsJavaScript
lsmp.kickPlayer(playerId: number, reason?: string): boolean

Disconnect a player.

playerLeave fires with the reason "kick" and your text as detail.

Needs the players.kick capability.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
reason optstringShown to the player, 256 bytes at most.
Returnsboolean: true if the player was connected.
Failure codeWhen
not-foundUnknown player.
permissionThe resource does not hold players.kick.

lsmp.banPlayer

ServerLua Β· JS
luaLua
lsmp.banPlayer(playerId [, opts]) --> {string}?
jsJavaScript
lsmp.banPlayer(playerId: number, opts?: BanOptions): string[] | null

Ban a connected player, then kick them.

The ban is recorded under each identifier type of modes the player has, so that they cannot come back by changing only one (a guest has no lsmp identifier). playerLeave fires with the reason "ban". Bans are kept by the server and listed in the admin panel.

Needs the players.ban capability.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
opts optBanOptionsSee BanOptions.
Returns (Lua){string}?: The identifier types actually banned, or nil/null if the player is unknown or the capability is missing.
Returns (JavaScript)string[] | null: The identifier types actually banned, or nil/null if the player is unknown or the capability is missing.
Failure codeWhen
not-foundUnknown player.
permissionThe resource does not hold players.ban.
Example
luaLua
lsmp.registerCommand("tempban", {
  help = "Ban a player for a week",
  params = { { name = "playerId" }, { name = "reason", optional = true } },
  permission = "admin.ban",
}, function(args, raw, source)
  local target = tonumber(args[1])
  local banned = target and lsmp.banPlayer(target, {
    reason = args[2] or "Banned for a week",
    durationMs = 7 * 86400000,
  })
  lsmp.log(banned and ("banned under " .. table.concat(banned, ", ")) or "no such player")
end)
jsJavaScript
lsmp.registerCommand('tempban', {
  help: 'Ban a player for a week',
  params: [{ name: 'playerId' }, { name: 'reason', optional: true }],
  permission: 'admin.ban',
}, (args, raw, source) => {
  const target = Number(args[0]);
  const banned = Number.isInteger(target)
    ? lsmp.banPlayer(target, { reason: args[1] || 'Banned for a week', durationMs: 7 * 86400000 })
    : null;
  lsmp.log(banned ? `banned under ${banned.join(', ')}` : 'no such player');
});

lsmp.removeBan

ServerLua Β· JS
luaLua
lsmp.removeBan(type, value) --> boolean
jsJavaScript
lsmp.removeBan(type: string, value: string | number): boolean

Lift a ban.

Needs the players.ban capability.

Parameters
ParameterTypeDescription
typestring"lsmp", "hwid", "ip" or "name".
valuestring|intThe banned value. For "lsmp", the account number is accepted.
Returnsboolean: true if a ban was lifted.
Failure codeWhen
not-foundNo such ban.
permissionThe resource does not hold players.ban.

Whitelist

While the whitelist is on, only the players it lists may join. The admin panel edits the same list.

lsmp.addToWhitelist

ServerLua Β· JS
luaLua
lsmp.addToWhitelist(type, value [, note]) --> boolean
jsJavaScript
lsmp.addToWhitelist(type: string, value: string | number, note?: string): boolean

Add an entry to the whitelist.

Needs the players.whitelist capability.

Parameters
ParameterTypeDescription
typestring"lsmp", "ip" or "name".
valuestring|intThe value. For "lsmp", the account number is accepted.
note optstringShown in the admin panel.
Returnsboolean: true if the entry was added.
Failure codeWhen
existsThe entry is already there.
permissionThe resource does not hold players.whitelist.

lsmp.removeFromWhitelist

ServerLua Β· JS
luaLua
lsmp.removeFromWhitelist(type, value) --> boolean
jsJavaScript
lsmp.removeFromWhitelist(type: string, value: string | number): boolean

Remove an entry from the whitelist.

Needs the players.whitelist capability.

Parameters
ParameterTypeDescription
typestring"lsmp", "ip" or "name".
valuestring|intThe value.
Returnsboolean: true if the entry was removed.
Failure codeWhen
not-foundNo such entry.
permissionThe resource does not hold players.whitelist.

lsmp.setWhitelistEnabled

ServerLua Β· JS
luaLua
lsmp.setWhitelistEnabled(enabled)
jsJavaScript
lsmp.setWhitelistEnabled(enabled: boolean): void

Switch the whitelist on or off.

Players already connected stay.

Needs the players.whitelist capability.

Parameters
ParameterTypeDescription
enabledbooleantrue to switch it on, false to switch it off.
Failure codeWhen
permissionThe resource does not hold players.whitelist.

lsmp.isWhitelistEnabled

ServerLua Β· JS
luaLua
lsmp.isWhitelistEnabled() --> boolean
jsJavaScript
lsmp.isWhitelistEnabled(): boolean

Whether the whitelist is on.

Returnsboolean: true while it is on.

Developer status

lsmp.setPlayerDev

ServerLua Β· JS
luaLua
lsmp.setPlayerDev(playerId, dev) --> boolean
jsJavaScript
lsmp.setPlayerDev(playerId: number, dev: boolean): boolean

Allow or forbid DevTools to a player on this server.

DevTools let the player inspect this server's web interfaces. The lsmp.devtools permission gives the same right through groups. Read it back with isPlayerDev.

Needs the players.dev capability.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
devbooleantrue to allow, false to forbid.
Returnsboolean: true if the player is connected.
Failure codeWhen
not-foundUnknown player.
permissionThe resource does not hold players.dev.

BanOptions

FieldTypeDefaultDescription
modesstrings{"lsmp", "hwid"}Identifier types to ban: "lsmp", "hwid", "ip".
reasonstringβ€”Shown to the player and in the admin panel.
durationMsmspermanentHow long the ban lasts.
Server Β· Lua & JS

Persistent storage

A persistent key/value store private to each resource, with no setup.

lsmp.storage is a small persistent key/value store, private to each resource and kept on the server's disk across restarts. It needs no setup: use it for settings, counters, small player records. For large or relational data, use MySQL; to compare the options, see Storing data.

  • Each resource has its own store: two resources never see each other's keys. The store follows the resource's identity: an operator resource and a marketplace mod with the same folder name never share it.
  • Values are any transportable value: numbers (integers and floats stay distinct), strings, booleans, bytes, vectors, lists and maps. A value is at most 64 KiB encoded, and a store at most 16 MiB, each entry counting 64 bytes on top of its key and value (about 260 000 entries at most).
  • Reads and writes are immediate (in memory). Changes reach the disk within about 750 ms; lsmp.storage.flush() waits until they are written. Stores are also flushed when the server stops.
  • If a store file cannot be read, the resource's calls fail with io and the file is never overwritten, so nothing is lost.
luaLua
local function addPlaytime(account, minutes)
  local key = "playtime:" .. account
  local total = (lsmp.storage.get(key) or 0) + minutes
  lsmp.storage.set(key, total)
  return total
end

for _, key in ipairs(lsmp.storage.keys("playtime:")) do
  lsmp.log(key, lsmp.storage.get(key))
end
jsJavaScript
function addPlaytime(account, minutes) {
  const key = `playtime:${account}`;
  const total = (lsmp.storage.get(key) ?? 0) + minutes;
  lsmp.storage.set(key, total);
  return total;
}

for (const key of lsmp.storage.keys("playtime:")) lsmp.log(key, lsmp.storage.get(key));
βœ“
Keys

Prefix keys by kind ("player:", "house:") so lsmp.storage.keys can list one kind. Key players on their account (lsmp.getPlayerLsmpId), never on their playerId or name.

Functions

lsmp.storage.get

ServerLua Β· JS
luaLua
lsmp.storage.get(key) --> any?
jsJavaScript
lsmp.storage.get(key: string): Value | null

Reads a stored value.

Parameters
ParameterTypeDescription
keystringKey: 1 to 256 bytes, any content.
Returns (Lua)any?: The value, or nil/null if the key is absent; nil, "io" (JavaScript: null and getLastError() = "io") if the store is unreadable.
Returns (JavaScript)Value | null: The value, or nil/null if the key is absent; nil, "io" (JavaScript: null and getLastError() = "io") if the store is unreadable.

lsmp.storage.set

ServerLua Β· JS
luaLua
lsmp.storage.set(key, value) --> boolean
jsJavaScript
lsmp.storage.set(key: string, value: Value): boolean

Stores a value, or deletes the key when the value is nil/null.

A value over 64 KiB encoded raises.

Parameters
ParameterTypeDescription
keystringKey: 1 to 256 bytes, any content.
valuevalueThe value; nil/null deletes the key.
Returnsboolean: false with limit (the store would exceed 16 MiB) or io (unreadable store).
Example
luaLua
local ok, err = lsmp.storage.set("house:12", { owner = 4211, price = 250000, locked = true })
if not ok then lsmp.error("cannot save house: " .. err) end
jsJavaScript
if (!lsmp.storage.set("house:12", { owner: 4211, price: 250000, locked: true })) {
  lsmp.error(`cannot save house: ${lsmp.getLastError()}`);
}

lsmp.storage.delete

ServerLua Β· JS
luaLua
lsmp.storage.delete(key) --> boolean
jsJavaScript
lsmp.storage.delete(key: string): boolean

Deletes a key.

Parameters
ParameterTypeDescription
keystringKey: 1 to 256 bytes, any content.
Returnsboolean: false if the key was absent.

lsmp.storage.keys

ServerLua Β· JS
luaLua
lsmp.storage.keys([prefix]) --> {string}
jsJavaScript
lsmp.storage.keys(prefix: string = ""): string[]

The keys that start with a prefix, sorted.

Parameters
ParameterTypeDescription
prefix optstringPrefix; empty lists every key. Default: ""
Returns (Lua){string}: The keys.
Returns (JavaScript)string[]: The keys.

lsmp.storage.flush

ServerLua Β· JS
luaLua
lsmp.storage.flush([cb]) --> boolean, err
jsJavaScript
lsmp.storage.flush(): Promise<boolean>

Writes this resource's pending changes to disk now. Asynchronous.

Call it before an operation that must not lose a recent write, for example in resourceStop.

Returns (Lua)boolean, err: true once the store is on disk; fails with io if the write failed.
Returns (JavaScript)Promise<boolean>: true once the store is on disk; fails with io if the write failed.
Example
luaLua
lsmp.storage.set("config:motd", "Welcome!")
lsmp.storage.flush(function(ok, err)
  if not ok then lsmp.error("flush failed: " .. err) end
end)
jsJavaScript
lsmp.storage.set("config:motd", "Welcome!");
lsmp.storage.flush().catch((e) => lsmp.error(`flush failed: ${e.code}`));
Server Β· Lua & JS

MySQL

Asynchronous queries to a MySQL or MariaDB database through a connection pool.

Resources can use a MySQL or MariaDB database through a connection pool. Queries are asynchronous: the server never waits for the database. Results use the same values in Lua and JavaScript.

⚠
Sandbox

A database reaches outside the server, so a sandboxed resource cannot create a pool: createPool fails with permission. The operator trusts a resource with "sandbox": false in resources.json.

  • Connections open on demand, up to connectionLimit, and are reused.
  • Always pass values as parameters (?), never by building SQL text: parameters cannot be used for SQL injection.
  • SQL NULL is lsmp.null in Lua and null in JavaScript, in results and in parameters. Integers beyond 2^53 are BigInt in JavaScript.
  • Pools of a resource are closed when it stops; queries already sent complete first (within the stop grace time).

Creating a pool

lsmp.mysql.createPool

ServerLua Β· JS
luaLua
lsmp.mysql.createPool(opts) --> MysqlPool?
jsJavaScript
lsmp.mysql.createPool(opts: MysqlPoolOptions): MysqlPool | null

Creates a connection pool.

Parameters
ParameterTypeDescription
optsMysqlPoolOptionsConnection settings (table below).
Returns (Lua)MysqlPool?: The pool, or nil/null with permission (sandboxed resource) or limit (8 pools per resource).
Returns (JavaScript)MysqlPool | null: The pool, or nil/null with permission (sandboxed resource) or limit (8 pools per resource).
OptionTypeDefaultDescription
hoststring"127.0.0.1"Server address.
portinteger3306Server port.
userstringrequiredUser name.
passwordstring""Password.
databasestringβ€”Default database.
charsetstring"utf8mb4""utf8mb4", "utf8", "latin1" or "binary".
connectionLimitinteger8Connections at most, 1..64.
connectTimeoutMsms10000Deadline to open a connection.
queryTimeoutMsms0A query running longer fails with timeout and its connection is closed. 0 = no limit.
Example
luaLua
local db = lsmp.mysql.createPool({
  host = "127.0.0.1", user = "game", password = "secret", database = "lsmp",
  connectionLimit = 4, queryTimeoutMs = 5000,
})
jsJavaScript
const db = lsmp.mysql.createPool({
  host: "127.0.0.1", user: "game", password: "secret", database: "lsmp",
  connectionLimit: 4, queryTimeoutMs: 5000,
});

Queries

Failures: error (SQL error), io (connection problem), timeout (queryTimeoutMs), cancelled (pool closed). An SQL error comes with details { errno, sqlState, message }: the third value in Lua, fields of the Error in JavaScript.

pool.query

ServerLua Β· JS
luaLua
pool:query(sql [, params] [, cb]) --> MysqlResult, err
jsJavaScript
pool.query(sql: string, params?: Value[]): Promise<MysqlResult>

Runs one statement. Asynchronous.

A SELECT returns the list of rows, each row a table keyed by column name. Other statements return { affectedRows, insertId, warningCount }.

Parameters
ParameterTypeDescription
sqlstringThe statement, with ? placeholders.
params optlistValues for the placeholders, in order: numbers, strings, booleans, lsmp.null/null.
Returns (Lua)MysqlResult, err: The rows, or the write summary.
Returns (JavaScript)Promise<MysqlResult>: The rows, or the write summary.
Example
luaLua
-- inside a host coroutine (event handler, file body, lsmp.createThread)
local rows, err, details = db:query("SELECT name, money FROM players WHERE account = ?", { account })
if not rows then
  lsmp.error("query failed: " .. err .. " " .. (details and details.message or ""))
elseif rows[1] then
  lsmp.log(rows[1].name .. " has $" .. rows[1].money)
end

local res = db:query("UPDATE players SET money = money + ? WHERE account = ?", { 100, account })
jsJavaScript
async function loadPlayer(account) {
  try {
    const rows = await db.query("SELECT name, money FROM players WHERE account = ?", [account]);
    if (rows.length) lsmp.log(`${rows[0].name} has $${rows[0].money}`);
    const res = await db.query("UPDATE players SET money = money + ? WHERE account = ?", [100, account]);
    lsmp.log(`${res.affectedRows} row(s) changed`);
  } catch (e) {
    lsmp.error(`query failed: ${e.code} ${e.message}`);
  }
}

pool.transaction

ServerLua Β· JS
luaLua
pool:transaction(fn [, cb]) --> any, err
jsJavaScript
pool.transaction(fn: Function): Promise<Value>

Runs several statements in one transaction. Asynchronous.

fn(tx) runs inside the transaction; use tx:query(sql, params) / tx.query(sql, params) like pool.query. When fn returns, the transaction is committed and its result is the result of transaction. When fn raises or rejects, it is rolled back and the error is passed on.

Parameters
ParameterTypeDescription
fnfnfn(tx); in Lua it may suspend on tx:query.
Returns (Lua)any, err: What fn returned.
Returns (JavaScript)Promise<Value>: What fn returned.
Example
luaLua
local ok, err = pcall(function()
  return db:transaction(function(tx)
    tx:query("UPDATE accounts SET balance = balance - ? WHERE id = ?", { 50, from })
    tx:query("UPDATE accounts SET balance = balance + ? WHERE id = ?", { 50, to })
    return true
  end)
end)
if not ok then lsmp.error("transfer failed: " .. tostring(err)) end
jsJavaScript
async function transfer(from, to, amount) {
  await db.transaction(async (tx) => {
    await tx.query("UPDATE accounts SET balance = balance - ? WHERE id = ?", [amount, from]);
    await tx.query("UPDATE accounts SET balance = balance + ? WHERE id = ?", [amount, to]);
  });
}

pool.close

ServerLua Β· JS
luaLua
pool:close([cb]) --> boolean, err
jsJavaScript
pool.close(): Promise<boolean>

Lets queued queries finish, then closes the pool. Asynchronous.

Queries sent after the call fail with cancelled. Pools are also closed automatically when the resource stops.

Returns (Lua)boolean, err: true when closed.
Returns (JavaScript)Promise<boolean>: true when closed.
Server Β· Lua & JS

Files

Asynchronous file access on the server, with a private data folder for each resource.

lsmp.fs reads and writes files on the server machine. Every call is asynchronous: the disk work happens in the background and the server keeps running. To read files shipped inside your resource, use lsmp.readResourceFile instead.

  • Every resource has a private data folder, lsmp.getDataPath(), always readable and writable, sandboxed or not. Store your files there.
  • A sandboxed resource can only reach its data folder and the folders the operator lists in SandboxFsRead / SandboxFsWrite (server.cfg). Anything else fails with permission.
  • Use / in paths on every system.
CodeWhen
not-foundThe file or folder does not exist.
existsmkdir on an existing path, writeFile with exclusive on an existing file.
permissionRefused by the sandbox or by the system.
invalidMalformed path, a folder where a file is expected, a folder that is not empty, append with exclusive.
limitFile larger than 512 MiB to read, or not enough memory.
ioAny other disk error.

Failures come with details { message } (third value in Lua, message of the Error in JavaScript).

Data folder

lsmp.getDataPath

ServerLua Β· JS
luaLua
lsmp.getDataPath() --> string
jsJavaScript
lsmp.getDataPath(): string

The absolute path of the resource's private data folder, created on first call.

The folder follows the resource's identity: an operator resource and a marketplace mod with the same folder name never share it.

Returns (Lua)string: The path, without a trailing /.
Returns (JavaScript)string: The path, without a trailing /.
Example
luaLua
local file = lsmp.getDataPath() .. "/scores.json"
jsJavaScript
const file = `${lsmp.getDataPath()}/scores.json`;

Files

lsmp.fs.readFile

ServerLua Β· JS
luaLua
lsmp.fs.readFile(path [, opts] [, cb]) --> string|string, err
jsJavaScript
lsmp.fs.readFile(path: string, opts?: ReadFileOptions): Promise<string | Uint8Array>

Reads a whole file (512 MiB at most). Asynchronous.

Parameters
ParameterTypeDescription
pathstringAbsolute, or relative to the server folder.
opts optReadFileOptions{ binary = true } returns bytes (Uint8Array in JavaScript); text (UTF-8) by default.
Returns (Lua)string, err: The content.
Returns (JavaScript)Promise<string | Uint8Array>: The content.
Example
luaLua
lsmp.fs.readFile(lsmp.getDataPath() .. "/scores.json", function(text, err)
  if not text then
    if err ~= "not-found" then lsmp.warn("cannot read scores: " .. err) end
    return
  end
  scores = lsmp.json.decode(text)
end)
jsJavaScript
async function loadScores() {
  try {
    return JSON.parse(await lsmp.fs.readFile(`${lsmp.getDataPath()}/scores.json`));
  } catch (e) {
    if (e.code !== "not-found") lsmp.warn(`cannot read scores: ${e.code}`);
    return {};
  }
}

lsmp.fs.writeFile

ServerLua Β· JS
luaLua
lsmp.fs.writeFile(path, data [, opts] [, cb]) --> boolean, err
jsJavaScript
lsmp.fs.writeFile(path: string, data: string|Uint8Array|ArrayBuffer, opts?: WriteFileOptions): Promise<boolean>

Writes a file, replacing it or appending to it. Asynchronous.

Parameters
ParameterTypeDescription
pathstringAbsolute, or relative to the server folder.
datadataA string, or bytes (lsmp.bytes/string in Lua; Uint8Array or ArrayBuffer in JavaScript).
opts optWriteFileOptions{ append = false, exclusive = false }: append adds at the end; exclusive fails with exists if the file exists. Not both.
Returns (Lua)boolean, err: true when written.
Returns (JavaScript)Promise<boolean>: true when written.
Example
luaLua
lsmp.fs.writeFile(lsmp.getDataPath() .. "/chat.log", line .. "\n", { append = true }, function(ok, err)
  if not ok then lsmp.warn("log write failed: " .. err) end
end)
jsJavaScript
lsmp.fs.writeFile(`${lsmp.getDataPath()}/chat.log`, `${line}\n`, { append: true })
  .catch((e) => lsmp.warn(`log write failed: ${e.code}`));

lsmp.fs.rename

ServerLua Β· JS
luaLua
lsmp.fs.rename(from, to [, cb]) --> boolean, err
jsJavaScript
lsmp.fs.rename(from: string, to: string): Promise<boolean>

Renames or moves a file or folder. Asynchronous.

Parameters
ParameterTypeDescription
fromstringCurrent path.
tostringNew path.
Returns (Lua)boolean, err
Returns (JavaScript)Promise<boolean>

lsmp.fs.remove

ServerLua Β· JS
luaLua
lsmp.fs.remove(path [, opts] [, cb]) --> boolean, err
jsJavaScript
lsmp.fs.remove(path: string, opts?: RemoveOptions): Promise<boolean>

Removes a file or a folder. Asynchronous.

A folder must be empty unless recursive is set. Removing a path that does not exist succeeds.

Parameters
ParameterTypeDescription
pathstringAbsolute, or relative to the server folder.
opts optRemoveOptions{ recursive = false }.
Returns (Lua)boolean, err
Returns (JavaScript)Promise<boolean>

Folders

lsmp.fs.mkdir

ServerLua Β· JS
luaLua
lsmp.fs.mkdir(path [, opts] [, cb]) --> boolean, err
jsJavaScript
lsmp.fs.mkdir(path: string, opts?: MkdirOptions): Promise<boolean>

Creates a folder. Asynchronous.

Without recursive, the parent must exist and the folder must not (exists). With recursive, missing parents are created and an existing folder is fine.

Parameters
ParameterTypeDescription
pathstringAbsolute, or relative to the server folder.
opts optMkdirOptions{ recursive = false }.
Returns (Lua)boolean, err
Returns (JavaScript)Promise<boolean>

lsmp.fs.list

ServerLua Β· JS
luaLua
lsmp.fs.list(path [, cb]) --> {DirEntry}, err
jsJavaScript
lsmp.fs.list(path: string): Promise<DirEntry[]>

The entries of a folder, sorted by name. Asynchronous.

Parameters
ParameterTypeDescription
pathstringAbsolute, or relative to the server folder.
Returns (Lua){DirEntry}, err: A list of { name, isDir, size, mtimeMs } (size 0 for folders).
Returns (JavaScript)Promise<DirEntry[]>: A list of { name, isDir, size, mtimeMs } (size 0 for folders).
Example
luaLua
lsmp.createThread(function()
  local entries, err = lsmp.fs.list(lsmp.getDataPath())
  for _, e in ipairs(entries or {}) do
    lsmp.log(e.name, e.isDir and "dir" or e.size .. " bytes")
  end
end)
jsJavaScript
(async () => {
  for (const e of await lsmp.fs.list(lsmp.getDataPath())) {
    lsmp.log(e.name, e.isDir ? "dir" : `${e.size} bytes`);
  }
})();

lsmp.fs.stat

ServerLua Β· JS
luaLua
lsmp.fs.stat(path [, cb]) --> FileStat?, err
jsJavaScript
lsmp.fs.stat(path: string): Promise<FileStat | null>

Information about a path. Asynchronous.

A path that does not exist is not a failure: the result is nil/null.

Parameters
ParameterTypeDescription
pathstringAbsolute, or relative to the server folder.
Returns (Lua)FileStat?, err: { isDir, isFile, size, mtimeMs }, or nil/null if nothing is there.
Returns (JavaScript)Promise<FileStat | null>: { isDir, isFile, size, mtimeMs }, or nil/null if nothing is there.
Server Β· Lua & JS

HTTP routes

Answer HTTP requests under /res/<resource>/ on the server's HTTP port.

A resource can answer HTTP requests on the server's HTTP port (HttpPort in server.cfg), under its own path: http://<server>:<HttpPort>/res/<resource name>/.... Use it for webhooks, a small JSON API for your website, or files generated on the fly. Pages shown in game load their files from the resource package, not from here (see Web interfaces).

  • One route per resource, covering every path under /res/<name>/. It is removed when the resource stops; requests not answered yet get 503. At most 256 requests are handled at once for one route (more get 503) and 64 from one client address (more get 429; the loopback is not counted).
  • Requests are public: anyone who can reach the port can call your route. Check a secret or a signature for anything that is not public.
  • A request body over maxBodyBytes is answered 413 without calling the handler. A handler that does not answer within timeoutMs leaves the client with 504. A handler that raises gets the client a 500, and the error is logged.

Serving

lsmp.http.serve

ServerLua Β· JS
luaLua
lsmp.http.serve(fn [, opts]) --> function
jsJavaScript
lsmp.http.serve(fn: Function, opts?: HttpServeOptions): () => boolean

Serves /res/<resource name>/... with a handler function.

The handler receives a request and returns the response: a string (sent as 200, text/plain), or a response table. In JavaScript it may return a Promise. A second call while the route exists raises.

Parameters
ParameterTypeDescription
fnfnfn(req) -> response.
opts optHttpServeOptions{ maxBodyBytes = 1048576, timeoutMs = 10000 }: largest accepted body (at most 16 MiB) and answer deadline (at most 300 000 ms).
Returns (Lua)function: The function that removes the route.
Returns (JavaScript)() => boolean: The function that removes the route.
Request fieldTypeDescription
methodstringUpper case: "GET", "POST"...
pathstringThe path after /res/<name>, starting with /.
querytableQuery parameters, decoded: { page = "2" }.
headerstableHeader names in lower case; repeated headers joined with ", ".
bodystring or bytesThe body; bytes (Uint8Array in JavaScript) when it is not valid UTF-8.
addressstringThe client's IP address.
Response fieldTypeDefaultDescription
statusinteger200100..599.
headerstableβ€”Header values are strings. Content-Length, Transfer-Encoding and Connection are set by the server and refused; a value with a line break raises.
bodystring or bytes""The body.
jsonvalueβ€”Sent as JSON with Content-Type: application/json. Not with body.
Example
luaLua
lsmp.http.serve(function(req)
  if req.method == "GET" and req.path == "/status" then
    return {
      status = 200,
      headers = { ["content-type"] = "application/json" },
      body = lsmp.json.encode({ players = #lsmp.getPlayers() }),
    }
  end
  return { status = 404, body = "not found" }
end)
jsJavaScript
lsmp.http.serve(async (req) => {
  if (req.method === "GET" && req.path === "/status") {
    return { json: { players: lsmp.getPlayers().length } };
  }
  return { status: 404, body: "not found" };
});

Example: a webhook

luaLua
local SECRET = "change-me"

lsmp.http.serve(function(req)
  if req.method ~= "POST" or req.headers["x-secret"] ~= SECRET then
    return { status = 403, body = "forbidden" }
  end
  local data = lsmp.json.decode(req.body)
  if not data then return { status = 400, body = "bad json" } end
  lsmp.emitAllClients("news:flash", data.text)
  return { status = 204 }
end)
jsJavaScript
const SECRET = "change-me";

lsmp.http.serve((req) => {
  if (req.method !== "POST" || req.headers["x-secret"] !== SECRET) return { status: 403, body: "forbidden" };
  let data;
  try { data = JSON.parse(req.body); } catch { return { status: 400, body: "bad json" }; }
  lsmp.emitAllClients("news:flash", data.text);
  return { status: 204 };
});

To call other web services from a script, see the HTTP client.

Server Β· Lua & JS

Console commands

Add commands to the server console and the admin panel, and let players run them with the right permission.

A command registered by a server script answers in the server terminal and in the admin panel console. The built-in commands (start, stop, kick, say...) come first and cannot be replaced.

Players do not type server commands directly: a resource passes their line to executeCommand, usually from the chat (the bundled chat resource runs every line that starts with /). The player's permissions then decide which handlers run.

OptionWho may run the command
(no permission)The console, and players holding command.<name>.
permission = "admin.kick"The console, and players holding that permission.
permission = falseThe console and every player.
restricted = trueThe console only, never a player.

Registering

lsmp.registerCommand

ServerLua Β· JS
luaLua
lsmp.registerCommand(name [, opts], fn) --> off
jsJavaScript
lsmp.registerCommand(name: string, opts: CommandOptions | undefined, fn: Function): () => boolean  // also (name, fn)

Add a command to the server console.

The handler receives (args, raw, source, invoker):

- args: the words after the command name, split on spaces; a word that starts with " runs to the next " (no escapes);
- raw: the rest of the line as typed, leading spaces removed;
- source: the playerId when a player runs it, nil/null from the console or the admin panel;
- invoker: who ran it: the admin user, the player's name, or resource:<name> for a script.

Several handlers may share a name, in any resource and either language: they all run, each filtered by its own permission. Names are 1 to 64 characters (A-Z a-z 0-9 _ . : -), case-insensitive, with an optional leading /.

Parameters
ParameterTypeDescription
namestringThe command name.
opts optCommandOptionsSee CommandOptions.
fnfnThe handler.
Returns (Lua)function: A function that unregisters this handler and returns true if it was registered.
Returns (JavaScript)() => boolean: A function that unregisters this handler and returns true if it was registered.
β„Ή
Answering a player

lsmp.log writes to the server log. To answer a player who ran the command, send them a message (for example the chat's chat:message event) when source is not nil/null.

Example
luaLua
lsmp.perms.declare("admin.announce", "Use /announce")

lsmp.registerCommand("announce", {
  help = "Show a message to every player",
  params = { { name = "text", help = "What to say" } },
  permission = "admin.announce",
}, function(args, raw, source, invoker)
  if raw == "" then
    lsmp.log("usage: announce <text>")
    return
  end
  lsmp.emitAllClients("announce", raw)
  lsmp.log(invoker .. " announced: " .. raw)
end)
jsJavaScript
lsmp.perms.declare('admin.announce', 'Use /announce');

lsmp.registerCommand('announce', {
  help: 'Show a message to every player',
  params: [{ name: 'text', help: 'What to say' }],
  permission: 'admin.announce',
}, (args, raw, source, invoker) => {
  if (!raw) {
    lsmp.log('usage: announce <text>');
    return;
  }
  lsmp.emitAllClients('announce', raw);
  lsmp.log(`${invoker} announced: ${raw}`);
});

lsmp.unregisterCommand

SharedLua Β· JS
luaLua
lsmp.unregisterCommand(name, fn) --> boolean
jsJavaScript
lsmp.unregisterCommand(name: string, fn: Function): boolean

Remove a command handler of this resource.

The same as calling the function registerCommand returned. A resource's commands are removed when it stops. Works for server and client commands.

Parameters
ParameterTypeDescription
namestringThe command name.
fnfnThe handler that was registered.
Returnsboolean: true if the handler was registered.

Running a command for a player

lsmp.executeCommand

ServerLua Β· JS
luaLua
lsmp.executeCommand(source, line) --> "ok" | "unknown" | "denied" | "invalid"
jsJavaScript
lsmp.executeCommand(source: number | null, line: string): "ok" | "unknown" | "denied" | "invalid"

Run a console line on behalf of a player, or with console rights.

With a playerId, the player must hold the permission of a handler for it to run; handlers marked restricted never run. With nil/null, every handler runs, as from the console. Built-in commands are not reachable this way. Handlers run on the next server tick, after the call returns.

Needs the commands.execute capability for a player, commands.console for console rights.

Parameters
ParameterTypeDescription
sourceplayerId?The player, or nil/null for console rights.
linestringThe line, command name first, with or without a leading /.
Returnsstring: "ok" (handlers will run), "unknown" (no such command), "denied" (the player may not run it, or left) or "invalid" (no command name in the line); nil/null when the capability is missing.
Failure codeWhen
permissionThe resource does not hold the capability.
Example
luaLua
-- In a chat resource: a line starting with "/" is a command.
lsmp.onClient("chat:say", function(source, text)
  if text:sub(1, 1) ~= "/" then return end
  local verdict = lsmp.executeCommand(source, text:sub(2))
  if verdict == "unknown" then
    lsmp.emitClient(source, "chat:message", { name = "", text = "Unknown command.", system = true })
  elseif verdict == "denied" then
    lsmp.emitClient(source, "chat:message", { name = "", text = "Not allowed.", system = true })
  end
end)
jsJavaScript
// In a chat resource: a line starting with "/" is a command.
lsmp.onClient('chat:say', (source, text) => {
  if (typeof text !== 'string' || text[0] !== '/') return;
  const verdict = lsmp.executeCommand(source, text.slice(1));
  if (verdict === 'unknown') lsmp.emitClient(source, 'chat:message', { name: '', text: 'Unknown command.', system: true });
  else if (verdict === 'denied') lsmp.emitClient(source, 'chat:message', { name: '', text: 'Not allowed.', system: true });
});

CommandOptions

FieldTypeDefaultDescription
helpstringβ€”One line shown by help in the console and in completions.
paramslistβ€”Parameters shown while typing: { name, help, type, optional } each. Display only: the handler still receives strings.
permissionstring | boolean"command.<name>"The permission a player needs; false for every player.
restrictedbooleanfalsetrue: the console only, never a player.
Server Β· Lua & JS

Server and resource lifecycle

When your scripts start and stop, and what they can still do on the way out.

Resource states

A resource is in one state at a time, the same for its Lua and its JavaScript scripts: stopped β†’ starting β†’ started or failed; started β†’ stopping β†’ stopped. On the server, every enabled resource starts once, with the server, and runs until the server stops: nothing starts, stops or restarts a resource in between, neither the console nor a script. A failed resource stays failed until the next server start. lsmp.getResourceState and the resources console command show it.

Starting a resource

  1. Its dependencies start first. A dependency that is missing, disabled in resources.json or failed makes the resource failed, with the reason in the log.
  2. Its server scripts run in manifest order, JavaScript files before Lua files. In JavaScript, a module-level await is waited for before the next file and before the resource counts as started, up to ResourceStartTimeoutMs (server.cfg, 30 s by default). A Lua file runs until it ends or first waits (a while true do lsmp.wait(...) end loop is fine).
  3. A script that throws, or a module-level Promise that rejects, makes the resource failed: what it already registered or created is removed, the error and the file are logged, and the resources that depend on it do not start.
  4. Otherwise the resource is started and resourceStart (name) fires in every resource, itself included.

Stopping a resource

  1. It happens when the server shuts down (below). The resources that depend on it stop first.
  2. resourceStop (name) fires, in the stopping resource first, then in the others. Its handlers may wait (a Promise in JS, a suspended handler in Lua) up to ResourceStopGraceMs (2 s by default): this is the moment to save. Everything the resource owns still works during the handlers.
  3. Then the resource is cleaned up: event handlers, commands, timers and pending waits, its HTTP route, its MySQL pools (queries already queued finish first), its storage is written to disk, the entities and pickups it created (except lifePolicy = "keep"), its synchronized scenes, its voice channels, its declared permissions, and the weather it forced is restored.
luaLua
lsmp.on("resourceStop", function(name)
  if name ~= lsmp.getResourceName() then return end
  for playerId, data in pairs(sessions) do
    lsmp.storage.set("session:" .. data.account, data)
  end
end)
jsJavaScript
lsmp.on('resourceStop', async (name) => {
  if (name !== lsmp.getResourceName()) return;
  for (const data of sessions.values()) lsmp.storage.set(`session:${data.account}`, data);
  await lsmp.storage.flush();
});

Changing a resource

The server reads its resources once, when it starts. To apply a change (an edited file, a new or removed resource, resources.json), restart the server: players are disconnected with the shutdown message and join again. No console command and no function starts, stops or restarts a resource while the server runs.

On the client, a script can still mount and unmount resources while the game runs: see Hot resources.

Server start and shutdown

MomentWhat happens
StartEvery enabled resource starts, in dependency order: the only start of the server's resources. Then serverStart fires once, when they all reached started or failed and the game port listens.
Shutdownquit, the admin panel, an update, or a stop signal: no new connection; playerLeave with the reason "shutdown" for every player, who is then disconnected (no event or call from that player reaches a handler afterwards); serverStop, whose handlers may wait up to ShutdownGraceMs (5 s by default); every resource stops (as above, within what is left of that time); storage and permissions are written; the process exits.
CrashNothing of the above runs. Save important data as it changes, not only at shutdown.
luaLua
lsmp.on("serverStop", function()
  local res, err = db:query("UPDATE servers SET online = 0 WHERE id = ?", { SERVER_ID })
  if not res then lsmp.warn("could not mark the server offline: " .. err) end
end)
jsJavaScript
lsmp.on('serverStop', async () => {
  try {
    await db.query('UPDATE servers SET online = 0 WHERE id = ?', [SERVER_ID]);
  } catch (err) {
    lsmp.warn(`could not mark the server offline: ${err.code}`);
  }
});

On the client

A client starts the server's resources when it joins (those mounted automatically, in dependency order) and stops them all when it leaves. resourceStart and resourceStop fire there too; a client's resourceStop handlers get 1 s. In between, a client script can mount and unmount resources with lsmp.mountResource and lsmp.unmountResource: the only change made to resources while connected.

Server Β· Lua & JS

Resource capabilities and sandbox

What a resource is allowed to do: sensitive functions (capabilities) and access to the machine (sandbox).

Two independent protections let a server owner run resources they did not write, including marketplace mods:

  • Capabilities decide which sensitive lsmp functions a resource may use: kicking players, moving them between dimensions, deleting other resources' entities...
  • The sandbox decides what a resource may do on the machine: files, network, databases, processes.

Both are set by the operator, never by the resource itself.

Capabilities

Operator resources get every capability by default. Marketplace mods get them too, except the four marked "refused". The operator changes them per resource in the admin panel (see Console and admin panel).

CapabilityCoversOperator resourceMarketplace mod
perms.manageWrites of lsmp.perms (groups, members, rules)grantedgranted
commands.executelsmp.executeCommand(playerId, line): run a command for a player (their permissions still apply)grantedgranted
commands.consolelsmp.executeCommand(nil, line): run a command with console rightsgrantedgranted
players.kicklsmp.kickPlayergrantedgranted
players.banlsmp.banPlayer, lsmp.removeBangrantedgranted
players.whitelistWhitelist functionsgrantedgranted
players.devlsmp.setPlayerDevgrantedgranted
players.identityIP address and hardware id (getPlayerIdentifier(s), playerPreConnection)grantedgranted
dimensions.managesetPlayerDimension, setEntityDimension, setDimensionPopulation, setDimensionLockdowngrantedgranted
voice.manageWrites of lsmp.voice (channels, members, muting)grantedgranted
benefits.consumelsmp.benefits.consume, consumeRevocationgrantedgranted
benefits.readlsmp.benefits.fetch, events benefitGrant and benefitRevokegrantedrefused
world.weatherlsmp.weather.set, resumeCycle, setSeedgrantedrefused
entities.foreignActing on entities, pickups and synchronized scenes created by another resource or by a clientgrantedrefused

A refused capability is never an error: the function fails with the code permission (false/nil with the code in Lua, false/null and lsmp.getLastError() in JavaScript, a rejected Promise for asynchronous functions). Events reserved to a capability are simply not delivered. The server log shows one warning per resource and capability at most once a minute, with the capability name; the admin panel counts the refusals.

βœ“
Write resources that degrade well

Test the result of capability-protected calls and tell the operator what is missing, rather than assuming success. A mod that needs world.weather can log once "grant world.weather to enable weather control" and keep working without it.

Sandbox

Server resources run in a sandbox by default (Sandbox in server.cfg). The operator trusts one resource with "sandbox": false in resources.json; an unsandboxed resource has full access to the machine, and the server log says so when it starts.

AreaSandboxed resource
FilesIts data folder (read and write) and its own package (lsmp.readResourceFile). Other folders only when listed in SandboxFsRead / SandboxFsWrite. Elsewhere: permission.
Outgoing networkAs allowed by SandboxNetConnect (default: everything). Refused: permission.
Listening socketsOnly what SandboxNetListen allows (default: nothing). Use lsmp.http.serve instead.
Databaseslsmp.mysql.createPool fails with permission.
Environment variablesOnly those listed in SandboxEnv (default NODE_ENV, TZ, LANG, LC_ALL).
Processes and native codeRefused: no child processes, no native modules, no access to the server process.
Lua standard libraryFunctions that reach outside (io, os.execute, load, debug...) raise an error that names the lsmp alternative.
Blocking codeLua or JavaScript code that runs longer than SandboxWatchdogSec (default 10 s) without suspending is interrupted.
β„Ή
Capabilities and the sandbox are separate

Unsandboxing a resource gives it the machine, not extra capabilities, and granting a capability does not open the sandbox.

lsmp.isSandboxed

ServerLua Β· JS
luaLua
lsmp.isSandboxed() --> boolean
jsJavaScript
lsmp.isSandboxed(): boolean

Whether the calling resource runs in the sandbox.

Returnsboolean
Example
luaLua
if lsmp.isSandboxed() then
  lsmp.warn("MySQL disabled: set \"sandbox\": false for this resource in resources.json")
end
jsJavaScript
if (lsmp.isSandboxed()) {
  lsmp.warn('MySQL disabled: set "sandbox": false for this resource in resources.json');
}
Server Β· Lua & JS

Synchronized scenes

Animations played together by several entities, the same on every client.

A synchronized scene plays animations on several entities at once, aligned to one origin, and every client sees the same thing: two peds shaking hands, a ped sitting on a bench, a character getting into a car with a door animation. The server starts it; every client of the dimension plays it, including players who stream the entities in later.

  • Participants are networked entities (peds, objects, vehicles), 1 to 8 per scene, in the same dimension and within 50 m of each other.
  • A resource stops its own scenes; acting on a scene of another resource, or using entities created by another resource as participants, needs the entities.foreign capability. Players' peds can always take part.
  • Scenes of a resource stop when it stops. A scene also stops when a participant disappears.
  • Clients receive syncSceneStart and syncSceneStop for each participant.

Scene definition

FieldTypeDefaultDescription
positionvec3requiredOrigin of the scene.
rotationrotation{0, 0, 0}Rotation of the origin, in degrees.
rotationOrderinteger2Euler order of rotation, 0..5 (the game's usual order is 2).
phasenumber0Starting point, 0..1 of the animation.
ratenumber1Playback speed.
holdLastFramebooleanfalseStay on the last frame at the end.
loopedbooleanfalseLoop.
durationMsms0Stop the scene after this time; 0 = no limit.
participantslistrequired1 to 8 participants (below).
Participant fieldTypeDefaultDescription
netIdnetIdrequiredThe entity.
dictstringrequiredAnimation dictionary (1 to 63 bytes).
clipstringrequiredAnimation name (1 to 63 bytes).
blendInnumber8Blend-in speed.
blendOutnumber-8Blend-out speed.
flagsinteger0Game scene flags.
ikFlagsinteger0Game IK flags.
offsettableβ€”{ x, y, z, heading } offset of this participant from the origin.

Functions

lsmp.startSyncScene

ServerLua Β· JS
luaLua
lsmp.startSyncScene(def) --> integer?
jsJavaScript
lsmp.startSyncScene(def: SyncSceneDef): number | null

Starts a synchronized scene played by every client.

A malformed definition (missing field, wrong type, more than 8 participants) raises.

Parameters
ParameterTypeDescription
defSyncSceneDefThe scene definition (tables above).
Returns (Lua)integer?: The scene id, or nil/null with not-found (a participant does not exist), invalid (participants in different dimensions or too far apart), limit (too many scenes) or permission.
Returns (JavaScript)number | null: The scene id, or nil/null with not-found (a participant does not exist), invalid (participants in different dimensions or too far apart), limit (too many scenes) or permission.
Example
luaLua
local scene = lsmp.startSyncScene({
  position = { x = -1037.0, y = -2737.0, z = 20.17 },
  rotation = { x = 0, y = 0, z = 150 },
  participants = {
    { netId = pedA, dict = "mp_common", clip = "givetake1_a" },
    { netId = pedB, dict = "mp_common", clip = "givetake1_b" },
  },
})
if not scene then lsmp.warn("scene refused: " .. lsmp.getLastError()) end
jsJavaScript
const scene = lsmp.startSyncScene({
  position: { x: -1037, y: -2737, z: 20.17 },
  rotation: { x: 0, y: 0, z: 150 },
  participants: [
    { netId: pedA, dict: "mp_common", clip: "givetake1_a" },
    { netId: pedB, dict: "mp_common", clip: "givetake1_b" },
  ],
});
if (scene === null) lsmp.warn(`scene refused: ${lsmp.getLastError()}`);

lsmp.stopSyncScene

ServerLua Β· JS
luaLua
lsmp.stopSyncScene(sceneId) --> boolean
jsJavaScript
lsmp.stopSyncScene(sceneId: number): boolean

Stops a scene.

Parameters
ParameterTypeDescription
sceneIdintegerThe scene, as returned by startSyncScene.
Returnsboolean: false with not-found or permission (scene of another resource).

lsmp.setSyncScenePhase

ServerLua Β· JS
luaLua
lsmp.setSyncScenePhase(sceneId, phase [, rate]) --> boolean
jsJavaScript
lsmp.setSyncScenePhase(sceneId: number, phase: number, rate?: number): boolean

Moves a running scene to another point, and optionally changes its speed.

Parameters
ParameterTypeDescription
sceneIdintegerThe scene, as returned by startSyncScene.
phasenumber0..1.
rate optnumberNew speed (>= 0); unchanged when absent.
Returnsboolean: false with not-found or permission.

lsmp.isSyncSceneActive

ServerLua Β· JS
luaLua
lsmp.isSyncSceneActive(sceneId) --> boolean
jsJavaScript
lsmp.isSyncSceneActive(sceneId: number): boolean

Whether a scene is running.

Parameters
ParameterTypeDescription
sceneIdintegerThe scene, as returned by startSyncScene.
Returnsboolean

lsmp.getEntitySyncScene

SharedLua Β· JS
luaLua
lsmp.getEntitySyncScene(netId) --> SyncSceneInfo?
jsJavaScript
lsmp.getEntitySyncScene(netId: number): SyncSceneInfo | null

The synchronized scene an entity is playing.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
Returns (Lua)SyncSceneInfo?: { sceneId, dict, clip }, or nil/null if it plays none.
Returns (JavaScript)SyncSceneInfo | null: { sceneId, dict, clip }, or nil/null if it plays none.

Client API

Client Β· Lua & JS

Local player, spawn and death

Who the local player is, when and where they appear, what happens when they die, and how to leave the server.

When a player joins, their ped exists but stays hidden behind the LS:MP loading screen: frozen, invisible, without collision. LS:MP never places the player by itself, and never respawns them after a death. A client script decides both: that is what makes character selection, spawn menus, death screens and timers possible.

  1. Resources start

    Every client resource of the server runs its top-level code.

  2. Auto spawn

    Once they all ran, the auto-spawn handler is called, once: the resource that set it with setAutoSpawnHandler picks a place and calls lsmp.spawn. A gamemode that spawns players itself turns this off with setAutoSpawn(false).

  3. Spawn

    lsmp.spawn loads the world around the point, places the ped, closes the loading screen, and fires playerSpawn on this client and on the server.

⚠
A server needs a spawn resource

If nothing spawns the player, the loading screen stays. After 30 s a warning is logged; after 60 s the client leaves the server cleanly instead of hanging. A gamemode that needs more time (a character creator) calls closeLoadingScreen to show its own interface: the timer then stops. The bundled spawn-mgr resource is a complete spawn manager (examples).

Identity

lsmp.getLocalPlayer

ClientLua Β· JS
luaLua
lsmp.getLocalPlayer() --> integer?
jsJavaScript
lsmp.getLocalPlayer(): number | null

The playerId of the local player.

The same number the server uses for this player. It is not the game's playerId() native, which is a local slot. playerJoin is not fired for the local player: read this at start instead.

Returns (Lua)integer?: The playerId, or nil/null outside a session.
Returns (JavaScript)number | null: The playerId, or nil/null outside a session.

lsmp.getGameScreen

ClientLua Β· JS
luaLua
lsmp.getGameScreen() --> ScreenSize?
jsJavaScript
lsmp.getGameScreen(): ScreenSize | null

The size of the game image, in pixels.

To convert pixel positions into the normalized 0..1 coordinates used by worldToScreen and the drawing natives.

Returns (Lua)ScreenSize?: { width, height }, or nil/null before the game window exists.
Returns (JavaScript)ScreenSize | null: { width, height }, or nil/null before the game window exists.

Spawning

lsmp.spawn

ClientLua Β· JS
luaLua
lsmp.spawn(position [, opts]) --> boolean
jsJavaScript
lsmp.spawn(position: Vec3Like, opts?: SpawnOptions): boolean

Make the local player appear at a position.

The world around the point is loaded first, then the ped is placed with its feet at position, made visible and given back its controls; the loading screen closes on the first spawn. playerSpawn fires when it is done. Also works later, to move a living player with a full reload of the area.

Parameters
ParameterTypeDescription
positionvec3Where the feet go.
opts optSpawnOptions{ heading, model }: heading in degrees (default 0), ped model as a hash or name (default: the current model).
Returnsboolean: true if the spawn was started.
Failure codeWhen
disconnectedNot in a session.
Example
luaLua
local POINTS = {
  { x = 195.0, y = -933.7, z = 30.7, h = 145.0 },
  { x = -1037.6, y = -2737.6, z = 20.2, h = 330.0 },
}

lsmp.setAutoSpawnHandler(function()
  local p = POINTS[math.random(#POINTS)]
  lsmp.spawn({ x = p.x, y = p.y, z = p.z }, { heading = p.h, model = "mp_m_freemode_01" })
end)
jsJavaScript
const POINTS = [
  { x: 195.0, y: -933.7, z: 30.7, h: 145.0 },
  { x: -1037.6, y: -2737.6, z: 20.2, h: 330.0 },
];

lsmp.setAutoSpawnHandler(() => {
  const p = POINTS[Math.floor(Math.random() * POINTS.length)];
  lsmp.spawn({ x: p.x, y: p.y, z: p.z }, { heading: p.h, model: 'mp_m_freemode_01' });
});

lsmp.setAutoSpawnHandler

ClientLua Β· JS
luaLua
lsmp.setAutoSpawnHandler(fn)
jsJavaScript
lsmp.setAutoSpawnHandler(fn: Function | null): void

Set the function that spawns the player when they join.

Called once per session, after every client resource ran its top-level code, if auto spawn is still on and nothing spawned the player yet. When several resources set one, the last call wins; it is removed when its resource stops.

Parameters
ParameterTypeDescription
fnfn?The handler, or nil/null to remove this resource's.

lsmp.setAutoSpawn

ClientLua Β· JS
luaLua
lsmp.setAutoSpawn(enabled)
jsJavaScript
lsmp.setAutoSpawn(enabled: boolean): void

Turn the auto spawn on or off.

A gamemode with its own arrival (character selection, a lobby) calls lsmp.setAutoSpawn(false) at the top of its client script, then calls lsmp.spawn when it is ready. The setting belongs to the resource: the last writer wins, and it is restored when that resource stops.

Parameters
ParameterTypeDescription
enabledbooleanfalse to keep the player hidden until a script spawns them.

lsmp.closeLoadingScreen

ClientLua Β· JS
luaLua
lsmp.closeLoadingScreen()
jsJavaScript
lsmp.closeLoadingScreen(): void

Lift the loading screen without spawning the player.

For an arrival that shows its own interface first (character creator, rules to accept). The ped stays hidden until lsmp.spawn.

Death and respawn

playerDeath (playerId, killerId, weaponHash, position, flags, killerEntity) fires on every client for every player who dies. Compare playerId with lsmp.getLocalPlayer() to react to your own death. The dead player stays down until a script resurrects them.

lsmp.resurrect

ClientLua Β· JS
luaLua
lsmp.resurrect(position [, opts]) --> boolean
jsJavaScript
lsmp.resurrect(position: Vec3Like, opts?: ResurrectOptions): boolean

Bring the dead local player back to life at a position.

The ped is revived in place and moved, keeping its netId: nothing is streamed again for the other players. Call it whenever you like: after a timer, a death screen, a key press.

Parameters
ParameterTypeDescription
positionvec3Where the feet go.
opts optResurrectOptions{ heading } in degrees (default 0).
Returnsboolean: true if the player was resurrected.
Failure codeWhen
disconnectedNot in a session.
Example
luaLua
local RESPAWN_DELAY_MS = 5000

lsmp.on("playerDeath", function(playerId, killerId, weaponHash, position)
  if playerId ~= lsmp.getLocalPlayer() then return end
  lsmp.wait(RESPAWN_DELAY_MS)
  lsmp.resurrect({ x = position.x, y = position.y, z = position.z + 0.5 }, { heading = 0 })
end)
jsJavaScript
const RESPAWN_DELAY_MS = 5000;

lsmp.on('playerDeath', async (playerId, killerId, weaponHash, position) => {
  if (playerId !== lsmp.getLocalPlayer()) return;
  await lsmp.wait(RESPAWN_DELAY_MS);
  lsmp.resurrect({ x: position.x, y: position.y, z: position.z + 0.5 }, { heading: 0 });
});

Leaving

lsmp.disconnect

ClientLua Β· JS
luaLua
lsmp.disconnect([reason]) --> boolean
jsJavaScript
lsmp.disconnect(reason?: string): boolean

Leave the server.

The server sees playerLeave with the reason "quit" and your text as detail.

Parameters
ParameterTypeDescription
reason optstringWhy, 127 bytes at most.
Returnsboolean: true if the client was in a session.
Failure codeWhen
disconnectedNot in a session.
Client Β· Lua & JS

Entities and streaming

Networked entities on the client: netIds against game handles, what is streamed in, and who simulates what.

A networked entity (a vehicle, a ped, an object the server knows) has two names:

NameWhat it isUsed by
netIdThe same number on the server and every client, for the entity's whole life.lsmp functions, events, network messages, meta.
HandleThe game's own number for the entity on this client. It exists only while the entity is built here.Game natives, outlines.

A client builds only the entities near its player (streaming). An entity far away is known by its netId but has no handle here. Never store handles: store netIds and convert when you need a native.

Converting

lsmp.getEntityFromNetId

ClientLua Β· JS
luaLua
lsmp.getEntityFromNetId(netId) --> integer?
jsJavaScript
lsmp.getEntityFromNetId(netId: number): number | null

The game handle of a networked entity.

Right after the server creates an entity, its netId is known at once but the game builds it over the next frames: retry for a moment before giving up.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
Returns (Lua)integer?: The handle, or nil/null while the entity is not built on this client.
Returns (JavaScript)number | null: The handle, or nil/null while the entity is not built on this client.
Failure codeWhen
not-foundThe entity is not built on this client.
Example
luaLua
local function waitForEntity(netId, timeoutMs)
  local deadline = lsmp.getTickCount() + timeoutMs
  while lsmp.getTickCount() < deadline do
    local handle = lsmp.getEntityFromNetId(netId)
    if handle then return handle end
    lsmp.wait(100)
  end
  return nil
end
jsJavaScript
async function waitForEntity(netId, timeoutMs) {
  const deadline = lsmp.getTickCount() + timeoutMs;
  while (lsmp.getTickCount() < deadline) {
    const handle = lsmp.getEntityFromNetId(netId);
    if (handle !== null) return handle;
    await lsmp.wait(100);
  }
  return null;
}

lsmp.getNetIdFromEntity

ClientLua Β· JS
luaLua
lsmp.getNetIdFromEntity(entity) --> integer?
jsJavaScript
lsmp.getNetIdFromEntity(entity: number): number | null

The netId of a game handle.

Parameters
ParameterTypeDescription
entityhandleA game handle.
Returns (Lua)integer?: The netId, or nil/null for an entity LS:MP does not network (a local prop, ambient traffic of this client only).
Returns (JavaScript)number | null: The netId, or nil/null for an entity LS:MP does not network (a local prop, ambient traffic of this client only).
Failure codeWhen
not-foundThe entity is not networked.

Simulation (ownership)

Each networked entity is simulated by one client, its owner: that client runs its physics and AI, and the others follow. Ownership moves on its own as players come and go. lsmp.getEntityOwner tells who it is; the server can pin it.

lsmp.requestEntityOwnership

ClientLua Β· JS
luaLua
lsmp.requestEntityOwnership(netId) --> boolean
jsJavaScript
lsmp.requestEntityOwnership(netId: number): boolean

Ask to simulate an entity.

Useful before driving or moving something another player simulates. The server decides: when it accepts, entityAdopt fires on this client. An entity pinned by the server is not handed over.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
Returnsboolean: true if the request was sent.
Failure codeWhen
not-foundUnknown entity.
disconnectedNot in a session.

Events

EventArgumentsWhen
entityStreamIn(netId, entity)An entity was built on this client; the handle is valid in the handler. Other players' peds come through here; your own never does.
entityStreamOut(netId)The entity was removed from this client; its handle is no longer valid.
entityAdopt(netId)This client started simulating the entity.
entityRelease(netId)This client stopped simulating it.

Events are not replayed: entities already in range when a script starts are found with lsmp.getEntitiesInRadius or lsmp.getGamePool.

Client Β· Lua & JS

World helpers (raycast, ground, screen, pools)

Ready-made answers to common questions about the game world: what a line hits, where the ground is, where a point appears on screen, what exists around you.

Each of these wraps one or two game natives with a single call, vectors in and out, and no output parameters. They answer for this client's game: only what is loaded around the local player exists here.

lsmp.raycast

ClientLua Β· JS
luaLua
lsmp.raycast(from, to [, opts]) --> RaycastResult
jsJavaScript
lsmp.raycast(from: Vec3Like, to: Vec3Like, opts?: RaycastOptions): RaycastResult

What a straight line from from to to hits first.

It tests collision, not pixels: glass, fences and objects without collision can be crossed. To know what is drawn at a point of the screen, use the picker.

Parameters
ParameterTypeDescription
fromvec3Start of the line.
tovec3End of the line.
opts optRaycastOptionsSee RaycastOptions.
ReturnsRaycastResult: A RaycastResult.
Example
luaLua
-- What is the player looking at, up to 50 m?
local cam = getGameplayCamCoord()
local rot = getGameplayCamRot(2)
local pitch, yaw = math.rad(rot.x), math.rad(rot.z)
local dir = { x = -math.sin(yaw) * math.cos(pitch), y = math.cos(yaw) * math.cos(pitch), z = math.sin(pitch) }
local hit = lsmp.raycast(cam, { x = cam.x + dir.x * 50, y = cam.y + dir.y * 50, z = cam.z + dir.z * 50 },
  { ignore = playerPedId() })
if hit.hit and hit.entity then
  lsmp.log("looking at entity " .. hit.entity)
end
jsJavaScript
// What is the player looking at, up to 50 m?
const cam = getGameplayCamCoord();
const rot = getGameplayCamRot(2);
const pitch = rot.x * Math.PI / 180, yaw = rot.z * Math.PI / 180;
const dir = { x: -Math.sin(yaw) * Math.cos(pitch), y: Math.cos(yaw) * Math.cos(pitch), z: Math.sin(pitch) };
const hit = lsmp.raycast(cam, { x: cam.x + dir.x * 50, y: cam.y + dir.y * 50, z: cam.z + dir.z * 50 },
  { ignore: playerPedId() });
if (hit.hit && hit.entity !== null) lsmp.log(`looking at entity ${hit.entity}`);

lsmp.getGroundZ

ClientLua Β· JS
luaLua
lsmp.getGroundZ(position [, opts]) --> number?
jsJavaScript
lsmp.getGroundZ(position: Vec3Like, opts?: GroundOptions): number | null

The height of the ground below a point.

The game looks down from position. Far from the player the map's collision is not loaded and there is no answer: bring the player (or the camera) closer first, or request the collision with the natives and retry.

Parameters
ParameterTypeDescription
positionvec3The point to look down from.
opts optGroundOptions{ water }: true counts the water surface as ground (default false).
Returns (Lua)number?: The height, or nil/null when no ground was found.
Returns (JavaScript)number | null: The height, or nil/null when no ground was found.
Example
luaLua
local p = getEntityCoords(playerPedId(), true)
local ground = lsmp.getGroundZ({ x = p.x + 10, y = p.y, z = p.z + 50 })
if ground then lsmp.log(("ground at %.2f"):format(ground)) end
jsJavaScript
const p = getEntityCoords(playerPedId(), true);
const ground = lsmp.getGroundZ({ x: p.x + 10, y: p.y, z: p.z + 50 });
if (ground !== null) lsmp.log(`ground at ${ground.toFixed(2)}`);

lsmp.worldToScreen

ClientLua Β· JS
luaLua
lsmp.worldToScreen(position) --> ScreenPoint
jsJavaScript
lsmp.worldToScreen(position: Vec3Like): ScreenPoint

Where a world position appears on the screen.

x and y are normalized: 0,0 is the top-left corner, 1,1 the bottom-right. They match the drawing natives (drawRect, text) directly; multiply by getGameScreen for pixels. Call it every frame, from lsmp.onTick, to follow a moving point.

Parameters
ParameterTypeDescription
positionvec3The world position.
ReturnsScreenPoint: { x, y, onScreen }; onScreen is false behind the camera or outside the screen.
Example
luaLua
lsmp.onTick(function()
  local p = getEntityCoords(playerPedId(), true)
  local s = lsmp.worldToScreen({ x = p.x, y = p.y, z = p.z + 1.2 })
  if s.onScreen then drawRect(s.x, s.y, 0.01, 0.015, 255, 200, 0, 200, false) end
end)
jsJavaScript
lsmp.onTick(() => {
  const p = getEntityCoords(playerPedId(), true);
  const s = lsmp.worldToScreen({ x: p.x, y: p.y, z: p.z + 1.2 });
  if (s.onScreen) drawRect(s.x, s.y, 0.01, 0.015, 255, 200, 0, 200, false);
});

lsmp.getGamePool

ClientLua Β· JS
luaLua
lsmp.getGamePool([opts]) --> {integer}
jsJavaScript
lsmp.getGamePool(opts?: QueryOptions): Uint32Array

The game handles of the networked entities that exist on this client.

Networked entities only: those of the session that have a game instance here. Entities your script creates with natives for this client alone are not listed; keep their handles. To find entities around a point by netId, see getEntitiesInRadius.

Parameters
ParameterTypeDescription
opts optQueryOptions{ types }: entity types to include, among "vehicle", "ped", "object" and "playerPed" (lsmp.EntityType); by default every type except player peds.
Returns (Lua){integer}: The handles (JS: Uint32Array).
Returns (JavaScript)Uint32Array: The handles (JS: Uint32Array).
Example
luaLua
local vehicles = lsmp.getGamePool({ types = { "vehicle" } })
lsmp.log(#vehicles .. " vehicles on this client")
jsJavaScript
const vehicles = lsmp.getGamePool({ types: [lsmp.EntityType.Vehicle] });
lsmp.log(`${vehicles.length} vehicles on this client`);

Shapes

RaycastOptions

FieldTypeDefaultDescription
flagsint-1 (everything)What the line can hit, as the game's shape test flags: 1 map, 2 vehicles, 4 peds (8 ped capsules), 16 objects, 256 vegetation.
ignorehandleβ€”An entity the line goes through, usually the player's ped or vehicle.

RaycastResult

FieldTypeDefaultDescription
hitbooleanβ€”true if the line hit something.
positionvec3?β€”Where.
normalvec3?β€”The surface direction at that point.
entityhandle?β€”The entity hit; absent for the map.
Client Β· Lua & JS

HUD, blips and money

The money shown in the game HUD, and the parts of the HUD LS:MP lets scripts adjust. Blips use the game's natives.

Money

The game shows a wallet and a bank amount in the top-right corner. LS:MP lets a script set them, so the HUD matches your server's own economy. The amounts are display only: your money lives in your scripts and your database, on the server.

β„Ή
One resource at a time

The displayed money is a setting owned by the resource that set it: the last writer wins, and the game's values come back when that resource stops.

lsmp.hud.setMoney

ClientLua Β· JS
luaLua
lsmp.hud.setMoney(wallet, bank) --> boolean
jsJavaScript
lsmp.hud.setMoney(wallet: number, bank: number): boolean

Show these amounts in the HUD.

Parameters
ParameterTypeDescription
walletintCash, 0 to 2147483647.
bankintBank, 0 to 2147483647.
Returnsboolean: true if the amounts are shown.
Failure codeWhen
unavailableThe HUD cannot be changed at this moment (no session).
Example
luaLua
lsmp.onServer("economy:balance", function(wallet, bank)
  lsmp.hud.setMoney(wallet, bank)
end)
jsJavaScript
lsmp.onServer('economy:balance', (wallet, bank) => {
  lsmp.hud.setMoney(wallet, bank);
});

lsmp.hud.resetMoney

ClientLua Β· JS
luaLua
lsmp.hud.resetMoney() --> boolean
jsJavaScript
lsmp.hud.resetMoney(): boolean

Give the money display back to the game.

Returnsboolean: true if this resource had set the money.

lsmp.hud.getMoney

ClientLua Β· JS
luaLua
lsmp.hud.getMoney() --> HudMoney?
jsJavaScript
lsmp.hud.getMoney(): HudMoney | null

The amounts the HUD shows.

Returns (Lua)HudMoney?: { wallet, bank }, or nil/null when no script sets them.
Returns (JavaScript)HudMoney | null: { wallet, bank }, or nil/null when no script sets them.

Replay recording

lsmp.hud.hideReplayRecordingThisFrame

ClientLua Β· JS
luaLua
lsmp.hud.hideReplayRecordingThisFrame()
jsJavaScript
lsmp.hud.hideReplayRecordingThisFrame(): void

Hide the replay recording indicator for this frame.

Call it every frame, from lsmp.onTick, while your own interface covers that corner of the screen.

Blips

LS:MP draws no player blips by itself. Use the game's blip natives (addBlipForEntity, addBlipForCoord, setBlipSprite...) from a client script. Blips attached to an entity go away with it when it is streamed out. The bundled player-blips resource puts a blip on every player near you (examples).

luaLua
lsmp.on("entityStreamIn", function(netId, entity)
  if not isEntityAPed(entity) or not isPedAPlayer(entity) then return end
  local blip = addBlipForEntity(entity)
  setBlipSprite(blip, 1)
  setBlipColour(blip, 0)
end)
jsJavaScript
lsmp.on('entityStreamIn', (netId, entity) => {
  if (!isEntityAPed(entity) || !isPedAPlayer(entity)) return;
  const blip = addBlipForEntity(entity);
  setBlipSprite(blip, 1);
  setBlipColour(blip, 0);
});
Client Β· Lua & JS

Nametags

The names LS:MP draws above other players: how visible, how far, how large.

LS:MP draws the name of each nearby player above their head. A client script can change how they look, for every player or for one, without drawing anything itself.

β„Ή
Owned settings

A style belongs to the resource that set it: the last writer wins, and the previous style comes back when that resource stops. nil/null removes this resource's style.

lsmp.nametags.setStyle

ClientLua Β· JS
luaLua
lsmp.nametags.setStyle(style)
jsJavaScript
lsmp.nametags.setStyle(style: NametagStyle | null): void

Set the style of every nametag.

Fields not given keep their default.

Parameters
ParameterTypeDescription
styleNametagStyle?A NametagStyle, or nil/null to remove this resource's.
Example
luaLua
-- Names only within 15 m, a bit smaller.
lsmp.nametags.setStyle({ distance = 15, scale = 0.8 })
jsJavaScript
// Names only within 15 m, a bit smaller.
lsmp.nametags.setStyle({ distance: 15, scale: 0.8 });

lsmp.nametags.setPlayerStyle

ClientLua Β· JS
luaLua
lsmp.nametags.setPlayerStyle(playerId, style)
jsJavaScript
lsmp.nametags.setPlayerStyle(playerId: number, style: NametagStyle | null): void

Set the style of one player's nametag.

It wins over the general style for that player. For example, always show your teammates, and hide the others.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
styleNametagStyle?A NametagStyle, or nil/null to remove this resource's.
Example
luaLua
for _, id in ipairs(teammates) do
  lsmp.nametags.setPlayerStyle(id, { visibility = "always", beacon = true })
end
jsJavaScript
for (const id of teammates) {
  lsmp.nametags.setPlayerStyle(id, { visibility: 'always', beacon: true });
}

lsmp.nametags.getStyle

ClientLua Β· JS
luaLua
lsmp.nametags.getStyle() --> NametagStyle
jsJavaScript
lsmp.nametags.getStyle(): NametagStyle

The general nametag style in force.

Every field is filled in. A player's own style is read with getPlayerStyle.

ReturnsNametagStyle: A NametagStyle.

lsmp.nametags.getPlayerStyle

ClientLua Β· JS
luaLua
lsmp.nametags.getPlayerStyle(playerId) --> NametagStyle?
jsJavaScript
lsmp.nametags.getPlayerStyle(playerId: number): NametagStyle | null

The style in force for one player's nametag.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
Returns (Lua)NametagStyle?: A NametagStyle, or nil/null for an unknown player.
Returns (JavaScript)NametagStyle | null: A NametagStyle, or nil/null for an unknown player.
Failure codeWhen
not-foundUnknown player.

NametagStyle

FieldTypeDefaultDescription
alphanumber1Opacity, 0 to 1. 0 hides the name.
scalenumber1Size factor, greater than 0.
distancemeters256Shown up to this distance from the camera.
visibilitystring"auto""auto" (shown when the player's ped is visible), "always" (even when it is not) or "never".
beaconbooleanfalseDraw a marker above the name.
Client Β· Lua & JS

Outlines and picking

Draw a line around an entity or a piece of the map, and find out exactly what is drawn under a point of the screen.

Outlines

An outline is drawn around an entity, as thick at 200 m as at 2 m, and hidden by walls like the entity itself. It takes a game handle, not a netId (see Entities and streaming).

Outlines belong to the resource that drew them: a resource cannot change or remove another resource's outline, and its outlines go away when it stops. At most 32 outlines exist at once, shared by every resource: outline what matters, and take down what you put up.

lsmp.outline.showEntity

ClientLua Β· JS
luaLua
lsmp.outline.showEntity(entity [, opts]) --> boolean
jsJavaScript
lsmp.outline.showEntity(entity: number, opts?: OutlineOptions): boolean

Outline an entity, or change the style of this resource's outline on it.

Parameters
ParameterTypeDescription
entityhandleA game handle.
opts optOutlineOptionsSee OutlineOptions.
Returnsboolean: true if the outline is drawn.
Failure codeWhen
not-foundThe handle is not usable, or the 32 outlines are taken.
permissionAnother resource outlines this entity.
Example
luaLua
local vehicle = getVehiclePedIsIn(playerPedId(), false)
if vehicle ~= 0 then
  lsmp.outline.showEntity(vehicle, { color = "#40beff", width = 3 })
end
jsJavaScript
const vehicle = getVehiclePedIsIn(playerPedId(), false);
if (vehicle) lsmp.outline.showEntity(vehicle, { color: '#40beff', width: 3 });

lsmp.outline.hideEntity

ClientLua Β· JS
luaLua
lsmp.outline.hideEntity(entity) --> boolean
jsJavaScript
lsmp.outline.hideEntity(entity: number): boolean

Remove this resource's outline from an entity.

Parameters
ParameterTypeDescription
entityhandleA game handle.
Returnsboolean: true if this resource outlined it.

lsmp.outline.hasEntity

ClientLua Β· JS
luaLua
lsmp.outline.hasEntity(entity) --> boolean
jsJavaScript
lsmp.outline.hasEntity(entity: number): boolean

Whether this resource outlines an entity.

Parameters
ParameterTypeDescription
entityhandleA game handle.
Returnsboolean: true while the outline is drawn.

lsmp.outline.showGeometry

ClientLua Β· JS
luaLua
lsmp.outline.showGeometry(entity, geomKey [, opts]) --> boolean
jsJavaScript
lsmp.outline.showGeometry(entity: number | null, geomKey: number, opts?: OutlineOptions): boolean

Outline one piece of geometry: a door, a window, one wall of a building.

The geometry key comes from the picker (geometry.key). Buildings and terrain are not entities: pass nil/null as the entity for map geometry.

Parameters
ParameterTypeDescription
entityhandle?The entity the piece belongs to, or nil/null for the map.
geomKeyuintThe geometry key.
opts optOutlineOptionsSee OutlineOptions; position helps to find map geometry again.
Returnsboolean: true if the outline is drawn.
Failure codeWhen
not-foundNo such geometry, or the 32 outlines are taken.
permissionAnother resource outlines this geometry.

lsmp.outline.hideGeometry

ClientLua Β· JS
luaLua
lsmp.outline.hideGeometry(entity, geomKey) --> boolean
jsJavaScript
lsmp.outline.hideGeometry(entity: number | null, geomKey: number): boolean

Remove this resource's outline from a piece of geometry.

Parameters
ParameterTypeDescription
entityhandle?The entity, or nil/null for the map.
geomKeyuintThe geometry key.
Returnsboolean: true if this resource outlined it.

lsmp.outline.hasGeometry

ClientLua Β· JS
luaLua
lsmp.outline.hasGeometry(entity, geomKey) --> boolean
jsJavaScript
lsmp.outline.hasGeometry(entity: number | null, geomKey: number): boolean

Whether this resource outlines a piece of geometry.

Parameters
ParameterTypeDescription
entityhandle?The entity, or nil/null for the map.
geomKeyuintThe geometry key.
Returnsboolean: true while the outline is drawn.

lsmp.outline.clear

ClientLua Β· JS
luaLua
lsmp.outline.clear() --> integer
jsJavaScript
lsmp.outline.clear(): number

Remove every outline of this resource.

Returns (Lua)integer: How many were removed.
Returns (JavaScript)number: How many were removed.

lsmp.outline.count

ClientLua Β· JS
luaLua
lsmp.outline.count() --> integer
jsJavaScript
lsmp.outline.count(): number

How many outlines this resource draws.

Returns (Lua)integer: The number of outlines.
Returns (JavaScript)number: The number of outlines.

OutlineOptions

FieldTypeDefaultDescription
colorcolor"#ffffff"Any color form. An alpha below 255 makes it translucent.
widthnumber2Thickness in pixels, up to 64.
modestring"outline""outline", "fill" (the whole silhouette) or "dashed".
softnessnumber0Blur of the edge, 0 to 1.
dashPeriodnumberβ€”Length of a dash and its gap, in pixels ("dashed").
dashSpeednumberβ€”How fast the dashes move, in pixels per second ("dashed").
positionvec3β€”showGeometry only: a point of the piece.

Picking

The picker answers "what is drawn at this point of the screen?" from the image itself. No collision is involved: it also finds what a raycast goes through (a fence, leaves, an object without collision), and it gives the exact piece of geometry under the point, not only the entity.

It costs an extra render pass while it runs: turn it on when you need it. Each resource holds it on its own account, and it runs while at least one resource holds it.

lsmp.selection.setEnabled

ClientLua Β· JS
luaLua
lsmp.selection.setEnabled(enabled) --> boolean
jsJavaScript
lsmp.selection.setEnabled(enabled: boolean): boolean

Hold the picker on, or release this resource's hold.

Parameters
ParameterTypeDescription
enabledbooleantrue to hold it, false to release.
Returnsboolean: true if this resource's hold changed.
Failure codeWhen
unavailableThe picker is not available on this client.

lsmp.selection.isEnabled

ClientLua Β· JS
luaLua
lsmp.selection.isEnabled() --> boolean
jsJavaScript
lsmp.selection.isEnabled(): boolean

Whether the picker runs (for any resource).

Returnsboolean: true while it runs.

lsmp.selection.setPoint

ClientLua Β· JS
luaLua
lsmp.selection.setPoint(point)
jsJavaScript
lsmp.selection.setPoint(point: Vec2Like | null): void

Pick at a fixed point of the screen.

Without a point, the picker follows the mouse cursor. { x = 0.5, y = 0.5 } picks at the centre, under a crosshair. Like other owned settings, the last resource to set it wins until it stops.

Parameters
ParameterTypeDescription
pointvec2?{ x, y }, normalized 0..1, or nil/null to follow the cursor again.

lsmp.selection.setPointPixel

ClientLua Β· JS
luaLua
lsmp.selection.setPointPixel(x, y)
jsJavaScript
lsmp.selection.setPointPixel(x: number, y: number): void

Pick at a fixed point of the screen, in pixels.

Parameters
ParameterTypeDescription
xnumberFrom the left edge.
ynumberFrom the top edge.

lsmp.selection.get

ClientLua Β· JS
luaLua
lsmp.selection.get() --> Selection?
jsJavaScript
lsmp.selection.get(): Selection | null

What is under the pick point.

See Selection. Already up to date inside a selectionChange handler.

Returns (Lua)Selection?: The selection, or nil/null while the picker is off.
Returns (JavaScript)Selection | null: The selection, or nil/null while the picker is off.
Example
luaLua
lsmp.selection.setEnabled(true)
lsmp.selection.setPoint({ x = 0.5, y = 0.5 })

lsmp.on("selectionChange", function(entity, geomKey, valid)
  local hit = lsmp.selection.get()
  if not valid or not hit then return end
  if hit.baked then
    lsmp.log(("scenery, %.1f m"):format(hit.distance))
  else
    lsmp.log(("%s, model 0x%x, %.1f m"):format(hit.type, hit.model, hit.distance))
  end
end)
jsJavaScript
lsmp.selection.setEnabled(true);
lsmp.selection.setPoint({ x: 0.5, y: 0.5 });

lsmp.on('selectionChange', (entity, geomKey, valid) => {
  const hit = lsmp.selection.get();
  if (!valid || !hit) return;
  if (hit.baked) lsmp.log(`scenery, ${hit.distance.toFixed(1)} m`);
  else lsmp.log(`${hit.type}, model 0x${hit.model.toString(16)}, ${hit.distance.toFixed(1)} m`);
});

lsmp.selection.setOutline

ClientLua Β· JS
luaLua
lsmp.selection.setOutline(enabled [, opts]) --> boolean
jsJavaScript
lsmp.selection.setOutline(enabled: boolean, opts?: SelectionOutlineOptions): boolean

Keep an outline on whatever is picked, with no per-frame code.

The entity under the point gets one style, the piece of geometry another. Defaults: a light blue outline for the entity, yellow dashes for the geometry.

Parameters
ParameterTypeDescription
enabledbooleantrue to show, false to stop.
opts optSelectionOutlineOptions{ entity, geometry }, each an OutlineOptions.
Returnsboolean: true if the setting was applied.
Failure codeWhen
unavailableThe picker is not available on this client.

lsmp.selection.setToolOpen

ClientLua Β· JS
luaLua
lsmp.selection.setToolOpen(open) --> boolean
jsJavaScript
lsmp.selection.setToolOpen(open: boolean): boolean

Open or close the inspection tool.

The engine's own tool: the camera freezes, the mouse hovers over the world and a panel describes what is under it. It manages the picker by itself.

Parameters
ParameterTypeDescription
openbooleantrue to open, false to close.
Returnsboolean: true if the request was applied.
Failure codeWhen
unavailableThe tool is not available on this client.

lsmp.selection.isToolOpen

ClientLua Β· JS
luaLua
lsmp.selection.isToolOpen() --> boolean
jsJavaScript
lsmp.selection.isToolOpen(): boolean

Whether the inspection tool is open.

Returnsboolean: true while it is open.

selectionChange (entity, geomKey, valid) fires when what is under the pick point changes, not every frame.

Selection

FieldTypeDefaultDescription
serialintβ€”Increases with each new reading.
validbooleanβ€”false when nothing is under the point (sky, nothing drawn).
entityhandle?β€”The entity picked; absent for buildings and terrain.
modelhash?β€”Its model. Read it here: some picked entities have no model information for natives.
typestring?β€”"vehicle", "ped" or "object".
bakedbooleanβ€”true for map geometry (buildings, terrain).
distancemeters?β€”From the camera.
positionvec3?β€”The world position under the point.
pointvec2β€”The pick point, normalized.
geometrytable?β€”The piece of geometry: key (for showGeometry), and its triangle and vertex counts.
Client Β· Lua & JS

Console commands and key input

Commands in the player's F8 console, and reacting to keys and buttons.

Console commands

A client command is typed by the player in the F8 console, with or without a leading /. It runs on that player's machine only: anything that must be checked or shared goes to the server (an event or a remote call). For commands in the server console, see Console commands.

lsmp.registerCommand

ClientLua Β· JS
luaLua
lsmp.registerCommand(name [, opts], fn) --> off
jsJavaScript
lsmp.registerCommand(name: string, opts: CommandOptions | undefined, fn: Function): () => boolean

Add a command to the F8 console.

The handler receives (args, raw): args are the words after the command name, split on spaces (a word that starts with " runs to the next "); raw is the rest of the line as typed. help and params are shown while the player types; they are display only, args are always strings.

Several handlers may share a name: they all run. Names follow the server rules; the built-in client commands (devtools, disconnect...) cannot be registered. A resource's commands are removed when it stops; unregisterCommand removes one before.

Parameters
ParameterTypeDescription
namestringThe command name.
opts optCommandOptions{ help, params }: see CommandOptions (permission and restricted are server only).
fnfnThe handler.
Returns (Lua)function: A function that unregisters this handler and returns true if it was registered.
Returns (JavaScript)() => boolean: A function that unregisters this handler and returns true if it was registered.
Example
luaLua
lsmp.registerCommand("heal", {
  help = "Ask the server to heal you",
}, function(args, raw)
  local ok, err = lsmp.callServer("medic:heal")
  if not ok then lsmp.log("no medic available: " .. tostring(err)) end
end)
jsJavaScript
lsmp.registerCommand('heal', { help: 'Ask the server to heal you' }, async () => {
  try {
    await lsmp.callServer('medic:heal');
  } catch (err) {
    lsmp.log(`no medic available: ${err.code}`);
  }
});

Key input

Keys are read with the game's control natives, every frame, from lsmp.onTick. Controls are game actions (INPUT_...), not physical keys: a player who rebinds a key in the game settings keeps your feature working. isControlJustPressed fires once per press; isControlPressed while held.

luaLua
local INPUT_MULTIPLAYER_INFO = 20   -- Z on a default layout

lsmp.onTick(function()
  if isControlJustPressed(0, INPUT_MULTIPLAYER_INFO) then
    lsmp.emit("scoreboard:toggle")
  end
end)
jsJavaScript
const INPUT_MULTIPLAYER_INFO = 20;   // Z on a default layout

lsmp.onTick(() => {
  if (isControlJustPressed(0, INPUT_MULTIPLAYER_INFO)) lsmp.emit('scoreboard:toggle');
});
  • A focused page takes the keyboard. While a browser has the focus (a chat field, a menu), the control natives report nothing: the same key cannot fire twice for one action.
  • Disable a game action while you use its key: disableControlAction(0, control, true) every frame.
  • Keep the handler short. It runs every frame; heavy work belongs in a timer or an async function.
Client Β· Lua & JS

Browsers (2D and 3D)

Show web pages in game: 2D pages drawn over the game, and 3D pages rendered into a texture placed in the world. Each page talks only to the script that opened it.

2D browser3D browser
Created withlsmp.createBrowserlsmp.createBrowser3D
ShownOver the game, in a rectangle of the screenNowhere by itself: its texture replaces a game texture (lsmp.replaceTexture)
Mouse and keyboardWhen it has the focus (both, or one of the two)None
Addresseshttps://, rsc://<resource>/…; http://localhost outside a serverhttps://, rsc://<its own resource>/…
At most16 per resource, 128 on the client4 per resource, 64 on the client

A browser belongs to the resource that created it: it closes when the resource stops, and only that resource's handlers hear from it. The page itself uses the lsmp object of a page. For a guided start, see Web interfaces and the UI tutorial. A method called on a handle of another resource does nothing and returns false, with the code permission in lsmp.getLastError().

luaclient/main.lua
local hud = lsmp.createBrowser("rsc://shop/index.html", {
  bounds = { x = 0.70, y = 0.10, width = 0.28, height = 0.80 },
})

hud:on("load", function(url)
  hud:emit("init", lsmp.getPlayerName(lsmp.getLocalPlayer()))
end)

-- The page calls lsmp.callServer("buy", itemId); the return value answers it.
hud:on("buy", function(itemId)
  local ok, err = lsmp.callServer("shop:buy", itemId)
  return { ok = ok ~= nil, error = err }
end)
jsclient/main.js
const hud = lsmp.createBrowser('rsc://shop/index.html', {
  bounds: { x: 0.70, y: 0.10, width: 0.28, height: 0.80 },
});

hud.on('load', () => {
  hud.emit('init', lsmp.getPlayerName(lsmp.getLocalPlayer()));
});

// The page calls lsmp.callServer('buy', itemId); the return value answers it.
hud.on('buy', async (itemId) => {
  try {
    return { ok: true, result: await lsmp.callServer('shop:buy', itemId) };
  } catch (err) {
    return { ok: false, error: err.code };
  }
});
jsweb/index.html (page)
lsmp.on('init', (name) => {
  document.querySelector('#hello').textContent = `Hello, ${name}`;
});

async function buy(itemId) {
  const answer = await lsmp.call('buy', itemId);
  if (!answer.ok) document.querySelector('#error').textContent = answer.error;
}

2D browsers

lsmp.createBrowser

ClientLua Β· JS
luaLua
lsmp.createBrowser(url [, opts]) --> Browser?
jsJavaScript
lsmp.createBrowser(url: string, opts?: BrowserOptions): Browser | null

Open a 2D page over the game, owned by the calling resource.

The page starts loading at once; messages you emit before it is ready are kept and delivered when it is (see load). Without bounds the page covers the whole screen, transparent where the page is. Failures return nil/null; read the code with lsmp.getLastError(): limit (16 open 2D browsers for this resource, 128 on the client) or unavailable (the game's web engine is not ready). A refused address or out-of-range option raises a RangeError.

Parameters
ParameterTypeDescription
urlstringhttps://…, rsc://<resource>/… (pages of a resource's webui folders), or http://localhost, http://127.0.0.1, http://[::1] outside a server session only (local development). See URL rules.
opts optBrowserOptionsOptions, below.
Returns (Lua)Browser?: The handle, or nil on failure.
Returns (JavaScript)Browser | null: The handle, or null on failure.
BrowserOptionsTypeDefaultDescription
boundsRectfull screen{ x, y, width, height } as fractions of the screen, 0..1. The rectangle must fit on the screen.
boundsPixelRectThe same in pixels. Do not give both bounds and boundsPixel.
visiblebooleantrueShown at once.
focusbooleanfalseTakes the mouse and keyboard at once. See Focus.
cursorbooleantrueWith focus: false takes the keyboard only, with no cursor (a chat field). Same as the cursor option of browser.setFocus.
keepInputbooleanfalseWith focus: true takes the mouse only, the player keeps playing. Same as the keepInput option of browser.setFocus.
zIndexinteger0Stacking among this server's 2D pages, -1000..1000; higher is on top.

browser.destroy

ClientLua Β· JS
luaLua
browser:destroy()
jsJavaScript
browser.destroy(): void

Close the page.

Pending browser.calls fail with cancelled, and popups the page opened close with it. Afterwards every method of the handle does nothing and returns false (or nil/null). Resources do not need it at stop: their browsers close by themselves.

browser.isValid

ClientLua Β· JS
luaLua
browser:isValid() --> boolean
jsJavaScript
browser.isValid(): boolean

Whether the browser is still open.

Returnsboolean: false once destroyed, by you or when the resource stopped.

browser.id

ClientLua Β· JS
luaLua
browser.id --> integer
jsJavaScript
browser.id: number

Read-only field: the 2D browser id given by the client.

Stable for the life of the handle. It is the number shown by DevTools and in the client log for this browser.

browser.setUrl

ClientLua Β· JS
luaLua
browser:setUrl(url) --> boolean
jsJavaScript
browser.setUrl(url: string): boolean

Load another page, with the same address rules as createBrowser.

Pending calls of the old page fail with cancelled. load fires again when the new page is ready. Also the way to reload a page after a crash.

Parameters
ParameterTypeDescription
urlstringThe new address. A refused address raises a RangeError.
Returnsboolean: false if the browser was destroyed.

browser.setBounds

ClientLua Β· JS
luaLua
browser:setBounds(rect) --> boolean
jsJavaScript
browser.setBounds(rect: Rect): boolean

Move and resize the page, as fractions of the screen.

Parameters
ParameterTypeDescription
rectRect{ x, y, width, height }, 0..1; width and height above 0, and the rectangle inside the screen. Otherwise RangeError.
Returnsboolean: false if the browser was destroyed.

browser.setBoundsPixel

ClientLua Β· JS
luaLua
browser:setBoundsPixel(rect) --> boolean
jsJavaScript
browser.setBoundsPixel(rect: Rect): boolean

Move and resize the page, in pixels.

Pixel bounds do not follow a change of resolution; fractions do. Use lsmp.getGameScreen to read the screen size.

Parameters
ParameterTypeDescription
rectRect{ x, y, width, height } in pixels, non-negative, width and height above 0, at most 16384 to the far edge.
Returnsboolean: false if the browser was destroyed.

browser.setVisible

ClientLua Β· JS
luaLua
browser:setVisible(visible) --> boolean
jsJavaScript
browser.setVisible(visible: boolean): boolean

Show or hide the page.

A hidden page keeps running and keeps its state: hiding is cheaper than destroying and recreating it. A hidden page never takes the mouse.

Parameters
ParameterTypeDescription
visiblebooleantrue to show.
Returnsboolean: false if the browser was destroyed.

browser.isVisible

ClientLua Β· JS
luaLua
browser:isVisible() --> boolean
jsJavaScript
browser.isVisible(): boolean

Whether the page is shown.

Returnsboolean: false when hidden or destroyed.

browser.setFocus

ClientLua Β· JS
luaLua
browser:setFocus(focused [, opts]) --> boolean
jsJavaScript
browser.setFocus(focused: boolean, opts?: FocusOptions): boolean

Give the page the mouse and keyboard, the keyboard alone or the mouse alone, or take them back.

While a page has the focus, the player's input goes to the page instead of the game. By default the page takes the mouse and the keyboard, and the cursor shows: right for a menu or a form. With cursor set to false, it takes the keyboard only: no cursor, no clicks, and the camera stays still while the player types. Use it for a chat field or any text input that needs no mouse. With keepInput set to true, it takes the mouse only: the cursor shows and clicks reach the page, while the player keeps playing with the keyboard and gamepad (walking, driving). The mouse then moves the cursor instead of the camera, and a click does not fire. Use it for a panel that stays usable during play (a radio, a map, a tracker). The keys still go to the game, so a text field in such a page would also move the player: use the default focus for typing. The two options cannot be combined. The player can always take the input back with Ctrl+Alt+Backspace; the page then gets focusLost. Give the focus only while the player needs it, and remove it when they are done.

Parameters
ParameterTypeDescription
focusedbooleantrue to take the input, false to give it back to the game.
opts optFocusOptionsOptions, below.
Returnsboolean: false if the browser was destroyed.
FocusOptionsTypeDefaultDescription
cursorbooleantruetrue: the mouse and the keyboard, with the cursor. false: the keyboard only, with no cursor and no clicks. No effect when focused is false.
keepInputbooleanfalsetrue: the mouse only. The cursor shows and clicks reach the page; the game keeps the keyboard and gamepad, and the mouse no longer turns the camera. A RangeError with cursor set to false.
Example
luaLua
local menu = lsmp.createBrowser("rsc://shop/menu.html", { visible = false })

lsmp.registerCommand("shop", function()
  menu:setVisible(true)
  menu:setFocus(true)
end)

-- The page calls lsmp.emit("close") from its close button.
menu:on("close", function()
  menu:setFocus(false)
  menu:setVisible(false)
end)

-- The player took the input back with Ctrl+Alt+Backspace.
menu:on("focusLost", function()
  menu:setVisible(false)
end)

-- A chat field needs the keyboard only: no cursor while the player types.
local chat = lsmp.createBrowser("rsc://shop/chat.html", {
  bounds = { x = 0.01, y = 0.03, width = 0.32, height = 0.34 },
})

lsmp.registerCommand("say", function()
  chat:setFocus(true, { cursor = false })
  chat:emit("open")
end)

-- The page gives the line back when the player presses Enter.
chat:on("submit", function(text)
  chat:setFocus(false)
end)

-- A radio panel stays usable while the player drives: mouse only.
local radio = lsmp.createBrowser("rsc://shop/radio.html", {
  bounds = { x = 0.75, y = 0.70, width = 0.24, height = 0.28 },
})

lsmp.registerCommand("radio", function()
  radio:setFocus(not radio:hasFocus(), { keepInput = true })
end)
jsJavaScript
const menu = lsmp.createBrowser('rsc://shop/menu.html', { visible: false });

lsmp.registerCommand('shop', () => {
  menu.setVisible(true);
  menu.setFocus(true);
});

// The page calls lsmp.emit('close') from its close button.
menu.on('close', () => {
  menu.setFocus(false);
  menu.setVisible(false);
});

// The player took the input back with Ctrl+Alt+Backspace.
menu.on('focusLost', () => menu.setVisible(false));

// A chat field needs the keyboard only: no cursor while the player types.
const chat = lsmp.createBrowser('rsc://shop/chat.html', {
  bounds: { x: 0.01, y: 0.03, width: 0.32, height: 0.34 },
});

lsmp.registerCommand('say', () => {
  chat.setFocus(true, { cursor: false });
  chat.emit('open');
});

// The page gives the line back when the player presses Enter.
chat.on('submit', (text) => chat.setFocus(false));

// A radio panel stays usable while the player drives: mouse only.
const radio = lsmp.createBrowser('rsc://shop/radio.html', {
  bounds: { x: 0.75, y: 0.70, width: 0.24, height: 0.28 },
});

lsmp.registerCommand('radio', () => {
  radio.setFocus(!radio.hasFocus(), { keepInput: true });
});

browser.hasFocus

ClientLua Β· JS
luaLua
browser:hasFocus() --> boolean
jsJavaScript
browser.hasFocus(): boolean

Whether the page holds the focus (the mouse and keyboard, or the keyboard alone).

Returnsboolean: false after setFocus(false), after the player's Ctrl+Alt+Backspace, or once destroyed.

browser.setZIndex

ClientLua Β· JS
luaLua
browser:setZIndex(z) --> boolean
jsJavaScript
browser.setZIndex(z: number): boolean

Change the stacking order among this server's 2D pages.

LS:MP's own interface (menu, console, payment window) always stays above every server page.

Parameters
ParameterTypeDescription
zinteger-1000..1000; higher is on top.
Returnsboolean: false if the browser was destroyed.

Talking to the page

The same four methods exist on 2D and 3D handles. Values are those a page understands: see Values and limits.

browser.emit

ClientLua Β· JS
luaLua
browser:emit(event, ...) --> boolean
jsJavaScript
browser.emit(event: string, ...args: Value[]): boolean

Send an event to the page's lsmp.on handlers.

Before the page is ready, events wait in a queue (256 messages or 1 MiB at most) and are delivered in order right after load. A value the page cannot represent, a message over the limit, or more than 32 arguments raises. The names load, loadError, focusLost, crash and those starting with lsmp: are reserved.

Parameters
ParameterTypeDescription
eventstringEvent name, 1 to 128 characters.
... optValueUp to 32 values.
Returnsboolean: false if the browser was destroyed or the queue is full (code limit).

browser.on

ClientLua Β· JS
luaLua
browser:on(event, fn) --> function
jsJavaScript
browser.on(event: string, fn: Function): () => boolean

Handle an event or a call from this browser's page, or one of its lifecycle events.

The handler receives the page's arguments. For a page lsmp.emit, every handler of the name runs. For a page lsmp.call, handlers run in order until one returns a value: that value is the answer (a JS handler may return a Promise; a Lua handler may wait, it runs in a coroutine). If all return nil/undefined the answer is nil/null; a handler that raises answers with the code error, and the error is logged in the client console. With no handler, the page gets no-handler at once.

The same function registered twice for one name counts once. Lifecycle events are in the table below.

Parameters
ParameterTypeDescription
eventstringEvent name, or "load", "loadError", "focusLost", "crash".
fnfunctionfn(...args); its return value answers a page call.
Returns (Lua)function: Call it to remove the handler; it returns true if it was registered.
Returns (JavaScript)() => boolean: Call it to remove the handler; it returns true if it was registered.

browser.off

ClientLua Β· JS
luaLua
browser:off(event, fn) --> boolean
jsJavaScript
browser.off(event: string, fn: Function): boolean

Remove a handler registered with on.

Parameters
ParameterTypeDescription
eventstringThe event name.
fnfunctionThe same function that was registered.
Returnsboolean: true if it was registered.

browser.call

ClientLua Β· JS
luaLua
browser:call(event, ... [, cb]) --> any, err
jsJavaScript
browser.call(event: string | CallOptions, ...args: Value[]): Promise<Value>

Call the page's lsmp.on handler and get its answer.

The call waits for the page if it is still loading. Asynchronous: in Lua with a callback or inside a coroutine, see Conventions. Failure codes (Error codes):

Parameters
ParameterTypeDescription
eventstring | CallOptionsThe handler's name, or { name, timeoutMs }: timeoutMs from 1 to 300000, default 10000.
... optValueUp to 32 values.
Returns (Lua)any, err: The page's answer, or nil and a code.
Returns (JavaScript)Promise<Value>: Resolves with the page's answer; rejects with an error whose code is one of the codes below.
CodeMeaning
timeoutNo answer in time.
no-handlerThe page has no lsmp.on handler for this name.
errorThe page's handler threw, or its answer could not be sent. Details in the page's console (DevTools).
cancelledThe browser was destroyed, or the page navigated away, before answering.
limit1024 calls are already waiting on this browser.
unavailableThe game's web engine is not running.
Example
luaLua
local form = lsmp.createBrowser("rsc://garage/form.html")

form:call({ name = "getColor", timeoutMs = 5000 }, function(color, err)
  if err then
    lsmp.warn("no color: " .. err)
  else
    lsmp.log("chosen color: " .. color)
  end
end)
jsJavaScript
const form = lsmp.createBrowser('rsc://garage/form.html');

form.call({ name: 'getColor', timeoutMs: 5000 })
  .then((color) => lsmp.log(`chosen color: ${color}`))
  .catch((err) => lsmp.warn(`no color: ${err.code}`));

Lifecycle events

Register them with browser:on, like page events. They come from LS:MP, never from the page, and only reach that handle's handlers. See also Engine events.

EventArgumentsWhen
loadurlThe page's document is ready (its DOMContentLoaded). Queued emits are delivered right after. Fires again after each navigation.
loadErrorurl, codeThe page could not load. code: "refused-url" (address not allowed), "network", "http-<status>" (such as "http-404"), "aborted".
focusLost2D only. The player took the input back (Ctrl+Alt+Backspace), or another page took the focus. hasFocus() is now false.
crashreasonThe page's process crashed. The handle stays valid. A 2D page is reloaded by LS:MP right away and load fires again (after repeated crashes it stays down until setUrl). For a 3D page, setUrl loads a page again.

3D browsers

A 3D browser renders a page off-screen into a texture. Show it in the world by putting that texture in place of a game texture with lsmp.replaceTexture: a screen in a bar, a billboard, a phone. A 3D page has no mouse or keyboard; drive it with emit and call.

lsmp.createBrowser3D

ClientLua Β· JS
luaLua
lsmp.createBrowser3D(url [, opts]) --> Browser3D?
jsJavaScript
lsmp.createBrowser3D(url: string, opts?: Browser3DOptions): Browser3D | null

Open an off-screen page that renders into a texture.

Failures return nil/null, with the code from lsmp.getLastError(): limit (4 open 3D browsers for this resource, 64 on the client) or unavailable. A refused address or an out-of-range option raises a RangeError.

Parameters
ParameterTypeDescription
urlstringhttps://…, or rsc://<this resource>/…: a 3D page cannot show another resource's pages.
opts optBrowser3DOptionswidth and height of the page and its texture in pixels, 1..4096, default 1024; fps, frames rendered per second, 1..60, default 30.
Returns (Lua)Browser3D?: The handle, or nil on failure.
Returns (JavaScript)Browser3D | null: The handle, or null on failure.
Example
luaLua
-- Show a web page on an existing world texture.
local screen = lsmp.createBrowser3D("rsc://cinema/screen.html", { width = 1280, height = 720, fps = 30 })
if not screen then return end

screen:on("load", function()
  local texture = screen:getTexture()
  if not texture then return end

  local bind = lsmp.replaceTexture(texture, {
    type = "txd", container = "cs4_02_build_1", name = "cs4_02_rsl_mr_bb",
  })
  if not bind then
    lsmp.warn("texture not bound: " .. tostring(lsmp.getLastError()))
    return
  end
  screen:emit("play", "intro")
end)
jsJavaScript
// Show a web page on an existing world texture.
const screen = lsmp.createBrowser3D('rsc://cinema/screen.html', { width: 1280, height: 720, fps: 30 });

screen?.on('load', () => {
  const texture = screen.getTexture();
  if (texture === null) return;

  const bind = lsmp.replaceTexture(texture, {
    type: 'txd', container: 'cs4_02_build_1', name: 'cs4_02_rsl_mr_bb',
  });
  if (bind === null) {
    lsmp.warn(`texture not bound: ${lsmp.getLastError()}`);
    return;
  }
  screen.emit('play', 'intro');
});

browser3d.destroy

ClientLua Β· JS
luaLua
browser3d:destroy()
jsJavaScript
browser3d.destroy(): void

Close the page; game textures it replaced are restored.

Pending calls fail with cancelled. Resources do not need it at stop: their browsers close by themselves.

browser3d.isValid

ClientLua Β· JS
luaLua
browser3d:isValid() --> boolean
jsJavaScript
browser3d.isValid(): boolean

Whether the 3D browser is still open.

Returnsboolean: false once destroyed.

browser3d.id

ClientLua Β· JS
luaLua
browser3d.id --> integer
jsJavaScript
browser3d.id: number

Read-only field: the 3D browser id given by the client.

Stable for the life of the handle. It is the number shown by DevTools and in the client log for this browser.

browser3d.setUrl

ClientLua Β· JS
luaLua
browser3d:setUrl(url) --> boolean
jsJavaScript
browser3d.setUrl(url: string): boolean

Load another page, with the same address rules as createBrowser3D.

Parameters
ParameterTypeDescription
urlstringThe new address. A refused address raises a RangeError.
Returnsboolean: false if the browser was destroyed.

browser3d.setSize

ClientLua Β· JS
luaLua
browser3d:setSize(width, height) --> boolean
jsJavaScript
browser3d.setSize(width: number, height: number): boolean

Resize the page and its texture.

The texture handle stays the same; bindings made with replaceTexture follow.

Parameters
ParameterTypeDescription
widthinteger1..4096 pixels.
heightinteger1..4096 pixels.
Returnsboolean: false if the browser was destroyed.

browser3d.getTexture

ClientLua Β· JS
luaLua
browser3d:getTexture() --> integer
jsJavaScript
browser3d.getTexture(): number

The texture the page renders into, for lsmp.replaceTexture.

The handle is stable for the browser's whole life. nil/null with the code unavailable if the texture does not exist yet, not-found once destroyed.

Returnsinteger: Texture handle.

browser3d.emit

ClientLua Β· JS
luaLua
browser3d:emit(event, ...) --> boolean
jsJavaScript
browser3d.emit(event: string, ...args: Value[]): boolean

Send an event to the page, as browser.emit.

Parameters
ParameterTypeDescription
eventstringEvent name.
... optValueUp to 32 values.
Returnsboolean: false if the browser was destroyed or the queue is full.

browser3d.on

ClientLua Β· JS
luaLua
browser3d:on(event, fn) --> function
jsJavaScript
browser3d.on(event: string, fn: Function): () => boolean

Handle an event, a call or a lifecycle event of the page, as browser.on.

Lifecycle events: load, loadError, crash (no focusLost: a 3D page has no focus).

Parameters
ParameterTypeDescription
eventstringEvent name or lifecycle event.
fnfunctionfn(...args); its return value answers a page call.
Returns (Lua)function: Call it to remove the handler.
Returns (JavaScript)() => boolean: Call it to remove the handler.

browser3d.off

ClientLua Β· JS
luaLua
browser3d:off(event, fn) --> boolean
jsJavaScript
browser3d.off(event: string, fn: Function): boolean

Remove a handler, as browser.off.

Parameters
ParameterTypeDescription
eventstringThe event name.
fnfunctionThe same function that was registered.
Returnsboolean: true if it was registered.

browser3d.call

ClientLua Β· JS
luaLua
browser3d:call(event, ... [, cb]) --> any, err
jsJavaScript
browser3d.call(event: string | CallOptions, ...args: Value[]): Promise<Value>

Call the page's handler and get its answer, as browser.call, with the same codes.

Parameters
ParameterTypeDescription
eventstring | CallOptionsThe handler's name, or { name, timeoutMs }.
... optValueUp to 32 values.
Returns (Lua)any, err: The answer, or nil and a code.
Returns (JavaScript)Promise<Value>: Resolves with the answer; rejects with a coded error.

Values and limits

Script valueIn the page
nil / nullnull (a missing argument too)
boolean, stringthe same
numbernumber. Integers beyond 2^53, NaN and infinities raise a TypeError.
table with keys / objectobject
sequence / arrayarray
vector{ x, y, z }; an { x, y, z } object from the page becomes a Vector3 in Lua
bytes (lsmp.bytes, Uint8Array)Uint8Array, and back
  • One message holds at most 32 arguments and 120,000 characters once written as JSON; more raises a RangeError, on both sides.
  • Event names: 1 to 128 characters, no control characters. Names starting with lsmp:, and load, loadError, focusLost, crash, are reserved.
  • At most 1024 calls wait on one browser in each direction; the next fails with limit. At most 1024 handlers on one browser.
  • In one frame, a page delivers at most 256 messages and 524 288 characters of JSON to its script; beyond, an emit is dropped and a call fails with limit. A page event no script handler listens to is dropped (a call fails with no-handler).

URL rules

  • rsc://<resource>/… serves the files of a resource's webui folders. A 3D browser may only open its own resource's pages.
  • https:// opens any public web page. The page still gets the lsmp object, linked to your script: only open sites you trust.
  • http:// is refused, except http://localhost, http://127.0.0.1 and http://[::1] in a 2D browser outside a server session: handy with a dev server (Vite, webpack) in Story mode with local resources.
  • Server pages cannot reach the player's local network or machine. LS:MP's own pages cannot be opened.

Focus and input

  • A 2D page without the focus is click-through: the mouse and keyboard go to the game. Only focused, visible pages take the mouse, each in its own rectangle.
  • The cursor shows only while something needs it: a page that holds the mouse, LS:MP's menu or console, a loading screen. In game it stays hidden.
  • Keyboard only: a page focused with cursor set to false takes the keyboard and nothing else. No cursor, no clicks, and the game gets no input until you remove the focus: what a chat field wants.
  • Mouse only, the player keeps playing: a page focused with keepInput set to true keeps the cursor on screen while the player walks or drives with the keyboard and gamepad. The mouse moves the cursor instead of the camera, clicks go to the page, and the cursor stays inside the game window.
  • What a page takes, the game no longer sees: while a page holds the keyboard, no script reads the keys the player types, not even with isDisabledControlPressed or the frontend controls; the same goes for the mouse. Close your page from its own keys (Escape in the page), not from a control read by your script. The key that closes a page (Escape, Enter) does not reach the game either.
  • Ctrl+Alt+Backspace always gives the input back to the player, from every page of the server. Your pages get focusLost and stay open; setFocus(true) gives them the input again.
  • LS:MP's own interface always comes first: its menu (F1) and console (F8) open over your pages.

Storage, microphone, camera and limits

A page runs with its real origin, 2D and 3D alike: rsc://<resource> for the files of a resource, or the https:// site. That gives it the usual web platform:

  • Storage: localStorage, sessionStorage and IndexedDB work, and what a page stores is kept on the player's disk: it is there again at the next connection, after a restart of the game too.
  • One store per server: the store belongs to the server the player joined (its address). A page never reads what a page of another server wrote, even at the same origin or with the same resource name. Story Mode has one store for all mods, separated by origin; a Marketplace trial keeps nothing once it ends.
  • Microphone and camera: navigator.mediaDevices.getUserMedia shows an LS:MP prompt that names your server, the resource and the page's origin. The player allows or blocks, for the session or for good (remembered for this server and this origin). LS:MP shows an indicator while a page records, and recording stops when the browser is destroyed. Screen capture is always refused.
  • Web Workers and BroadcastChannel work as on the web.
  • fetch and ES modules work for the files of the page's own resource (rsc://), and for https:// servers that allow it (CORS).

What to keep in mind:

  • A 2D page and a 3D page do not share storage, even at the same origin: 2D pages are frames of the LS:MP interface, and the browser keeps the storage of frames apart. Pass the value through your script if both need it.
  • rsc:// pages have no cookies and the Cache API does not store rsc:// files: use localStorage or IndexedDB. An https:// 2D page is an embedded frame: its cookies need SameSite=None; Secure.
  • Storage is a convenience, not a database. LS:MP clears the store of a server the player has not visited for 180 days, the least recently visited ones beyond 64 servers or 4 GB, and a store that grows over 1 GB. Keep what matters on your server.
  • 2D pages of the same origin can reach each other (parent.frames), like two tabs of one site. Pages of different origins, and the LS:MP interface around them, cannot be read or navigated.
  • No dialogs in 2D pages: alert, confirm and prompt do nothing. Draw your own. No pointer lock, no downloads.

Popups

window.open and target="_blank" links open an LS:MP popup window over the game, with the site's address in its title bar and a close button: useful for a sign-in page that refuses to load in a frame.

  • https:// only, and only right after a click or a key press of the player.
  • 3 popups at most; a popup cannot open another one. The size is fixed (520 Γ— 640).
  • Popups close with the browser that opened them, and when the player leaves the server.
Client Β· Lua & JS

Render scenes

Render peds, vehicles and objects in a private studio, away from the map and from the player's screen: portraits, vehicle thumbnails, item icons, on a transparent background. Shoot still images, or render the scene live on screen or onto a game texture.

A scene is a small world of its own: no map, no sky, no weather, no time of day. It holds the entities you add, a camera and lights. It renders with the game's own renderer, into images of its own: the player's screen is never read or touched.

The entities stay where they are in the world. The scene only draws them, at the place you give them in its own space, with their current look: clothes, pose, damage, paint and mods. An invisible or far away entity renders just as well, so a common pattern is to spawn a hidden entity, shoot it, then delete it.

  1. Create

    Create the scene with lsmp.createScene, at the size of the image you want.

  2. Add entities

    Add peds, vehicles or objects with scene.addEntity, each with its own position and rotation.

  3. Frame and light

    Place the camera with scene.setCamera, and light the scene with a preset, the ambient light, a key light or your own lights. Every setting has a default that frames a ped standing at the origin.

  4. Shoot or render live

    Call scene.shot for an image, or scene.enableRender to render continuously into a texture.

  5. Destroy

    Destroy the scene when you are done. The scenes of a resource are destroyed when it stops.

luaLua
-- A thumbnail of the player's vehicle, on a transparent background.
local scene, err = lsmp.createScene({ width = 512, height = 288, supersample = 2 })
if not scene then return lsmp.warn("no scene: " .. err) end

scene:setLightPreset("studio")
scene:addEntity(getVehiclePedIsIn(playerPedId(), false), { rotation = { 0, 0, -35 } })
scene:setCamera({ position = { 0, 6.5, 1.6 }, lookAt = { 0, 0, 0.2 }, fov = 40 })

local shot, shotErr = scene:shot({ format = "webp", dataUrl = true })
scene:destroy()
if shot then
  lsmp.emit("garage:thumbnail", shot.dataUrl)
else
  lsmp.warn("shot failed: " .. shotErr)
end
jsJavaScript
// A thumbnail of the player's vehicle, on a transparent background.
async function thumbnail() {
  const scene = lsmp.createScene({ width: 512, height: 288, supersample: 2 });
  if (!scene) return lsmp.warn(`no scene: ${lsmp.getLastError()}`);

  scene.setLightPreset('studio');
  scene.addEntity(getVehiclePedIsIn(playerPedId(), false), { rotation: { x: 0, y: 0, z: -35 } });
  scene.setCamera({ position: { x: 0, y: 6.5, z: 1.6 }, lookAt: { x: 0, y: 0, z: 0.2 }, fov: 40 });

  try {
    const shot = await scene.shot({ format: 'webp', dataUrl: true });
    lsmp.emit('garage:thumbnail', shot.dataUrl);
  } catch (err) {
    lsmp.warn(`shot failed: ${err.code}`);
  } finally {
    scene.destroy();
  }
}
β„Ή
Scenes or camera capture?

Camera capture photographs the world through a scripted camera: the map, the weather, the other players. A scene shows only what you put in it, lit the way you choose, and costs the player nothing on screen.

Creating a scene

lsmp.createScene

ClientLua Β· JS
luaLua
lsmp.createScene([opts]) --> Scene?
jsJavaScript
lsmp.createScene(opts?: SceneOptions): Scene | null

Create a render scene owned by this resource.

The scene starts with the "headshot" light preset, a white ambient light and a camera framed on a ped standing at the origin. Every setting can change afterwards. The handle has a read-only id.

Failure codes: limit (too many scenes, or too many pixels in total), unavailable (the game has not rendered its first frame yet, or this game build has no scenes), error (no graphics memory). See Error codes.

Parameters
ParameterTypeDescription
opts optSceneOptionsSee scene options.
Returns (Lua)Scene?: The scene, or nil and a code.
Returns (JavaScript)Scene | null: The scene, or null with the code in lsmp.getLastError().

scene.configure

ClientLua Β· JS
luaLua
scene:configure(opts) --> boolean
jsJavaScript
scene.configure(opts: SceneOptions): boolean

Change the size, the supersampling or the background.

Options you leave out keep their value. When a new size is refused, the scene keeps its previous size and stays usable. On a scene that renders live, the texture keeps its handle: replacements and the overlay follow.

Parameters
ParameterTypeDescription
optsSceneOptionsThe options to change.
Returnsboolean: true when applied; false otherwise, with the code in lsmp.getLastError(): limit, unavailable, error.

Scene options

OptionTypeDefaultMeaning
width, heightint512Size of the images in pixels, 16 to 4096.
supersampleint11 to 4. The scene renders at width Γ— supersample by height Γ— supersample, then scales down: smoother edges, finer hair. 2 is a good balance; 3 or 4 for small icons.
backgroundcolor | booleanfalsefalse: transparent. true: opaque black. A color, with alpha if you want a semi-transparent background. JPEG has no transparency.

Scene space

Positions are in meters, Z points up, and +Y is the front of the game's entities: a ped faces +Y, a car's nose points to +Y. Rotations are { x, y, z } in degrees, as in the game's rotation natives (z is the yaw): a yaw of 180 turns an entity to face -Y. Vectors and colors follow the Conventions.

An entity is placed by its origin, the point the game uses for its position: about 1 m above the feet for a ped, around the middle of the body for a vehicle or an object. The default camera stands at { 0, 3, -0.1 } and looks at { 0, 0, -0.1 }, with a vertical field of view of 40Β°: a whole ped at the origin, seen from the front.

Entities

scene.addEntity

ClientLua Β· JS
luaLua
scene:addEntity(entity [, opts]) --> integer?
jsJavaScript
scene.addEntity(entity: number, opts?: SceneTransform): number | null

Draw a ped, a vehicle or an object in the scene.

The entity must exist on this client: one your script created, the local player, any handle the natives give you. It is drawn with its current state, so change its clothes, paint or pose with the usual natives before a shot. The same entity can be in several scenes; a scene holds up to 32 entities.

Returns nil / null with the code not-found when the handle is unknown, is not a ped, vehicle or object, or the scene is full.

Parameters
ParameterTypeDescription
entityhandleA ped, vehicle or object handle.
opts optSceneTransform{ position, rotation } in scene space, both default { 0, 0, 0 }.
Returnsinteger?: An id for this entity in this scene (not the entity handle).
Example
luaLua
-- A ped next to its car, both turned towards the camera.
scene:addEntity(car, { position = { 0.6, 0, 0 }, rotation = { 0, 0, -30 } })
scene:addEntity(ped, { position = { -1.9, 0.6, 0.05 }, rotation = { 0, 0, 20 } })
jsJavaScript
// A ped next to its car, both turned towards the camera.
scene.addEntity(car, { position: { x: 0.6, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: -30 } });
scene.addEntity(ped, { position: { x: -1.9, y: 0.6, z: 0.05 }, rotation: { x: 0, y: 0, z: 20 } });

scene.setEntityTransform

ClientLua Β· JS
luaLua
scene:setEntityTransform(id, opts) --> boolean
jsJavaScript
scene.setEntityTransform(id: number, opts: SceneTransform): boolean

Move or turn an entity of the scene.

Only the fields you give change. Takes the id returned by addEntity. Handy for turntables: turn, shoot, turn again.

Parameters
ParameterTypeDescription
idintThe id from addEntity.
optsSceneTransform{ position, rotation }.
Returnsboolean: true when applied; false otherwise, with the code in lsmp.getLastError(): not-found.

scene.removeEntity

ClientLua Β· JS
luaLua
scene:removeEntity(id) --> boolean
jsJavaScript
scene.removeEntity(id: number): boolean

Take an entity out of the scene. The entity itself is left as it is.

Parameters
ParameterTypeDescription
idintThe id from addEntity.
Returnsboolean: true if it was in the scene.

scene.clearEntities

ClientLua Β· JS
luaLua
scene:clearEntities() --> integer
jsJavaScript
scene.clearEntities(): number

Take every entity out of the scene.

Returnsinteger: How many were removed.
β„Ή
Level of detail

A shot waits a few frames at most until the entities are ready: an outfit streamed, a vehicle's high-detail model loaded. An entity deleted after it was added is skipped, and counted in missing in the shot result.

Camera

scene.setCamera

ClientLua Β· JS
luaLua
scene:setCamera(opts) --> boolean
jsJavaScript
scene.setCamera(opts: SceneCamera): boolean

Place the camera of the scene.

Only the fields you give change. Give lookAt to aim at a point, or rotation to set the angles yourself, not both in the same call. Returns false with the code invalid when the camera would look at its own position.

Parameters
ParameterTypeDescription
optsSceneCameraSee the table below.
Returnsboolean: true when applied; false otherwise, with the code in lsmp.getLastError(): invalid.
Example
luaLua
-- A head-and-shoulders portrait of a ped standing at the origin.
scene:configure({ width = 256, height = 256 })
scene:setCamera({ position = { 0, 1.0, 0.62 }, lookAt = { 0, 0, 0.6 }, fov = 30 })
jsJavaScript
// A head-and-shoulders portrait of a ped standing at the origin.
scene.configure({ width: 256, height: 256 });
scene.setCamera({ position: { x: 0, y: 1.0, z: 0.62 }, lookAt: { x: 0, y: 0, z: 0.6 }, fov: 30 });
OptionTypeDefaultMeaning
positionvec3{ 0, 3, -0.1 }Where the camera stands.
lookAtvec3{ 0, 0, -0.1 }The point it looks at.
rotationrotationAngles in degrees, instead of lookAt.
fovdegrees40Vertical field of view, 1 to 170.
near, farmeters0.05, 500Clipping distances. near above 0, far above near.
orthobooleanfalseOrthographic projection: no perspective, for icons and blueprints.
orthoHeightmeters2With ortho, the height of the visible area.

Lighting

Light in a scene adds up from four sources: a preset of lights, the ambient light, an optional key light, and your own lights. The exposure scales them all. Nothing else lights the scene: no sun, no street lights, no time of day.

scene.setLightPreset

ClientLua Β· JS
luaLua
scene:setLightPreset(preset) --> boolean
jsJavaScript
scene.setLightPreset(preset: string): boolean

Replace the lights of the scene with a ready-made set.

Replaces every light added with addLight. The ambient and key lights stay as they are.

Parameters
ParameterTypeDescription
presetstring"headshot" (the default: the lights of the game's character portraits, for a ped seen from the front), "studio" (key, fill and rim lights for a subject of about two meters, for vehicles and objects) or "none".
Returnsboolean: true when applied; false otherwise, with the code in lsmp.getLastError().

scene.setAmbient

ClientLua Β· JS
luaLua
scene:setAmbient(opts) --> boolean
jsJavaScript
scene.setAmbient(opts: SceneAmbient): boolean

Set the light that comes from everywhere.

Only the fields you give change. Use intensity = 0 for a pitch black scene lit only by your lights.

Parameters
ParameterTypeDescription
optsSceneAmbientcolor (the same from every direction, default white), topColor (the light from above, default white), intensity (0 to 64, default 1).
Returnsboolean: true when applied; false otherwise, with the code in lsmp.getLastError().

scene.setKeyLight

ClientLua Β· JS
luaLua
scene:setKeyLight(opts) --> boolean
jsJavaScript
scene.setKeyLight(opts: SceneLight | null): boolean

Turn on the scene's sun, or turn it off.

A light that comes from far away in one direction, like the sun: every entity gets it from the same side. Off by default. nil, null or false turns it off.

Parameters
ParameterTypeDescription
optstable?direction (the direction the light travels, default { 0.4, -0.6, -0.7 }: from the front right of the default camera, from above), color (default white), intensity (0 to 256, default 8, about daylight).
Returnsboolean: true when applied; false otherwise, with the code in lsmp.getLastError().
Example
luaLua
scene:setKeyLight({ direction = { 0.5, -0.5, -0.7 }, color = "#fff4e0", intensity = 8 })
jsJavaScript
scene.setKeyLight({ direction: { x: 0.5, y: -0.5, z: -0.7 }, color: '#fff4e0', intensity: 8 });

scene.setExposure

ClientLua Β· JS
luaLua
scene:setExposure(ev) --> boolean
jsJavaScript
scene.setExposure(ev: number): boolean

Brighten or darken the whole image.

Every light, ambient included, is multiplied by 2^ev: 1 doubles the light, -1 halves it. Default 0.

Parameters
ParameterTypeDescription
evnumber-16 to 16.
Returnsboolean: true when applied; false otherwise, with the code in lsmp.getLastError().

scene.addLight

ClientLua Β· JS
luaLua
scene:addLight([opts]) --> integer?
jsJavaScript
scene.addLight(opts?: SceneLight): number | null

Add a point, spot or capsule light.

Lights live in the scene's space, like the entities. A scene holds up to 32 lights; only the first 8 also light glass and other transparent surfaces. Returns nil / null with the code limit when the scene is full.

Parameters
ParameterTypeDescription
opts optSceneLightSee the table below.
Returnsinteger?: The id of the light.
Example
luaLua
-- A warm spot above the car, a cold light behind the ped.
scene:setLightPreset("none")
scene:addLight({ type = "spot", position = { 0.6, 2.5, 3.5 }, direction = { 0, -0.55, -0.83 },
  color = "#ff8030", intensity = 30, range = 15, innerAngle = 12, outerAngle = 28 })
scene:addLight({ position = { -2, -1.5, 1.5 }, color = "#80b0ff", intensity = 10 })
jsJavaScript
// A warm spot above the car, a cold light behind the ped.
scene.setLightPreset('none');
scene.addLight({ type: 'spot', position: { x: 0.6, y: 2.5, z: 3.5 }, direction: { x: 0, y: -0.55, z: -0.83 },
  color: '#ff8030', intensity: 30, range: 15, innerAngle: 12, outerAngle: 28 });
scene.addLight({ position: { x: -2, y: -1.5, z: 1.5 }, color: '#80b0ff', intensity: 10 });
OptionTypeDefaultMeaning
typestring"point""point", "spot" or "capsule" (a light along a segment, like a neon tube).
positionvec3{ 0, 2.5, 1.5 }In front of the subject, above it.
directionvec3towards the originSpot: where it points. Capsule: the axis of the tube.
colorcolorwhite
intensitynumber40 to 1024.
rangemeters10Reach, 0.01 to 1000: nothing is lit beyond it.
falloffnumber8How the light fades towards range, 0.01 to 64: high values keep it strong, then fade it quickly near the edge.
innerAngle, outerAngledegrees20, 35Spot: half-angles of the cone, 0 to 89.9. Full light inside innerAngle, none beyond outerAngle.
lengthmeters1Capsule: length of the tube, 0 to 1000.

scene.updateLight

ClientLua Β· JS
luaLua
scene:updateLight(id, opts) --> boolean
jsJavaScript
scene.updateLight(id: number, opts: SceneLight): boolean

Change a light added with addLight. Only the fields you give change.

Parameters
ParameterTypeDescription
idintThe id from addLight.
optsSceneLightThe fields to change.
Returnsboolean: true when applied; false otherwise, with the code in lsmp.getLastError(): not-found.

scene.removeLight

ClientLua Β· JS
luaLua
scene:removeLight(id) --> boolean
jsJavaScript
scene.removeLight(id: number): boolean

Remove a light added with addLight.

Parameters
ParameterTypeDescription
idintThe id from addLight.
Returnsboolean: true if the light existed.

scene.clearLights

ClientLua Β· JS
luaLua
scene:clearLights() --> integer
jsJavaScript
scene.clearLights(): number

Remove every light, those of the preset included. The ambient and key lights stay.

Returnsinteger: How many lights added with addLight were removed.

Shots

scene.shot

ClientLua Β· JS
luaLua
scene:shot([opts] [, cb]) --> ShotResult, err
jsJavaScript
scene.shot(opts?: ShotOptions): Promise<ShotResult>

Render the scene to an image.

A shot renders the scene as it is when the frame is drawn, usually the frame of the request: to shoot several variations (angles, colors, outfits), wait for each result before changing the scene. It usually takes one or two frames. A scene keeps up to 4 shots in flight. Without width and height the image has the size of the scene (configure). Asynchronous: see Conventions; the Promise carries promise.jobId.

Failure codes: limit (too many shots in flight), unavailable (the game is not ready to render), cancelled (the scene was destroyed first), error (rendering or encoding failed). See Error codes.

Parameters
ParameterTypeDescription
opts optShotOptionswidth and height (16 to 4096, default the size of the scene), format ("png", "jpeg" or "webp", default "webp"), quality (JPEG and WebP, 0 to 100, default 90; WebP at 100 is lossless), dataUrl (also return a data: URL, default false), settleFrames (frames rendered before the image, 0 to 30, default 2).
Returns (Lua)ShotResult, err: The result below, or nil and a code.
Returns (JavaScript)Promise<ShotResult>: Resolves with the result below; rejects with a code.
FieldTypeMeaning
width, heightintSize of the image.
formatstringThe format of data.
databytesThe encoded image: a string in Lua, a Uint8Array in JavaScript.
dataUrlstring?The data URL when asked for; nil / null otherwise.
entitiesintEntities drawn in the image.
missingintEntities of the scene that no longer exist, skipped.
framesintFrames the shot waited before it was rendered.
msmsTime from the request to the image.
Example
luaLua
-- A turntable: eight angles of the same car, one after the other.
local id = scene:addEntity(car)
local frames = {}
for i = 0, 7 do
  scene:setEntityTransform(id, { rotation = { 0, 0, i * 45 } })
  local res = scene:shot({ format = "jpeg", quality = 90 })
  if res then frames[#frames + 1] = res.data end
end
jsJavaScript
// A turntable: eight angles of the same car, one after the other.
async function turntable(scene, car) {
  const id = scene.addEntity(car);
  const frames = [];
  for (let i = 0; i < 8; i++) {
    scene.setEntityTransform(id, { rotation: { x: 0, y: 0, z: i * 45 } });
    const res = await scene.shot({ format: 'jpeg', quality: 90 });
    frames.push(res.data);
  }
  return frames;
}

Live rendering

A scene can also render continuously, into a texture that stays on the graphics card: nothing is read back or encoded. Use it for a car turning in a dealership menu, a character preview next to a clothing shop, a security camera on a TV. Two ways to show the image, together or not:

  • On the screen: setOverlay draws it in a rectangle, above the game's HUD and below LS:MP pages.
  • As a game texture: getTexture returns a texture for lsmp.replaceTexture. The image then shows wherever the game draws the texture it replaces: a surface of the world, or a sprite.

Every change to the scene shows in the next live frame, and the entities keep the animation they have in the world. The image has premultiplied alpha: a transparent background stays transparent.

luaLua
-- A live preview of the player's car, turning, bottom right of the screen.
local scene = lsmp.createScene({ width = 512, height = 288 })
scene:setLightPreset("studio")
local car = scene:addEntity(getVehiclePedIsIn(playerPedId(), false))
scene:setCamera({ position = { 0, 6.5, 1.6 }, lookAt = { 0, 0, 0.2 }, fov = 40 })

scene:enableRender(true, { fps = 30 })
scene:setOverlay({ bounds = { x = 0.73, y = 0.72, width = 0.25, height = 0.25 } })

lsmp.onTick(function()
  if scene:isValid() then
    scene:setEntityTransform(car, { rotation = { 0, 0, (lsmp.getTickCount() / 20) % 360 } })
  end
end)
jsJavaScript
// A live preview of the player's car, turning, bottom right of the screen.
const scene = lsmp.createScene({ width: 512, height: 288 });
scene.setLightPreset('studio');
const car = scene.addEntity(getVehiclePedIsIn(playerPedId(), false));
scene.setCamera({ position: { x: 0, y: 6.5, z: 1.6 }, lookAt: { x: 0, y: 0, z: 0.2 }, fov: 40 });

scene.enableRender(true, { fps: 30 });
scene.setOverlay({ bounds: { x: 0.73, y: 0.72, width: 0.25, height: 0.25 } });

lsmp.onTick(() => {
  if (scene.isValid()) {
    scene.setEntityTransform(car, { rotation: { x: 0, y: 0, z: (lsmp.getTickCount() / 20) % 360 } });
  }
});

scene.enableRender

ClientLua Β· JS
luaLua
scene:enableRender(enabled [, opts]) --> boolean
jsJavaScript
scene.enableRender(enabled: boolean, opts?: RenderOptions): boolean

Start or stop rendering the scene live.

The first call creates the scene's texture; calling it again changes the rate. enableRender(false) stops rendering but keeps the last image: the texture and the overlay still show it.

Parameters
ParameterTypeDescription
enabledbooleantrue to render, false to stop.
opts optRenderOptionsfps: frames per second, 1 to 60, default 30.
Returnsboolean: true when applied; false otherwise, with the code in lsmp.getLastError(): limit (8 scenes already render live), unavailable, error.

scene.invalidate

ClientLua Β· JS
luaLua
scene:invalidate() --> boolean
jsJavaScript
scene.invalidate(): boolean

Ask for one more live frame as soon as possible.

Useful with a low fps when you just changed something and want it on screen at once. Several calls in the same frame render once.

Returnsboolean: false if the scene does not render live.

scene.getTexture

ClientLua Β· JS
luaLua
scene:getTexture() --> integer?
jsJavaScript
scene.getTexture(): number | null

The texture the scene renders into, for lsmp.replaceTexture.

Available after the first enableRender; it then stays the same for the life of the scene, even when configure changes its size. The scene owns it: destroying the scene restores every replacement and frees it.

Returnsinteger?: A texture handle, or nil / null before enableRender.

scene.setOverlay

ClientLua Β· JS
luaLua
scene:setOverlay(opts) --> boolean
jsJavaScript
scene.setOverlay(opts: SceneOverlay | boolean): boolean

Show the live image on the screen.

LS:MP draws the image in a rectangle, above the game's HUD and below LS:MP pages. true / false shows or hides it; a table changes the fields it gives, and sets visible back to true unless it says otherwise. The overlay shows the scene only once it has an image: enable live rendering first.

Parameters
ParameterTypeDescription
optsSceneOverlay | booleanvisible (default true), bounds ({ x, y, width, height } as fractions of the game's screen: 0 is the left or top edge, 1 the right or bottom one; default a quarter of the screen at the top left), zIndex (between overlays: the highest is drawn on top, default 0).
Returnsboolean: true when applied; false otherwise, with the code in lsmp.getLastError(): limit, unavailable, error.

scene.getRenderInfo

ClientLua Β· JS
luaLua
scene:getRenderInfo() --> SceneRenderInfo?
jsJavaScript
scene.getRenderInfo(): SceneRenderInfo | null

How the live rendering is doing.

ReturnsSceneRenderInfo?: nil / null when the scene does not render live. Fields: enabled, fps (frames actually rendered per second), frames (live frames since creation), skipped (frames where the scene waited its turn because the live scenes together went over the per-frame budget), gpuMs (graphics-card time of one render), texture, width, height, overlay (shown or not).
β„Ή
What it costs

A live scene costs the graphics card in proportion to its rendered pixels, width Γ— supersample by height Γ— supersample. Pick the smallest size and supersampling that look right, lower fps when the image moves slowly, and read getRenderInfo().gpuMs for the cost on the player's machine.

Destroying a scene

scene.destroy

ClientLua Β· JS
luaLua
scene:destroy()
jsJavaScript
scene.destroy(): void

Destroy the scene and give its memory back.

Shots still in flight reject with cancelled. The entities are left as they are in the world. Live rendering stops: the overlay disappears, and every game texture replaced with the scene's texture gets its original back.

scene.isValid

ClientLua Β· JS
luaLua
scene:isValid() --> boolean
jsJavaScript
scene.isValid(): boolean

false once the scene was destroyed, by the script or because its resource stopped.

Returnsboolean

On a destroyed scene, methods do nothing and return false, nil / null or 0, with the code not-found. A scene of another resource raises an Error.

Game textures

The texture of a scene that renders live (scene.getTexture) is a texture handle like any other: lsmp.replaceTexture shows it in place of a texture of the game. The handle belongs to the scene and goes with it: lsmp.releaseTexture refuses it. See Textures.

Limits

LimitValue
Scenes8 per resource, 16 on the client
Pixels, all scenes togetherAbout 8 million, counted at the rendered size (width Γ— supersample by height Γ— supersample)
Entities per scene32
Lights per scene32, the key light included; 8 of them light transparent surfaces
Shots in flight4 per scene
Scenes rendering live8 on the client; beyond the per-frame pixel budget, live scenes take turns (skipped)
β„Ή
When the resource stops

Its scenes are destroyed, its texture replacements are restored, and the Promises or callbacks of pending shots never complete.

Client Β· Lua & JS

Textures

Make a texture from an image file, from downloaded data or from pixels you compute, then show it in place of a texture of the game: a billboard, a poster, a vehicle livery, a sprite on screen.

A texture handle is an image owned by your resource, kept on the graphics card. A handle comes from one of three places:

- lsmp.createTexture: a still image, from a file or from pixels;
- a 3D browser: a web page, repainted as it changes;
- a scene that renders live.

Whatever its origin, lsmp.replaceTexture shows it in place of a texture of the game.

luaLua
-- The logo of the server on a billboard of the map.
local logo, err = lsmp.createTexture({ file = "img/logo.png" })
if not logo then return lsmp.warn("no texture: " .. err) end

lsmp.replaceTexture(logo, {
  type = "txd", container = "cs4_02_build_1", name = "cs4_02_rsl_mr_bb",
})
jsJavaScript
// The logo of the server on a billboard of the map.
const logo = lsmp.createTexture({ file: 'img/logo.png' });
if (logo === null) {
  lsmp.warn(`no texture: ${lsmp.getLastError()}`);
} else {
  lsmp.replaceTexture(logo, {
    type: 'txd', container: 'cs4_02_build_1', name: 'cs4_02_rsl_mr_bb',
  });
}

Creating a texture

lsmp.createTexture

ClientLua Β· JS
luaLua
lsmp.createTexture(source) --> integer?
jsJavaScript
lsmp.createTexture(source: TextureSource): number | null

Make a texture from an image file, from the content of an image file or from raw pixels.

Give it exactly one source:

- file: an image file shipped with your resource, with a path relative to the resource root. List the file in files of the manifest so that players receive it.
- data: the content of an image file that you already hold, for instance the body of an HTTP response.
- pixels: pixels that you computed, with width and height.

The handle is returned at once, and you can give it to replaceTexture right away. The image itself is decoded in the background, so even a large file does not freeze the game. A replacement shows once the image is ready, never a blank texture in the meantime. getTextureInfo tells where the image stands.

Failure codes: not-found (no such file in the resource), invalid (not a PNG, JPEG, WebP or DDS image that can be read), limit (larger than 4096 pixels on a side, over a limit of the resource, or more than the game can upload at once), unavailable (the game is not ready yet). See Error codes.

Parameters
ParameterTypeDescription
sourceTextureSourceWhere the image comes from: { file }, { data } or { pixels, width, height, format }. See the table below.
Returns (Lua)integer?: The texture handle, or nil and a code.
Returns (JavaScript)number | null: The texture handle, or null with the code in lsmp.getLastError().
Example
luaLua
-- An image downloaded while the server runs.
lsmp.http.get("https://example.com/banner.webp", { responseType = "bytes" }, function(res, err)
  if not res or not res.ok then return lsmp.warn("no banner") end
  local banner, code = lsmp.createTexture({ data = res.body })
  if not banner then lsmp.warn("banner refused: " .. code) end
end)

-- A 64 x 64 checkerboard built pixel by pixel: red, green, blue, alpha.
local size, rows = 64, {}
for y = 0, size - 1 do
  local row = {}
  for x = 0, size - 1 do
    local white = (math.floor(x / 8) + math.floor(y / 8)) % 2 == 0
    row[#row + 1] = white and "\255\255\255\255" or "\30\30\30\255"
  end
  rows[#rows + 1] = table.concat(row)
end
local checker = lsmp.createTexture({ pixels = table.concat(rows), width = size, height = size })
jsJavaScript
// An image downloaded while the server runs.
async function loadBanner() {
  const res = await lsmp.http.get('https://example.com/banner.webp', { responseType: 'bytes' });
  if (!res.ok) return null;
  const banner = lsmp.createTexture({ data: res.body });
  if (banner === null) lsmp.warn(`banner refused: ${lsmp.getLastError()}`);
  return banner;
}

// A 64 x 64 checkerboard built pixel by pixel: red, green, blue, alpha.
const size = 64;
const pixels = new Uint8Array(size * size * 4);
for (let y = 0; y < size; y++) {
  for (let x = 0; x < size; x++) {
    const white = ((x >> 3) + (y >> 3)) % 2 === 0;
    pixels.set(white ? [255, 255, 255, 255] : [30, 30, 30, 255], (y * size + x) * 4);
  }
}
const checker = lsmp.createTexture({ pixels, width: size, height: size });
Field of the sourceTypeMeaning
filestringPath of an image file of this resource, relative to its root, with / separators and no ...
databytesThe content of a PNG, JPEG, WebP or DDS file: a string in Lua, a Uint8Array or an ArrayBuffer in JavaScript.
pixelsbytesRaw pixels, 4 bytes each, rows from top to bottom, without padding: exactly width * height * 4 bytes.
width, heightintegerSize of pixels, 1 to 4096 each. Required with pixels, refused otherwise.
formatstringByte order of pixels: "rgba" (the default) or "bgra".

Image files

The type of an image is recognized from its content, not from its file name.

FormatWhat is read
PNGEvery color type and bit depth, with transparency.
JPEGBaseline and progressive, 8 bits per channel.
WebPLossy and lossless, with transparency. Animated WebP files are refused.
DDSUncompressed 8, 16, 24 and 32 bit formats, and the block compressed formats DXT1, DXT3, DXT5 (BC1 to BC3), BC4, BC5 and BC7. Cube maps, volume textures, texture arrays, BC6H and floating point formats are refused.
β„Ή
What the game gets

Every image becomes an uncompressed texture, 8 bits per channel with an alpha channel, at the size of the image and without mipmaps. Of a DDS file, only the largest level is read. Keep the image close to the size it has on screen: a 4096 pixel image on a small sign takes 64 MiB of video memory and shimmers from far away. Transparency is plain alpha, not premultiplied.

lsmp.getTextureInfo

ClientLua Β· JS
luaLua
lsmp.getTextureInfo(texture) --> TextureInfo?
jsJavaScript
lsmp.getTextureInfo(texture: number): TextureInfo | null

Size and state of a texture of this resource.

Works on every texture handle of the resource, the one of a 3D browser or of a scene included. state is:

- "loading": the image is still being decoded or sent to the graphics card;
- "ready": the texture shows its image;
- "failed": the image was damaged and could not be decoded. The texture stays valid but is never shown; release it.

The texture of a 3D browser or of a scene is always "ready".

Parameters
ParameterTypeDescription
textureintA texture handle of this resource.
Returns (Lua)TextureInfo?: { width, height, state }, or nil and not-found when the handle is unknown or belongs to another resource.
Returns (JavaScript)TextureInfo | null: { width, height, state }, or null with not-found when the handle is unknown or belongs to another resource.
Example
luaLua
-- Say so when the file shipped with the resource is damaged.
local logo = lsmp.createTexture({ file = "img/logo.png" })
setTimeout(function()
  local info = logo and lsmp.getTextureInfo(logo)
  if info and info.state == "failed" then
    lsmp.warn("img/logo.png cannot be read")
  end
end, 3000)
jsJavaScript
// Say so when the file shipped with the resource is damaged.
const logo = lsmp.createTexture({ file: 'img/logo.png' });
setTimeout(() => {
  const info = logo === null ? null : lsmp.getTextureInfo(logo);
  if (info && info.state === 'failed') lsmp.warn('img/logo.png cannot be read');
}, 3000);

lsmp.releaseTexture

ClientLua Β· JS
luaLua
lsmp.releaseTexture(texture) --> boolean
jsJavaScript
lsmp.releaseTexture(texture: number): boolean

Free a texture made by createTexture, restoring every replacement that used it.

Only the textures you made with createTexture can be released. The texture of a 3D browser or of a scene belongs to it and is freed when you destroy the browser or the scene: releasing it is refused with permission.

Failure codes: not-found (unknown handle, already released, or a texture of another resource), permission.

Parameters
ParameterTypeDescription
textureintA handle returned by createTexture.
Returns (Lua)boolean: true when the texture was freed; false and a code otherwise.
Returns (JavaScript)boolean: true when the texture was freed; false otherwise, with the code in lsmp.getLastError().

Showing a texture in the game

A replacement names a texture of the game by its container (the .ytd, .ydr, .ydd or .yft file that holds it, without extension) and its name, as a model viewer shows them. Every surface that uses that texture then shows yours.

lsmp.replaceTexture

ClientLua Β· JS
luaLua
lsmp.replaceTexture(texture, target) --> integer?
jsJavaScript
lsmp.replaceTexture(texture: number, target: TextureTarget): number | null

Show a texture handle in place of a texture of the game.

The replacement applies whenever the game has the target loaded, and again each time it streams back in. Binding the same texture to the same target twice returns the same id. To draw the image as a sprite, replace a texture of a dictionary that you load and draw yourself.

Failure codes: not-found (unknown texture handle, or target that cannot be replaced), permission (a texture of another resource). See Error codes.

Parameters
ParameterTypeDescription
textureintA texture handle of this resource.
targetTextureTarget{ type, container, name }: type is "txd" (a texture dictionary, .ytd), "drawable" (.ydr), "drawabledict" (.ydd) or "fragment" (.yft); container is the name of the file without extension; name is the texture inside it.
Returns (Lua)integer?: The id of the replacement, or nil and a code.
Returns (JavaScript)number | null: The id of the replacement, or null with the code in lsmp.getLastError().
Example
luaLua
-- Use a configured scene as a live texture in the world.
if scene:enableRender(true) then
  local texture = scene:getTexture()
  if texture then
    lsmp.replaceTexture(texture, {
      type = "txd", container = "cs4_02_build_1", name = "cs4_02_rsl_mr_bb",
    })
  end
end
jsJavaScript
// Use a configured scene as a live texture in the world.
if (scene.enableRender(true)) {
  const texture = scene.getTexture();
  if (texture !== null) {
    lsmp.replaceTexture(texture, {
      type: 'txd', container: 'cs4_02_build_1', name: 'cs4_02_rsl_mr_bb',
    });
  }
}

lsmp.restoreTexture

ClientLua Β· JS
luaLua
lsmp.restoreTexture(bindId) --> boolean
jsJavaScript
lsmp.restoreTexture(bindId: number): boolean

Give the game its original texture back.

Parameters
ParameterTypeDescription
bindIdintThe id returned by replaceTexture.
Returnsboolean: false when the id is unknown or belongs to another resource.

Drawing a texture on screen

The game draws sprites from texture dictionaries. To draw your own image, ship a small dictionary in your resource (see Assets and streaming) with a placeholder texture, replace the placeholder, then draw the sprite every frame.

luaLua
-- my_hud.ytd is shipped by the resource and holds a texture named "slot".
local badge = lsmp.createTexture({ file = "img/badge.png" })
if badge then
  requestStreamedTextureDict("my_hud", false)
  lsmp.replaceTexture(badge, { type = "txd", container = "my_hud", name = "slot" })

  lsmp.onTick(function()
    if hasStreamedTextureDictLoaded("my_hud") then
      drawSprite("my_hud", "slot", 0.9, 0.12, 0.08, 0.14, 0.0, 255, 255, 255, 255, false, 0)
    end
  end)
end
jsJavaScript
// my_hud.ytd is shipped by the resource and holds a texture named 'slot'.
const badge = lsmp.createTexture({ file: 'img/badge.png' });
if (badge !== null) {
  requestStreamedTextureDict('my_hud', false);
  lsmp.replaceTexture(badge, { type: 'txd', container: 'my_hud', name: 'slot' });

  lsmp.onTick(() => {
    if (hasStreamedTextureDictLoaded('my_hud')) {
      drawSprite('my_hud', 'slot', 0.9, 0.12, 0.08, 0.14, 0.0, 255, 255, 255, 255, false, 0);
    }
  });
}
βœ“
A page is often simpler

For an interface, a web page drawn over the game does the same with HTML and CSS. A sprite is the right tool when the image must go through the game itself: a marker in the world, or an image drawn behind the HUD.

Limits

LimitValue
Size of an image4096 pixels on a side
Size of an image file (file, data)96 MiB
Textures made by createTexture256 per resource
Pixels of those textures256 MiB per resource, counted as width * height * 4 bytes
β„Ή
When the resource stops

Its textures are freed and its replacements are restored: the game shows its own textures again.

Client Β· Lua & JS

Camera capture

Render a scripted camera to an image the player never sees: portraits, thumbnails, a character on a transparent background.

lsmp.captureCamera renders a scripted camera through the game, at full quality, during a frame the player does not see: their screen keeps the previous image for that frame. The image is resized, encoded and handed to your script as bytes, or as a data URL ready for a page.

To shoot only chosen entities in a studio of their own, with no map around them, use render scenes instead.

lsmp.captureCamera

ClientLua Β· JS
luaLua
lsmp.captureCamera(camera [, opts] [, cb]) --> CaptureResult, err
jsJavaScript
lsmp.captureCamera(camera: number, opts?: CaptureOptions): Promise<CaptureResult>

Capture what a scripted camera sees.

The capture takes a few frames. Asynchronous: see Conventions. The Promise carries the capture number in promise.jobId; in Lua, the callback form returns it.

Failure codes: not-found (unknown or destroyed camera), limit (too many captures queued, for this resource or for the client), cancelled (the capture was dropped, for instance the resource is stopping), error (anything else: the game was paused or loading for too long, the resolution changed, encoding failed, capture switched off in the player's settings). The error message gives the precise reason. See Error codes.

Parameters
ParameterTypeDescription
camerahandleA scripted camera, from createCam, createCamWithParams and the camera natives.
opts optCaptureOptionsSee the options.
Returns (Lua)CaptureResult, err: The result, or nil and a code.
Returns (JavaScript)Promise<CaptureResult>: Resolves with the result; rejects with a code.
Example
luaLua
-- A 256 x 256 portrait of the local player, shown in our page.
local function portrait(browser)
  local ped = playerPedId()
  local pos = getEntityCoords(ped, false)
  local heading = getEntityHeading(ped)
  local rad = math.rad(heading)
  local cam = createCamWithParams("DEFAULT_SCRIPTED_CAMERA",
    pos.x - math.sin(rad) * 1.2, pos.y + math.cos(rad) * 1.2, pos.z + 0.6,
    0.0, 0.0, heading + 180.0, 35.0, false, 0)

  local res, err = lsmp.captureCamera(cam, { width = 256, height = 256, dataUrl = true })
  destroyCam(cam, false)
  if res then
    browser:emit("portrait", res.dataUrl)
  else
    lsmp.warn("capture failed: " .. err)
  end
end
jsJavaScript
// A 256 x 256 portrait of the local player, shown in our page.
async function portrait(browser) {
  const ped = playerPedId();
  const pos = getEntityCoords(ped, false);
  const heading = getEntityHeading(ped);
  const rad = heading * Math.PI / 180;
  const cam = createCamWithParams('DEFAULT_SCRIPTED_CAMERA',
    pos.x - Math.sin(rad) * 1.2, pos.y + Math.cos(rad) * 1.2, pos.z + 0.6,
    0.0, 0.0, heading + 180.0, 35.0, false, 0);

  try {
    const res = await lsmp.captureCamera(cam, { width: 256, height: 256, dataUrl: true });
    browser.emit('portrait', res.dataUrl);
  } catch (err) {
    lsmp.warn(`capture failed: ${err.code}`);
  } finally {
    destroyCam(cam, false);
  }
}

Options

OptionTypeDefaultMeaning
width, heightint512Output size in pixels, 16 to 4096.
formatstring"webp""png", "jpeg" or "webp". WebP keeps the transparency of PNG at a fraction of its size.
qualityint90JPEG and WebP quality, 0 to 100. WebP at 100 is lossless.
settleFramesint2Frames rendered before the shot, 0 to 30, so that streaming and exposure settle after the camera moved.
fovdegreesthe camera'sVertical field of view of the image, above 0 and below 180.
dataUrlbooleanfalseAlso return a data:image/...;base64,... URL, ready for an <img> in a page.
chromaKeyboolean | color | tableofftrue makes a green background transparent. A color picks the color to remove. A table { color, similarity, smoothness, spill } tunes it: the three numbers are 0 to 1, defaults 0.4, 0.08 and 0.1. Only useful with png or webp.

Result

FieldTypeMeaning
width, heightintSize of the image.
formatstringThe format of data.
databytesThe encoded image: a string in Lua, a Uint8Array in JavaScript.
dataUrlstring?The data URL when dataUrl was asked for; nil / null otherwise.
sourceWidth, sourceHeightintSize of the region of the frame that was read.
upscaledbooleantrue when the output is larger than that region: ask for a smaller size, or play at a higher resolution, for a sharper image.
framesintFrames the capture took.
msmsTime the capture took.
β„Ή
When the resource stops

Its pending captures are dropped: their Promise or callback never completes. The player sees nothing of it.

Client Β· Lua & JS

Hot resources, stream sets and archives

Mount and unmount client resources while the game runs, load parts of their streamed assets on demand, take game assets and archives out of the streaming, and quiet the story-mode scripts.

Everything on this page changes what the game streams. These calls are jobs: the call returns at once, and the work runs in order with every other job of the client, whichever resource or language asked for it. A job never blocks the game. Read Assets and streaming first for the concepts and complete recipes.

  • Jobs run in the order they were requested: unregister the old map, then mount the resource of the new one, without waiting in between.
  • A job that cannot start (unknown resource, unknown set) fails at once: the Promise rejects, the Lua callback receives the code. Never synchronously: see Conventions.
  • When a resource stops, the Promises and callbacks it was waiting for are dropped. The jobs themselves run to their end.

Resources

lsmp.mountResource

ClientLua Β· JS
luaLua
lsmp.mountResource(name [, cb]) --> boolean, err
jsJavaScript
lsmp.mountResource(name: string): Promise<boolean>

Mount a client resource the server offers, downloading it if needed, then start its scripts.

For a resource the server lists but does not start on its own, or one that was unmounted earlier. With unmountResource, the only change made to resources while connected: the server's own resources start with the server and run until it stops. The resources it depends on are started first. Asynchronous: see Conventions. In JavaScript the Promise carries the job number in promise.jobId; in Lua, the callback form returns it.

Failure codes: not-found (the server offers no client resource of that name), error (the job failed: download, a dependency that cannot start). See Error codes.

Parameters
ParameterTypeDescription
namenameThe resource name.
Returns (Lua)boolean, err: true once the resource is started; false and a code otherwise.
Returns (JavaScript)Promise<boolean>: Resolves with true once the resource is started; rejects with a code otherwise.
Example
luaLua
local ok, err = lsmp.mountResource("island_b")
if ok then
  lsmp.emitServer("island:ready")
else
  lsmp.warn("island_b did not start: " .. err)
end
jsJavaScript
async function openIsland() {
  try {
    await lsmp.mountResource('island_b');
    lsmp.emitServer('island:ready');
  } catch (err) {
    lsmp.warn(`island_b did not start: ${err.code}`);
  }
}

lsmp.unmountResource

ClientLua Β· JS
luaLua
lsmp.unmountResource(name [, cb]) --> boolean, err
jsJavaScript
lsmp.unmountResource(name: string): Promise<boolean>

Stop a client resource and unmount it: its scripts end, its assets leave the streaming.

The resource receives resourceStop first, like every other resource, and keeps a short grace period to clean up. Only this player's copy stops: the server half of the resource keeps running. Asynchronous: see Conventions. In JavaScript the Promise carries the job number in promise.jobId; in Lua, the callback form returns it.

A resource can stop itself: the call is accepted, and its own Promise or callback never completes, since the resource is gone when the job ends.

Failure codes: not-found. See Error codes.

Parameters
ParameterTypeDescription
namenameThe resource name.
Returns (Lua)boolean, err: true once the resource is stopped; false and a code otherwise.
Returns (JavaScript)Promise<boolean>: Resolves with true once the resource is stopped; rejects with a code otherwise.
Example
luaLua
-- Swap two maps, in order.
local ok = lsmp.unmountResource("island_a")
if ok then lsmp.mountResource("island_b") end
jsJavaScript
// Swap two maps, in order.
async function swapIslands() {
  await lsmp.unmountResource('island_a');
  await lsmp.mountResource('island_b');
}

Stream sets

A resource can split its streamed files into named stream sets, declared in its manifest (stream_sets, see Resource layout). A set declared with "load": "manual" stays out of the streaming until a script loads it. Everything is already in the package: loading a set later downloads nothing.

lsmp.resources.loadStreamSet

ClientLua Β· JS
luaLua
lsmp.resources.loadStreamSet(resource, set [, cb]) --> boolean, err
jsJavaScript
lsmp.resources.loadStreamSet(resource: string, set: string): Promise<boolean>

Put the assets of a stream set in the streaming.

Works on any mounted resource, not only the caller. Loading a set that is already loaded succeeds: the result says the set is loaded, not that this call changed it. The call can be queued right behind the mountResource of the same resource. Asynchronous: see Conventions. In JavaScript the Promise carries the job number in promise.jobId; in Lua, the callback form returns it.

Failure codes: not-found (the resource is not mounted and not being mounted, or has no set of that name), error. See Error codes.

Parameters
ParameterTypeDescription
resourcenameA mounted resource.
setstringThe name of one of its stream sets. Exact, case-sensitive.
Returns (Lua)boolean, err: true once the set is loaded; false and a code otherwise.
Returns (JavaScript)Promise<boolean>: Resolves with true once the set is loaded; rejects with a code otherwise.
Example
luaLua
local ok, err = lsmp.resources.loadStreamSet("las-venturas", "addons")
if not ok then lsmp.warn("addons: " .. err) end
jsJavaScript
lsmp.resources.loadStreamSet('las-venturas', 'addons')
  .catch((err) => lsmp.warn(`addons: ${err.code}`));

lsmp.resources.unloadStreamSet

ClientLua Β· JS
luaLua
lsmp.resources.unloadStreamSet(resource, set [, cb]) --> boolean, err
jsJavaScript
lsmp.resources.unloadStreamSet(resource: string, set: string): Promise<boolean>

Take the assets of a stream set out of the streaming.

Each name the set provided falls back to what is below it: another set, the rest of the resource, another resource, or the game's own file. A model or texture still in use is not taken away from what uses it: it leaves once released, and the job still succeeds. Same rules and codes as loadStreamSet, except that error is the only failure once the job started.

Parameters
ParameterTypeDescription
resourcenameA mounted resource.
setstringThe name of the set.
Returns (Lua)boolean, err: true once the set is unloaded; false and a code otherwise.
Returns (JavaScript)Promise<boolean>: Resolves with true once the set is unloaded; rejects with a code otherwise.

lsmp.resources.getStreamSetState

ClientLua Β· JS
luaLua
lsmp.resources.getStreamSetState(resource, set) --> string?
jsJavaScript
lsmp.resources.getStreamSetState(resource: string, set: string): string | null

The state of a stream set, read at once.

Parameters
ParameterTypeDescription
resourcenameA resource.
setstringThe name of the set.
Returnsstring?: "unloaded", "loading", "loaded" or "unloading"; nil / null when the resource is not mounted or has no set of that name.
Example
luaLua
if lsmp.resources.getStreamSetState("las-venturas", "addons") == "unloaded" then
  lsmp.resources.loadStreamSet("las-venturas", "addons")
end
jsJavaScript
if (lsmp.resources.getStreamSetState('las-venturas', 'addons') === 'unloaded') {
  lsmp.resources.loadStreamSet('las-venturas', 'addons');
}

Streaming assets

These functions act on named assets of the streaming, the game's and those of every mounted resource. A name is the file name with its extension, which says what kind of asset it is: "prop_alien_egg_01.ydr", "cs1_01.ybn", "my_textures.ytd".

lsmp.resources.unregisterAssets

ClientLua Β· JS
luaLua
lsmp.resources.unregisterAssets(names [, cb]) --> AssetJobResult, err
jsJavaScript
lsmp.resources.unregisterAssets(names: string[]): Promise<AssetJobResult>

Take assets out of the streaming.

The whole list is one job. Send one large list rather than many small ones: 100,000 names is one call. A model or texture that something still uses is refused and counted in failed: it stays as it was. Maps (.ymap) and collisions (.ybn) are unloaded on the spot, so do it behind a loading screen. Asynchronous: see Conventions. In JavaScript the Promise carries the job number in promise.jobId; in Lua, the callback form returns it.

Failure code: error (the job could not run). See Error codes.

Parameters
ParameterTypeDescription
names Lua only{string}1 to 1,048,576 asset names, each a non-empty string.
names JavaScript onlystring[]1 to 1,048,576 asset names, each a non-empty string.
Returns (Lua)AssetJobResult, err: { done, failed }: names processed and names refused. A refused name is not a failure of the call.
Returns (JavaScript)Promise<AssetJobResult>: Resolves with { done, failed }: names processed and names refused. A refused name does not reject the Promise.
Example
luaLua
local names = lsmp.json.decode(lsmp.readResourceFile("data/base_map.json"))
local res, err = lsmp.resources.unregisterAssets(names)
if res then
  lsmp.log(("unregistered %d, refused %d"):format(res.done, res.failed))
end
jsJavaScript
async function clearBaseMap() {
  const names = JSON.parse(lsmp.readResourceFile('data/base_map.json'));
  const res = await lsmp.resources.unregisterAssets(names);
  lsmp.log(`unregistered ${res.done}, refused ${res.failed}`);
}

lsmp.resources.registerAssets

ClientLua Β· JS
luaLua
lsmp.resources.registerAssets(names [, cb]) --> AssetJobResult, err
jsJavaScript
lsmp.resources.registerAssets(names: string[]): Promise<AssetJobResult>

Put back assets that a script took out of the streaming.

Same rules and result as unregisterAssets. Failure codes: error, limit. See Error codes.

Parameters
ParameterTypeDescription
names Lua only{string}1 to 1,048,576 asset names.
names JavaScript onlystring[]1 to 1,048,576 asset names.
Returns (Lua)AssetJobResult, err: { done, failed }: names processed and names refused. A refused name is not a failure of the call.
Returns (JavaScript)Promise<AssetJobResult>: Resolves with { done, failed }: names processed and names refused. A refused name does not reject the Promise.

lsmp.resources.getAssetState

ClientLua Β· JS
luaLua
lsmp.resources.getAssetState(name) --> string?
jsJavaScript
lsmp.resources.getAssetState(name: string): string | null

The state of one asset, read at once.

Parameters
ParameterTypeDescription
namestringAsset name, with its extension.
Returnsstring?: "registered" (in the streaming) or "unregistered" (taken out by a script); nil / null when no asset has that name.

Game archives

lsmp.resources.invalidateArchives

ClientLua Β· JS
luaLua
lsmp.resources.invalidateArchives(names [, cb]) --> AssetJobResult, err
jsJavaScript
lsmp.resources.invalidateArchives(names: string[]): Promise<AssetJobResult>

Switch whole streaming archives of the game off.

This is what a map DLC does with filesToInvalidate: the maps of an invalidated archive are unloaded and ignored, its other assets leave memory once nothing uses them. Nothing is deleted: restoreArchives gives everything back, and so does stopping the resource that invalidated them, or leaving the server.

Send all the archives in one call: the whole base map is one job. Only streaming archives are known here; a data archive is counted in failed. Invalidating does not free room in the game's asset stores: to make room for another map, also unregister its models and textures. Asynchronous: see Conventions. In JavaScript the Promise carries the job number in promise.jobId; in Lua, the callback form returns it.

Failure code: error. See Error codes.

Parameters
ParameterTypeDescription
names Lua only{string}Archive names as the game registers them, the strings a DLC content.xml lists under filesToInvalidate: "platform:/levels/gta5/_citye/downtown_01/dt1_01.rpf".
names JavaScript onlystring[]Archive names as the game registers them, the strings a DLC content.xml lists under filesToInvalidate: "platform:/levels/gta5/_citye/downtown_01/dt1_01.rpf".
Returns (Lua)AssetJobResult, err: { done, failed }: names processed and names refused. A refused name is not a failure of the call.
Returns (JavaScript)Promise<AssetJobResult>: Resolves with { done, failed }: names processed and names refused. A refused name does not reject the Promise.
Example
luaLua
local res = lsmp.resources.invalidateArchives({
  "platform:/levels/gta5/_citye/downtown_01/dt1_01.rpf",
  "platform:/levels/gta5/_citye/downtown_01/dt1_02.rpf",
})
if res then lsmp.log(res.done .. " archives switched off") end
jsJavaScript
lsmp.resources.invalidateArchives([
  'platform:/levels/gta5/_citye/downtown_01/dt1_01.rpf',
  'platform:/levels/gta5/_citye/downtown_01/dt1_02.rpf',
]).then((res) => lsmp.log(`${res.done} archives switched off`));

lsmp.resources.restoreArchives

ClientLua Β· JS
luaLua
lsmp.resources.restoreArchives(names [, cb]) --> AssetJobResult, err
jsJavaScript
lsmp.resources.restoreArchives(names: string[]): Promise<AssetJobResult>

Switch archives that this resource invalidated back on.

Same rules and result as invalidateArchives. It happens on its own when the resource stops. Failure code: error.

Parameters
ParameterTypeDescription
names Lua only{string}Archive names.
names JavaScript onlystring[]Archive names.
Returns (Lua)AssetJobResult, err: { done, failed }: names processed and names refused. A refused name is not a failure of the call.
Returns (JavaScript)Promise<AssetJobResult>: Resolves with { done, failed }: names processed and names refused. A refused name does not reject the Promise.

lsmp.resources.getArchiveState

ClientLua Β· JS
luaLua
lsmp.resources.getArchiveState(name) --> string?
jsJavaScript
lsmp.resources.getArchiveState(name: string): string | null

The state of one game archive, read at once.

Parameters
ParameterTypeDescription
namestringArchive name as the game registers it.
Returnsstring?: "active" or "invalidated"; nil / null when no streaming archive has that name.

Story-mode scripts

The story-mode scripts of the game keep running in a session, and some of them load map pieces (IPLs) or start activities of their own. These calls quiet them. Each one is an owned setting: the last resource that calls it wins, and what it changed is restored when that resource stops.

lsmp.resources.suspendScriptIpls

ClientLua Β· JS
luaLua
lsmp.resources.suspendScriptIpls([cb]) --> AssetJobResult, err
jsJavaScript
lsmp.resources.suspendScriptIpls(): Promise<AssetJobResult>

Unload the map pieces (IPLs) that the story scripts load, and keep them from loading again.

For a server that replaces the map, or needs the world as the base game ships it, without the extra buildings and interiors the story adds. Asynchronous: see Conventions. In JavaScript the Promise carries the job number in promise.jobId; in Lua, the callback form returns it.

Failure code: error.

Returns (Lua)AssetJobResult, err: { done, failed }: names processed and names refused. A refused name is not a failure of the call.
Returns (JavaScript)Promise<AssetJobResult>: Resolves with { done, failed }: names processed and names refused. A refused name does not reject the Promise.
Example
luaLua
local res, err = lsmp.resources.suspendScriptIpls()
if not res then lsmp.warn("IPLs: " .. err) end
jsJavaScript
lsmp.resources.suspendScriptIpls().catch((err) => lsmp.warn(`IPLs: ${err.code}`));

lsmp.resources.resumeScriptIpls

ClientLua Β· JS
luaLua
lsmp.resources.resumeScriptIpls([cb]) --> AssetJobResult, err
jsJavaScript
lsmp.resources.resumeScriptIpls(): Promise<AssetJobResult>

Give the story scripts their map pieces back.

Undoes suspendScriptIpls. Failure code: error.

Returns (Lua)AssetJobResult, err: { done, failed }: names processed and names refused. A refused name is not a failure of the call.
Returns (JavaScript)Promise<AssetJobResult>: Resolves with { done, failed }: names processed and names refused. A refused name does not reject the Promise.

lsmp.resources.suspendStoryScript

ClientLua Β· JS
luaLua
lsmp.resources.suspendStoryScript(name) --> string
jsJavaScript
lsmp.resources.suspendStoryScript(name: string): string

Stop one story-mode script and keep it from starting again.

Synchronous. Some scripts of the game cannot be stopped this way: the result is then "refused".

Parameters
ParameterTypeDescription
namestringThe name of the game script, for example "blip_controller".
Returnsstring: "stopped", "loading", "running" (the state the script is in now), or "refused".
Example
luaLua
if lsmp.resources.suspendStoryScript("blip_controller") == "refused" then
  lsmp.warn("blip_controller cannot be stopped")
end
jsJavaScript
if (lsmp.resources.suspendStoryScript('blip_controller') === 'refused') {
  lsmp.warn('blip_controller cannot be stopped');
}

lsmp.resources.resumeStoryScript

ClientLua Β· JS
luaLua
lsmp.resources.resumeStoryScript(name) --> string
jsJavaScript
lsmp.resources.resumeStoryScript(name: string): string

Allow a story script to run again.

Undoes suspendStoryScript for this resource. The game starts the script again when it needs it.

Parameters
ParameterTypeDescription
namestringThe name of the game script.
Returnsstring: Same values as suspendStoryScript.
β„Ή
Everything is undone when the player leaves

Going to another server or back to story mode stops every resource, gives back every game asset a script unregistered, and switches invalidated archives back on.

Client Β· Lua & JS

Discord presence

What a player's Discord profile shows while they play on your server.

While a player is on a server and Discord runs on their machine, their Discord profile shows a card. By default its two lines are the server's name and the player count. A client script can replace them, and with a custom presence, the images, the buttons and the application.

  • Players decide. A player who turned the presence off in their LS:MP settings shows nothing, and every call returns false with the code permission.
  • Owned settings. Each field belongs to the resource that set it: the last writer wins, and the default comes back when that resource stops.
  • Change rarely. Discord limits how often a presence may change: update on a real change (a new area, a new vehicle), not every frame.
  • Texts are 128 bytes at most. nil/null puts the default back.

lsmp.discord.setDetails

ClientLua Β· JS
luaLua
lsmp.discord.setDetails(text) --> boolean
jsJavaScript
lsmp.discord.setDetails(text: string | null): boolean

Set the first line of the card.

Parameters
ParameterTypeDescription
textstring?The text, or nil/null for the default.
Returnsboolean: true if applied.
Failure codeWhen
permissionThe player turned the presence off.
Example
luaLua
local last = nil
lsmp.onTick(function()
  local vehicle = getVehiclePedIsIn(playerPedId(), false)
  local text = vehicle ~= 0 and "Driving" or "On foot"
  if text ~= last then
    last = text
    lsmp.discord.setDetails(text)
  end
end)
jsJavaScript
let last = null;
lsmp.onTick(() => {
  const text = getVehiclePedIsIn(playerPedId(), false) ? 'Driving' : 'On foot';
  if (text !== last) {
    last = text;
    lsmp.discord.setDetails(text);
  }
});

lsmp.discord.setState

ClientLua Β· JS
luaLua
lsmp.discord.setState(text) --> boolean
jsJavaScript
lsmp.discord.setState(text: string | null): boolean

Set the second line of the card.

Parameters
ParameterTypeDescription
textstring?The text, or nil/null for the default.
Returnsboolean: true if applied.
Failure codeWhen
permissionThe player turned the presence off.

lsmp.discord.setAsset

ClientLua Β· JS
luaLua
lsmp.discord.setAsset(slot, key [, hoverText]) --> boolean
jsJavaScript
lsmp.discord.setAsset(slot: string, key: string | null, hoverText?: string): boolean

Set the large or the small image of the card.

Needs a custom presence: the images are assets of your own Discord application (see setAppId), or https:// addresses from the hosts LS:MP accepts.

Parameters
ParameterTypeDescription
slotstring"large" or "small".
keystring?The asset key or image address, or nil/null for none.
hoverText optstringText shown when the image is hovered, 128 bytes at most.
Returnsboolean: true if applied.
Failure codeWhen
permissionThe player turned the presence off, or the server has no custom presence.

lsmp.discord.setButton

ClientLua Β· JS
luaLua
lsmp.discord.setButton(index, label [, url]) --> boolean
jsJavaScript
lsmp.discord.setButton(index: number, label: string | null, url?: string): boolean

Set one of the two buttons of the card.

Needs a custom presence. A button opens its address in the browser of whoever clicks it.

Parameters
ParameterTypeDescription
indexint0 or 1.
labelstring?The button text, or nil/null to remove the button.
url optstringAn https:// address; required with a label.
Returnsboolean: true if applied.
Failure codeWhen
permissionThe player turned the presence off, or the server has no custom presence.

lsmp.discord.setAppId

ClientLua Β· JS
luaLua
lsmp.discord.setAppId(appId) --> boolean
jsJavaScript
lsmp.discord.setAppId(appId: string): boolean

Show the card under your own Discord application.

Its name becomes the card's title and its assets become available to setAsset. Needs a custom presence.

Parameters
ParameterTypeDescription
appIdstringThe application id from the Discord developer portal: 17 to 20 digits, as a string.
Returnsboolean: true if applied.
Failure codeWhen
permissionThe player turned the presence off, or the server has no custom presence.

lsmp.discord.clear

ClientLua Β· JS
luaLua
lsmp.discord.clear()
jsJavaScript
lsmp.discord.clear(): void

Remove everything this resource set.

The card goes back to what other resources set, or to the default.

Page API

Page Β· JavaScript

The lsmp object in a page

What a web page opened by your resource can call: events and calls to and from the script that owns its browser, and a few read-only facts about the game.

Every page opened with lsmp.createBrowser or lsmp.createBrowser3D finds a global lsmp object, ready before the page's first script runs. It talks to one party: the client script that owns this browser, through that browser's handle (browser:on, browser:emit, browser:call). Two browsers never hear each other, and no page can reach another resource.

htmlweb/index.html
<!doctype html>
<html>
<body>
  <h1 id="hello">…</h1>
  <button id="buy">Buy a soda</button>
  <script>
    // The script sends 'init' once the page is loaded.
    lsmp.on('init', (name) => {
      document.getElementById('hello').textContent = `Hello, ${name}`;
    });

    // Ask the script, and wait for its answer.
    document.getElementById('buy').addEventListener('click', async () => {
      try {
        const answer = await lsmp.call('buy', 'soda', 1);
        document.getElementById('hello').textContent = answer.ok ? 'Enjoy!' : answer.error;
      } catch (err) {
        console.error('buy failed:', err.code);
      }
    });

    // Answer the script's calls.
    lsmp.on('getSelection', () => ({ item: 'soda', quantity: 1 }));
  </script>
</body>
</html>
luaclient/main.lua
local page = lsmp.createBrowser("rsc://shop/index.html", { focus = true })

page:on("load", function()
  page:emit("init", lsmp.getPlayerName(lsmp.getLocalPlayer()))
end)

page:on("buy", function(item, quantity)
  local ok, err = lsmp.callServer("shop:buy", item, quantity)
  return { ok = ok ~= nil, error = err }
end)
jsclient/main.js
const page = lsmp.createBrowser('rsc://shop/index.html', { focus: true });

page.on('load', () => {
  page.emit('init', lsmp.getPlayerName(lsmp.getLocalPlayer()));
});

page.on('buy', async (item, quantity) => {
  try {
    return { ok: true, result: await lsmp.callServer('shop:buy', item, quantity) };
  } catch (err) {
    return { ok: false, error: err.code };
  }
});

Which documents get it

Documentlsmp
The page loaded in a 2D or 3D browser of a resourceYes, linked to that browser.
An <iframe> of that page from the same origin (same rsc:// resource, or same site)Yes, linked to the same browser.
An <iframe> from another origin (video, ads, widget)No.
A popup opened by the pageNo.
The page opened in an ordinary web browser, outside the gameNo: see Developing outside the game.

The object is frozen: a page cannot replace or extend it, and a lsmp global the page declares itself is ignored.

Functions

lsmp.emit

pageJS
jsJavaScript
lsmp.emit(event: string, ...args: any[]): void

Send an event to the owning script's browser:on handlers.

Every handler of that name runs. If the script has none, the event is dropped silently. Throws a TypeError for a value that cannot travel (function, symbol, BigInt, NaN, Infinity, integer beyond 2^53), a RangeError for more than 32 arguments or a message over 120,000 characters of JSON, and an Error for a reserved name.

Not available in Lua.

Parameters
ParameterTypeDescription
eventstringEvent name, 1 to 128 characters, no control characters. load, loadError, focusLost, crash and names starting with lsmp: are reserved.
...args optanyUp to 32 JSON-compatible values; Uint8Array, ArrayBuffer and DataView travel as bytes.
Example
jsPage
document.querySelector('#close').addEventListener('click', () => {
  lsmp.emit('close');
});

document.querySelector('form').addEventListener('submit', (e) => {
  e.preventDefault();
  lsmp.emit('form:submit', Object.fromEntries(new FormData(e.target)));
});

lsmp.on

pageJS
jsJavaScript
lsmp.on(event: string, fn: (...args) => any): () => boolean

Handle an event or a call from the owning script.

For browser:emit, every handler runs. For browser:call, handlers run in order until one returns something other than undefined (a value, null, or a Promise): that is the answer, and a Promise is awaited. If they all return undefined, the answer is null. A handler that throws, or a Promise that rejects, answers with the code error (the error is printed in the page's console). With no handler, the script gets no-handler.

The same function registered twice for one name counts once.

Not available in Lua.

Parameters
ParameterTypeDescription
eventstringEvent name, same rules as lsmp.emit.
fnfunctionfn(...args); its return value (or Promise) answers a script call.
Returns() => boolean: Call it to remove the handler.
Example
jsPage
// Event from browser:emit('money', 1500)
lsmp.on('money', (amount) => {
  document.querySelector('#money').textContent = `$${amount}`;
});

// Call from browser:call('confirm', 'Sell your car?'): answers true or false
lsmp.on('confirm', (question) => askPlayer(question));

function askPlayer(question) {
  return new Promise((resolve) => {
    document.querySelector('#question').textContent = question;
    document.querySelector('#yes').onclick = () => resolve(true);
    document.querySelector('#no').onclick = () => resolve(false);
  });
}

lsmp.off

pageJS
jsJavaScript
lsmp.off(event: string, fn: Function): boolean

Remove a handler registered with lsmp.on.

Not available in Lua.

Parameters
ParameterTypeDescription
eventstringThe event name.
fnfunctionThe same function that was registered.
Returnsboolean: true if it was registered.

lsmp.call

pageJS
jsJavaScript
lsmp.call(event: string | { name: string, timeoutMs?: number }, ...args: any[]): Promise<any>

Call the owning script's browser:on handler and get its answer.

Same argument rules as lsmp.emit. The Promise rejects with an Error whose code says why:

Not available in Lua.

Parameters
ParameterTypeDescription
eventstring | { name, timeoutMs }The handler's name, or an object with name and timeoutMs (1 to 300000, default 10000).
...args optanyUp to 32 values.
ReturnsPromise<any>: Resolves with the script's answer (null when it returned nothing).
err.codeMeaning
timeoutNo answer in time.
no-handlerThe script has no browser:on handler for this name.
errorThe script's handler raised, or its answer could not be sent. The details are in the client console (F8), never in the page.
cancelledThe browser was destroyed or the page navigated away.
limit1024 calls are already waiting.
Example
jsPage
async function loadInventory() {
  try {
    const items = await lsmp.call({ name: 'inventory:list', timeoutMs: 5000 });
    render(items);
  } catch (err) {
    if (err.code === 'timeout') showMessage('The server is slow, try again.');
    else console.error('inventory:list failed', err.code);
  }
}

Constants

lsmp.version

pageJS
jsJavaScript
lsmp.version: string

The LS:MP version, such as "0.6.254".

Not available in Lua.

lsmp.gameVersion

pageJS
jsJavaScript
lsmp.gameVersion: string

The game version, such as "1.0.1158.16".

Not available in Lua.

lsmp.gameBuild

pageJS
jsJavaScript
lsmp.gameBuild: number

The game build number, such as 1158.

Not available in Lua.

lsmp.language

pageJS
jsJavaScript
lsmp.language: string

The language of the player's LS:MP interface, as a BCP 47 tag such as "fr-FR": use it to translate your page.

Not available in Lua.

lsmp.resource

pageJS
jsJavaScript
lsmp.resource: string

The name of the resource that owns this browser, such as "shop".

Not available in Lua.

Good to know

  • Order: the script's load handler runs once the page's document is ready (DOMContentLoaded). Register your lsmp.on handlers at the top of your scripts, not in a later callback, and they will be there for the first events.
  • Events the script sends before the page is ready are kept and delivered, in order, right after.
  • A page that navigates (or reloads) loses its handlers and its pending calls (cancelled); the script gets load again.
  • Never trust what a page sends: a page is code running on the player's machine. Check every value in the client script, and anything that matters on the server.
  • localStorage, IndexedDB, the microphone and the camera are available to pages, with a few rules: see Storage, microphone, camera and limits.

Developing outside the game

A page opened in Chrome or in your framework's dev server has no lsmp. A small stand-in keeps it working while you design it; in game, the real object is already there and the stand-in does nothing.

jsweb/lsmp-stub.js (load it first)
if (!('lsmp' in window)) {
  const handlers = new Map();
  window.lsmp = {
    version: 'dev', gameVersion: 'dev', gameBuild: 0, language: navigator.language, resource: 'dev',
    emit: (event, ...args) => console.log('[lsmp.emit]', event, ...args),
    on: (event, fn) => { handlers.set(event, fn); return () => handlers.delete(event); },
    off: (event) => handlers.delete(event),
    call: async (event, ...args) => { console.log('[lsmp.call]', event, ...args); return null; },
    // From the DevTools console: lsmp.fake('init', 'Jane')
    fake: (event, ...args) => handlers.get(event)?.(...args),
  };
}

In game, inspect your pages with DevTools. With local resources, a 2D browser can also open your dev server (http://localhost:5173) for hot reload.

tslsmp.d.ts (for TypeScript projects)
declare const lsmp: Readonly<{
  emit(event: string, ...args: unknown[]): void;
  on(event: string, fn: (...args: any[]) => unknown): () => boolean;
  off(event: string, fn: (...args: any[]) => unknown): boolean;
  call<T = unknown>(event: string | { name: string; timeoutMs?: number }, ...args: unknown[]): Promise<T>;
  version: string;
  gameVersion: string;
  gameBuild: number;
  language: string;
  resource: string;
}>;

Natives

Client Β· Lua & JS

Game natives

The game's natives are global functions in client scripts. Most work as they do in the game, some are checked first, and some are blocked.

About 6,700 game natives are global functions in client scripts, under the same names in Lua and JavaScript. They work on the game's own handles: convert a netId first with lsmp.getEntityFromNetId.

βœ“
Look one up

The natives reference lists each native with its arguments, its results, and what LS:MP does about it. Its Checked and Blocked filters list the natives described below. This page explains the rules they all follow.

Calling convention

  • Names are camelCase, always starting with a lowercase letter: SET_ENTITY_COORDS is setEntityCoords, _GET_LAST_ENTITY_HIT_BY_ENTITY is getLastEntityHitByEntity.
  • Out-params come back to you: skip them in the call and read them from the result. See Out-params.
  • Hashes come back unsigned, equal to lsmp.hash for the same name: getHashKey("adder") == lsmp.hash("adder"). As an argument, a hash can be given signed or unsigned.
  • A missing argument counts as 0, extra arguments are ignored, and an argument of the wrong type raises a TypeError that names the native and the argument.

Lua only:

  • A vector argument is three numbers, or one Vector3, which fills the same three slots: setEntityCoordsNoOffset(ped, pos, false, false, false).
  • A native that returns a vector gives a Vector3: local pos = getEntityCoords(ped, true).

JavaScript only:

  • A vector argument is three numbers, or one { x, y, z } object or [x, y, z] array, which fills the same three slots: setEntityCoordsNoOffset(ped, pos, false, false, false).
  • A native that returns a vector gives a plain { x, y, z } object: const { x, y, z } = getEntityCoords(ped, true).
luaLua
local ped = playerPedId()
setEntityHealth(ped, 200, 0)

local pos = getEntityCoords(ped, true)   -- a Vector3
local ahead = pos + getEntityForwardVector(ped) * 5.0
setEntityCoordsNoOffset(ped, ahead, false, false, false)
jsJavaScript
const ped = playerPedId();
setEntityHealth(ped, 200, 0);

const pos = getEntityCoords(ped, true);   // { x, y, z }
const fwd = getEntityForwardVector(ped);
setEntityCoordsNoOffset(ped, { x: pos.x + fwd.x * 5, y: pos.y + fwd.y * 5, z: pos.z }, false, false, false);
β„Ή
Input while LS:MP has the focus

While the LS:MP menu, the console or a focused page holds the keyboard and mouse, the input natives (isControlPressed and the like) report no input, so your key bindings do not fire while the player types.

Out-params

Many natives do not return their useful value: the game writes it through a pointer, such as a ground height, a screen size or a hit position. LS:MP allocates that pointer for you. Skip those arguments in the call, and read the values from the result, after the native's own return value.

Lua only:

βœ“
The contract

A native returns its own value first, if it has one, then its out-params in parameter order, as multiple return values.

JavaScript only:

βœ“
The contract

The results are the native's own value first, if it has one, then its out-params in parameter order. No result gives undefined, one gives the bare value, and two or more give an Array.

Lua only:

Out-paramYou receive
float*number
BOOL*boolean
int*integer, signed 32-bit
Hash*integer, unsigned
Entity*, Ped*, Vehicle*, Object*, Blip*integer, a game handle
scrVector3*Vector3

JavaScript only:

Out-paramYou receive
float*number
BOOL*boolean
int*number, signed 32-bit
Hash*number, unsigned
Entity*, Ped*, Vehicle*, Object*, Blip*number, a game handle
scrVector3*{ x, y, z }
luaLua
local ped = playerPedId()
local pos = getEntityCoords(ped, true)

-- BOOL return + float* out
local found, groundZ = getGroundZFor3dCoord(pos.x, pos.y, pos.z + 1.0, false, 0)

-- no return value + two vector outs
local mn, mx = getModelDimensions(getHashKey("adder"))
local size = mx - mn                     -- Vector3 arithmetic

-- no return value + two int outs
local w, h = getActualScreenResolution()

-- int return + BOOL* + two vector outs + Entity* out
local probe = startExpensiveSynchronousShapeTestLosProbe(pos.x, pos.y, pos.z, pos.x, pos.y, pos.z - 10.0, -1, ped, 7)
local result, hit, coords, normal, entity = getShapeTestResult(probe)
jsJavaScript
const ped = playerPedId();
const pos = getEntityCoords(ped, true);

// BOOL return + float* out
const [found, groundZ] = getGroundZFor3dCoord(pos.x, pos.y, pos.z + 1.0, false, 0);

// no return value + two vector outs: [{ x, y, z }, { x, y, z }]
const [mn, mx] = getModelDimensions(getHashKey('adder'));
const height = mx.z - mn.z;

// no return value + two int outs
const [w, h] = getActualScreenResolution();

// int return + BOOL* + two vector outs + Entity* out
const probe = startExpensiveSynchronousShapeTestLosProbe(pos, { x: pos.x, y: pos.y, z: pos.z - 10.0 }, -1, ped, 7);
const [result, hit, coords, normal, entity] = getShapeTestResult(probe);
⚠
Pointers the game only reads

Some natives take a value through a pointer only to read it: DELETE_PED(Ped* ped), DELETE_VEHICLE, REMOVE_BLIP, DELETE_ENTITY, the SET_*_AS_NO_LONGER_NEEDED family, the rope natives. LS:MP treats these pointers as outputs, so the value you give does not reach the game and the call has no effect on your handle. Each one carries a Known issue note in the natives reference.

Checked natives

The game trusts its arguments: an index out of range or a broken float can bring it down. LS:MP checks the arguments of the natives concerned before the game sees them, in both languages: an index must be in range, a float that must be a real number cannot be NaN or infinite, a handle must designate something alive, a required name must be given.

A refused call is silent: it does not raise, the native does not run, and it returns its neutral value (false, 0, 0.0 or a zero vector). If such a native seems to do nothing, check the accepted range on its entry in the natives reference.

FamilyNativesAccepted
HUD colorsreplaceHudColour, replaceHudColourWithRgbacolor 0 to 234
HUD componentsshowHudComponentThisFrame, hideHudComponentThisFrame, setHudComponentPosition and related0 to 160, scripted components 0 to 29
Vehicle windowsrollDownWindow, smashVehicleWindow, isVehicleWindowIntact and related0 to 7
Vehicle doorsisVehicleDoorFullyOpen, getIsDoorValid, getVehicleIndividualDoorLockStatus0 to 6
TyressetVehicleTyreFixed, getTyreHealth, setTyreHealth and related0 to 7
Vehicle classesgetVehicleClassMaxBraking, getVehicleClassMaxTraction and related0 to 22
Ped componentsgetPedDrawableVariation, getPedTextureVariation, getPedPaletteVariation0 to 11
Combat attributessetPedCombatAttributes0 to 90
TVsetTvChannel, setTvChannelPlaylist, setTvChannelPlaylistAtHourchannel -1 (off, for setTvChannel) or 0 to 4, hour 0 to 23
Text blocksrequestAdditionalText, hasAdditionalTextLoaded and relatedslot 0 to 21, 0 to 22 to query
MarkersdrawMarker, drawMarkerExtype 0 to 44, finite position, size and rotation
ClocksetClockTime, advanceClockTimeTo, networkOverrideClockTime, setClockDatehours 0–23, minutes and seconds 0–59, or a valid Gregorian date with a zero-based month and year 1898–2499

Enhanced 1158.16 adapters

These 17 client natives are available on GTA V Enhanced 1158.16. Calls on another build raise an error. LS:MP builds the game's structures from named script fields and returns ordinary Lua tables or JavaScript objects and arrays. Invalid arguments or incompatible target entities raise an error. Check the leading success value on query results that return one.

CallsResult or scope
getClosestRoadSuccess, south and north endpoints, south and north lane counts, and median width.
getGroupSizeLeader present as 0 or 1, then the number of followers.
getMpOutfitDataFromMetadataPass { male, index } with a zero-based index. Returns success and a record with componentDrawables, componentTextures, propDrawables, propTextures and tattooOverlays.
getPedHeadBlendDataSuccess and a record with six shape and skin IDs, three blend weights and Boolean isParent.
getPedNearbyPeds, getPedNearbyVehicles, getAllVehiclesCount and a dense array of up to 256 game handles. Lua starts at index 1, and JavaScript at index 0.
getPosFromFiredEventSuccess and the source position of the selected event type.
getWeaponHudStats, getWeaponComponentHudStatsSuccess and a record with damage, speed, capacity, accuracy and range.
addRope, attachEntitiesToRopeLoad rope textures before creation. Each resource can create up to 32 live ropes on this client. Attachments require a rope and two distinct local entities with physics instances owned by that resource.
taskScriptedAnimation, playEntityScriptedAnimScripted animation on a resource-owned local ped, vehicle or object. Load each clip dictionary first.
taskMoveNetworkByNameWithInitParams, taskMoveNetworkAdvancedByNameWithInitParamsMovement graphs on a resource-owned local ped. Clone override must be false. Flags may use only bits 0x04 and 0x08.
createMissionTrainReturns the local locomotive handle or 0. Preload the models for the selected variation. Pass false for both network flags.
luaLua
local pos = getEntityCoords(playerPedId(), true)
local found, south, north, lanesSouth, lanesNorth, median = getClosestRoad(pos, 0, 1, true)
if found then
    print(lanesSouth, lanesNorth, median)
end
jsJavaScript
const pos = getEntityCoords(playerPedId(), true);
const [found, south, north, lanesSouth, lanesNorth, median] = getClosestRoad(pos, 0, 1, true);
if (found) console.log(lanesSouth, lanesNorth, median);

For a scripted animation, pass a record per priority slot. Omit the record or use state: 0 for an empty slot, state: 1 for a clip, or state: 2 for three blended clips. Set dictionary, clip, phase, rate and weight, with the suffixes 2 and 3 for the other two clips. Phase and weight are 0–1, rate is 0–10, and rate and weight default to 1. The slot also accepts filter, blendIn and blendOut (0–60, default 0.25), duration (default -1), flags (bits 1, 2, 16, 32, 128 and 256) and ikFlags (must be zero).

For a movement graph, pass a record with optional hash pairs clipSetHash and variableClipSetHash and their 2 variants. Use floatName, floatValue, floatLerp for a float signal and boolName, boolValue for a Boolean signal. Add the suffix 2 for a second signal of either type. Float lerp defaults to -1. Structured parameter names and clip names support up to 127 UTF-8 bytes each. The natives reference lists the arguments and bounds for each call.

Blocked natives

Calling a blocked native raises an error before the game sees the call. The Blocked filter in the natives reference lists the current policy. Three camera and entity calls also enforce resource scope: pass false or 0 for the scope flag documented on destroyCam, destroyAllCams and setEntityAsMissionEntity.

FamilyWhat it coversInstead
Rockstar accounts and commerceMONEY, NETSHOPPING, SOCIALCLUB, APP, SAVEMIGRATIONKeep your economy and profiles on your server, with storage.
Rockstar online sessions and contentLOBBY, LANDINGPAGE, NETWORK_SESSION_*, NETWORK_TRANSITION_*, UGC, remote textures and Rockstar network authority changesLS:MP runs the session: use events and remote calls.
Game script threadsSTART_NEW_SCRIPT, TERMINATE_THREAD, the BRAIN namespaceYour code runs as a resource. To quiet a story script, see suspendStoryScript.
Saves and game flowSave data, STAT_SAVE, RESTART_GAMEStore data with storage.
Rockstar EditorRECORDING, REPLAYNot available to resources.
Raw memory and structuresDATAFILE, raw pointers and game structures without a typed adapterFor entity lists, lsmp.getGamePool. For JSON, your language's own JSON functions.
Shared menus and inputThe game's frontend and pause menu, on-screen keyboard and input layoutUse the LS:MP page and input APIs for your resource UI.
Managed world stateShared weather changes and unchecked clock incrementsUse the documented LS:MP world APIs and checked clock setters.
Replaced by the languageBit helpers and string conversionsYour language's own operators and functions.
luaLua
local ok, err = pcall(startNewScript, "cellphone_flashhand", 1424)
lsmp.log(tostring(ok) .. " " .. tostring(err))   --> false ... not available to scripts
jsJavaScript
try {
  startNewScript('cellphone_flashhand', 1424);
} catch (err) {
  lsmp.log(err.message);   // startNewScript: this native is not available to scripts
}

Any* pointers

An Any* parameter is a pointer whose size no signature gives: nothing tells how much the game will read or write there. A script cannot supply one safely, so every native with an Any* parameter is blocked, whatever you pass. This includes the natives that fill a script array, like getPedNearbyVehicles and getAllVehicles: use lsmp.getGamePool instead.

Coverage

  • About 220 names are not in the current game build. The global exists, does nothing, returns nothing, and never raises.
  • Some natives are not exposed at all, so the global does not exist. The notable gap is the interior room and portal cluster: getInteriorRoomCount, getInteriorPortalCount, getInteriorRoomName and the like. Basic interior lookups are present: isValidInterior, getInteriorFromEntity, getInteriorAtCoords, refreshInterior, and the entity-set natives.
  • One is left out on purpose: the game's WAIT. It only works inside the game's own compiled scripts and cannot pause an LS:MP script. Pause with lsmp.wait.
β„Ή
When a native seems to do nothing

Look it up in the natives reference before debugging your own code. It may not be in this build, it may have refused an argument out of range, or it may be blocked.

βœ•
One native can crash the game

getEntityModel reads the entity's archetype without checking that it exists. On an entity whose archetype is missing, the game goes down on the spot, and doesEntityExist does not protect you. Do not call it on a handle from a shape test or lsmp.raycast. The type natives (isEntityAPed, isEntityAVehicle, isEntityAnObject) read the entity itself and are safe.

Coming from FiveM

βœ“
Same contract

Out-params work the FiveM way, so scripts port easily: GetGroundZFor_3dCoord(x, y, z, water) gives a boolean and a number in FiveM, and getGroundZFor3dCoord(x, y, z, water, 0) gives the same here.

  • LS:MP names are camelCase; FiveM's are PascalCase.
  • There are no _i / _f / _v pointer sentinels and no Citizen.InvokeNative. You never declare an out-param: skip the argument.
  • A BOOL* out-param comes back as a real boolean, where FiveM gives an integer. A hash comes back unsigned.
  • In JavaScript, a vector comes back as an { x, y, z } object, not an array.
  • Parameter lists come from a natives database that sometimes includes parameters FiveM omits: getGroundZFor3dCoord takes a trailing p5, for instance.

Reference

Reference

Conventions (types, errors, units, colors, vectors, hashes, async, subscriptions)

The rules every lsmp function follows: types, errors and failures, absent values, colors, vectors, hashes, units, transportable values, asynchronous calls and subscriptions.

These rules hold for every lsmp function, on the server and on the client, in Lua and in JavaScript. Function pages do not repeat them: they only say what is specific to the function.

Types used in signatures

Signatures use a few names for common values. They are plain numbers, strings or tables: there is no special class to create.

TypeLuaJavaScriptMeaning
playerIdintegernumberA connected player, 0..65534. Valid for one session and reused after the player leaves. See Players.
netIdintegernumberA networked entity, 1..65535, the same number on the server and on every client. Reused after the entity is deleted.
handleintegernumberClient only: the game's own handle of an entity, valid on this client only. Turn a netId into a handle with lsmp.getEntityFromNetId.
dimensionintegernumberA dimension, 0..65535. 0 is the default world. See Dimensions.
vec3 (input)Vector3, {x, y, z} or {x = .., y = .., z = ..}{x, y, z} or [x, y, z]A position or a direction, in meters, always one argument.
Vector3 / Vec3 (output)Vector3{x, y, z}What functions return.
rotation{x, y, z}{x, y, z}Degrees: x = pitch, y = roll, z = yaw.
headingnumbernumberDegrees, yaw only.
hashinteger or stringnumber or stringA 32-bit game hash. A string is hashed with lsmp.hash.
msintegernumberA duration in milliseconds.
epochMsintegernumberA point in time: milliseconds since the Unix epoch (lsmp.nowMs()).
metersnumbernumberA distance.
colorsee Colorssee ColorsA color, read in four forms.
valuesee Transportable valuessee Transportable valuesAny value that can travel between resources, engines and machines.
eventstringstringAn event or RPC name: 1 to 128 bytes of UTF-8, no NUL, case-sensitive. See Reserved names.
namestringstringA resource name (its folder name).
idssequence of integersUint32ArrayA list of netIds that can be large (getEntities, getEntitiesInRadius).
fnfunctionfunctionA function you provide (handler, callback).

A ? after a type (string?, integer?) or | null means the value may be absent: nil in Lua, null in JavaScript.

Errors and failures

A call can go wrong in two ways that never overlap: a programming error raises, a run-time failure returns a failure value.

SituationLuaJavaScript
Programming error: wrong type, missing required argument, a function expected and not givenraises lsmp.fn: <text>TypeError
Value out of its domain: number out of range, unknown name in a fixed list, path leaving the resource, size over a documented limit, reserved nameraises lsmp.fn: <text>RangeError (reserved name: Error)
Run-time failure of a synchronous call: player gone, unknown entity, quota reached, capability refused, object of another resourceaction: false, "code"; read: nil, "code"action: false; read: null; the code with lsmp.getLastError()
Run-time failure of an asynchronous callcb(nil, "code", details?), or nil, "code", details? in a coroutinethe Promise rejects with an Error whose code is the failure code
  • Every message starts with the function name: lsmp.setEntityMeta: arg 2 'key' .... A method says browser:emit: in Lua and browser.emit: in JavaScript.
  • A value that cannot be sent names its path: lsmp.emitServer: args[2].inventory[4].icon: function is not transportable. Indices follow the language: args[1] is the first argument in Lua, args[0] in JavaScript.
  • A refused capability is a failure with the code permission, never an error. The server log gets one warning per resource and capability at most once a minute, naming the capability and where the operator grants it. See Capabilities.
  • Nothing is silently converted: a number is never taken for a string (or the reverse), undefined is never stored as "undefined", a boolean is never a number, a string that is too long is never cut.
  • In an asynchronous JavaScript function, a programming error throws synchronously (at the call); everything else rejects the Promise. In Lua, a programming error raises at the call, before any callback.
  • details (third Lua value, extra fields of the JavaScript Error) only exists where a function says so (MySQL, HTTP, files).
luaLua
local ok, err = lsmp.setEntityOwner(netId, playerId)
if not ok then
  lsmp.warn("cannot give the entity: " .. err) -- "not-found", "permission"...
end
jsJavaScript
if (!lsmp.setEntityOwner(netId, playerId)) {
  lsmp.warn(`cannot give the entity: ${lsmp.getLastError()}`);
}

The codes form a closed list: see Error codes.

Absent values

  • Absent is nil in Lua and null in JavaScript, everywhere: return values, fields of returned tables, event arguments (killerId, oldOwner...). A business value (0 for the default dimension) is never used to mean "absent".
  • A field that is absent from a returned table does not exist in Lua; in JavaScript it is present and null when the shape documents it.
  • "Unknown" and "empty" are told apart by an existence function: lsmp.entityExists, lsmp.playerExists.
  • In JavaScript, undefined and null passed as an argument both mean "absent" (the documented default applies), except where nil has an explicit meaning, such as "nil deletes" for meta and storage.

Booleans

  • Functions and events return real booleans.
  • Arguments and option fields take true or false; nil or absent selects the documented default. A number, a string or a table in place of a boolean is a programming error: 0 is not false.
  • Some sensitive settings have no default and need the boolean explicitly, for example lsmp.setDimensionPopulation(dimension, enabled).

Colors

Every function that takes a color reads it the same way:

FormExampleMeaning
number 0xRRGGBB0xFF0000Opaque. A number above 0xFFFFFF is an error (use one of the forms below for transparency).
named fields{ r = 255, g = 0, b = 0, a = 128 }Integers 0..255; a defaults to 255.
list{255, 0, 0} / [255, 0, 0, 128]Same, in order r, g, b, a.
string"#ff0000", "#ff000080"Hexadecimal, case-insensitive.

Colors are returned as "#rrggbb" when opaque, otherwise "#rrggbbaa".

Vectors and rotations

  • A position is always one argument, never three numbers: Lua Vector3, {x, y, z} or {x = .., y = .., z = ..}; JavaScript {x, y, z} or [x, y, z]. A component that is not a finite number is an error.
  • Functions return a Vector3 in Lua and a plain {x, y, z} object in JavaScript.
  • Screen points use {x, y} (Lua table {x = .., y = ..}).
  • A rotation is {x, y, z} in degrees: x = pitch, y = roll, z = yaw, in the game's usual rotation order. Where only the facing matters, functions take a heading (degrees).
luaLua
local pos = lsmp.getEntityCoords(netId)       -- Vector3
local car = lsmp.createEntity("vehicle", "adder", pos, { heading = 90.0 })
lsmp.createEntity("object", "prop_barrier_work05", { x = 10, y = 20, z = 30 })
jsJavaScript
const pos = lsmp.getEntityCoords(netId);       // { x, y, z }
const car = lsmp.createEntity("vehicle", "adder", pos, { heading: 90 });
lsmp.createEntity("object", "prop_barrier_work05", [10, 20, 30]);

Hashes

  • Hashes are unsigned 32-bit integers everywhere, game natives included: lsmp.getEntityModel(car) == lsmp.hash("adder").
  • As input, a hash may be an integer in -2^31 .. 2^32-1 (signed or unsigned form of the same bits) or a string, which is hashed with lsmp.hash (ASCII letters are lower-cased first). Anything else is an error.

Units

QuantityUnitNaming
durationmilliseconds, integersuffix Ms: timeoutMs, transitionMs, durationMs, lifetimeMs
point in timemilliseconds since the Unix epochsuffix Ms: untilMs, atMs, mtimeMs, purchasedAtMs
distancemetersexplicit name, no suffix: radius, range, maxRadius
angledegreesheading, rotation, fov
screen positionnormalized 0..1except functions whose name contains Pixel

There are no seconds or days in the API. server.cfg keys follow their own naming (see server.cfg).

Transportable values

Event arguments, RPC arguments and results, meta values and stored values all use the same rules. A value is copied when it crosses a resource, an engine or the network: consider it copied, never shared.

LuaJavaScriptTravels as
nil (argument), lsmp.nullundefined, nullnothing (absent)
booleanbooleanboolean
integerinteger number within Β±(2^53-1), bigint within 64 bitsinteger
float (even 3.0)any other number (NaN, Infinity included)float
string (valid UTF-8)stringstring
non-UTF-8 string, or lsmp.bytes(s)Uint8Array, Buffer, ArrayBuffer, DataViewbytes
Vector3object whose only own keys are numeric x, y, zvector
sequence with keys exactly 1..n; an empty tableArray (holes become null)list
table whose keys are all stringsplain object (own string keys)map

Received values become: integers within Β±(2^53-1) a JavaScript number, larger ones a bigint; bytes a Lua string or a JavaScript Uint8Array; a vector a Lua Vector3 or a JavaScript {x, y, z}.

Not transportable (the call raises before anything is sent): functions, coroutines, userdata, handles, Lua tables with mixed or non-string keys or holes, Vector2/Vector4/Quaternion (send {x = .., y = ..}), JavaScript Map, Set, Date, RegExp, Promise, Error, class instances, symbols, typed arrays other than Uint8Array (wrap them: new Uint8Array(x.buffer, x.byteOffset, x.byteLength)), strings with a lone surrogate, nesting deeper than 32 levels.

⚠
Good to know

- An empty Lua table travels as a list: a JavaScript {} sent to Lua and back returns [].
- A map entry whose value is absent disappears in Lua ({ a = nil } has no key a). Inside a list, an absent element arrives as lsmp.null in Lua so the length is kept.
- A JavaScript object with only numeric x, y, z keys becomes a Vector3 in Lua. To send a business object with these keys, add another key.
- Lua floats are 32-bit: a vector sent from JavaScript to Lua loses precision beyond about 7 digits.
- The order of keys of a map built in Lua is not fixed.

Size limits (per direction, per meta value, per stored value) are in Limits and quotas.

Asynchronous functions

Functions that wait for the disk, the database, the network or another machine are asynchronous. Their pages say so.

JavaScript: Promises

An asynchronous function returns a Promise. It resolves with the result, or rejects with an Error whose message is "lsmp.fn: <code>: <detail>" and whose code is one of the error codes. When an operation has a job id, it is exposed as promise.jobId.

Lua: callback or coroutine

  • Callback: pass a function as the last argument, after the declared parameters (lsmp.fs.readFile(path, cb) and lsmp.fs.readFile(path, opts, cb) both work). It is called later, never during the call, exactly once, with cb(result, nil) on success and cb(nil, "code", details) on failure (false instead of nil when the normal result is a boolean). An error raised inside the callback is logged and goes no further.
  • Coroutine: without a callback, inside a host coroutine, the call suspends and returns result, err, details. The rest of the server keeps running.
  • Without a callback outside a host coroutine, the call raises lsmp.fn: needs a callback here (not inside a coroutine).
  • Host coroutines are: the body of every script file, every handler of lsmp.on, lsmp.once, lsmp.onServer, lsmp.onClient and lsmp.onCall, playerPreConnection handlers, and every lsmp.createThread function. A suspended handler blocks neither the next event nor the other handlers. When the resource stops, its pending waits end with cancelled.
  • lsmp.onTick handlers, and functions called by Lua itself (a table.sort comparator, a metamethod), cannot suspend.
luaLua
-- Coroutine form: inside an event handler
lsmp.on("resourceStart", function(name)
  if name ~= lsmp.getResourceName() then return end
  local text, err = lsmp.fs.readFile(lsmp.getDataPath() .. "/motd.txt")
  if text then lsmp.log(text) else lsmp.warn("no motd: " .. err) end
end)

-- Callback form: works anywhere
lsmp.storage.flush(function(ok, err)
  if not ok then lsmp.warn("flush failed: " .. err) end
end)
jsJavaScript
lsmp.on("resourceStart", async (name) => {
  if (name !== lsmp.getResourceName()) return;
  try {
    const text = await lsmp.fs.readFile(lsmp.getDataPath() + "/motd.txt");
    lsmp.log(text);
  } catch (e) {
    lsmp.warn(`no motd: ${e.code}`);
  }
});

Subscriptions

  • lsmp.on, once, onServer, onClient, onCall, onTick, registerCommand, browser:on and lsmp.http.serve return an unsubscribe function off(), which returns true if it removed something. Each also has a symmetric off* function (off, offServer, offClient, offCall, offTick, unregisterCommand, browser:off).
  • The same (name, fn) pair registered twice is registered once; the second call returns the same off.
  • A handler that raises is isolated and logged as [resource] lsmp: handler of '<name>' raised: ...; the other handlers still run. It stays registered (only onTick handlers are disabled after 8 consecutive errors).
  • Adding or removing a handler during a dispatch takes effect at the next dispatch.
  • Everything a resource registered is removed when it stops.
  • Handlers of one event run in registration order (resources in load order). When both engines of a side listen, JavaScript handlers run before Lua handlers. In JavaScript, this is undefined in every handler.
luaLua
local off = lsmp.on("playerJoin", function(playerId, name)
  lsmp.log(name .. " joined")
end)
-- later
off()
jsJavaScript
const off = lsmp.on("playerJoin", (playerId, name) => {
  lsmp.log(`${name} joined`);
});
// later
off();

Handles

  • Objects returned by createBrowser, createScene, lsmp.mysql.createPool... are handles: call their methods with obj:m() in Lua and obj.m() in JavaScript. Their id field, when they have one, is read-only.
  • A method of a destroyed handle does nothing and returns false or nil; isValid() returns false. It never raises.
  • Handles belong to the resource that created them and cannot be sent to another resource (they are not transportable). Passing the id of another resource's object fails with permission.
  • Game identifiers (client entity handles, netIds, playerIds) stay integers.

Isolation and restore

  • Objects: a resource only acts on what it created. Browsers, scenes, outlines, captures, MySQL pools, voice channels, HTTP routes, commands, handlers and timers belong to their resource and are destroyed when it stops. Acting on another resource's object fails with permission.
  • Server entities: the entities and pickups a resource creates belong to it. Acting on others needs the entities.foreign capability. When the resource stops, its entities and pickups are deleted (except lifePolicy = "keep") and its synchronized scenes stop.
  • Global settings that a resource changes are restored when it stops: the last writer wins, and when it stops the value of the previous writer comes back (or the engine default). This covers the synchronized weather on the server, and on the client the voice settings, nametag styles, Discord presence, local weather, auto spawn, HUD money and player blips, picking and outlines.
  • Not restored: the whitelist, bans, permissions and groups, meta, storage, and dimension settings (population, client entities). They are data or operator policy.
  • The log level, memory and time budgets are per resource.

Reserved names

  • Engine event names (see Engine events) can be listened to with lsmp.on, but emit, emitServer, emitClient, emitAllClients, emitDimensionClients, onServer, onClient, onCall and browser:emit with these names raise Error (lsmp.emit: 'playerDeath' is an engine event).
  • The prefix lsmp: is reserved for event names, RPC names and meta keys (storage keys are not concerned).
  • Browser lifecycle names (load, loadError, focusLost, crash) are reserved on a browser handle: a page cannot emit them.
  • Built-in console commands (help, status, players, resources, kick, say, quit on the server) cannot be registered by a script.
  • Meta keys starting with lsmp: read as absent and raise on write.

Lists, identifiers and seats

  • Lists are Lua sequences {...} and JavaScript arrays. Lists of netIds that can be large are a Uint32Array in JavaScript (getEntities, getEntitiesInRadius).
  • Lists of pairs are lists of objects: { seat, ped }, { playerId, role }.
  • Seats: 0 is the driver, 1 and up are passengers, everywhere.
  • Entity types are strings: "vehicle", "ped", "object", "playerPed" (lsmp.EntityType).
  • Identifiers are strict integers: a numeric string is not a playerId. Out-of-range identifiers are errors.

Lua and JavaScript differences

The API is the same in both languages. These differences are deliberate, and are the only ones:

SubjectLuaJavaScript
method callobj:m()obj.m()
asynchronous callfinal callback or coroutine, result, errPromise
reason of a synchronous failuresecond return value "code"lsmp.getLastError()
vector returnedVector3{x, y, z}
bytesstring (send binary explicitly with lsmp.bytes(s))Uint8Array
explicit null in a list, JSON or SQLlsmp.nullnull
JSONlsmp.json.encode/decode/arrayJSON
threadlsmp.createThread(fn, ...)async function
printprint = lsmp.logconsole.* routed to lsmp.log/warn/error/debug
timersinteger idsclient: integer ids; server: Node Timeout objects
integers beyond 2^5364-bit Lua integersBigInt
indices in error pathsfrom 1 (args[1] = first argument)from 0 (args[0])

lsmp.null

SharedLua
luaLua
lsmp.null

Lua only: an explicit null. It stands for JSON null, SQL NULL and an absent element inside a list.

Test it with v == lsmp.null (it is not falsy). Received lists keep their length with it: {1, lsmp.null, 3}. In a map, an absent value is simply a missing key. JavaScript uses null.

Not available in JavaScript.

Reference

Engine events (table)

Every event LS:MP fires for your scripts: when it fires, on which side, with which arguments, and what is guaranteed.

Engine events tell your scripts what happens in the game and on the server: a player joins, an entity changes owner, a resource stops. Listen to them with lsmp.on like any local event. Their names are reserved: a script can listen to them but never emit them.

One fact has the same name and the same arguments on the server and on the client. When an event exists on both sides, the table says "server, client".

luaLua
lsmp.on("playerJoin", function(playerId, name)
  lsmp.log(name .. " joined as player " .. playerId)
end)
jsJavaScript
lsmp.on("playerJoin", (playerId, name) => {
  lsmp.log(`${name} joined as player ${playerId}`);
});

Guarantees

Unless an event says otherwise, these rules hold for every engine event:

  • Asynchronous: an engine event is never delivered inside the lsmp call that caused it. lsmp.setPlayerDimension returns first, then playerDimensionChange arrives.
  • Both engines of the side receive it: JavaScript handlers first, then Lua handlers, each in registration order (resources in load order).
  • Order: two events coming from the same part of the engine arrive in the order they happened. There is no order between unrelated parts (voice and dimensions, for example).
  • Types: real booleans, nil/null for absent values, unsigned hashes, vectors (Vector3 in Lua, {x, y, z} in JavaScript), strings for reasons and kinds.
  • No replay: a resource that starts does not receive past events. Read the current state instead: lsmp.getPlayers(), lsmp.getResources(), lsmp.weather.get()...
  • A handler may suspend (Lua coroutine, async function) without delaying the other handlers.

All engine events

EventSidesArgumentsWhen
resourceStartserver, clientnameAfter a resource's entry scripts (and module-level awaits) completed.
resourceStopserver, clientnameBefore a resource is torn down: its own handlers run first, then other resources'.
serverStartserverβ€”Once, after every resource of the boot set has started and the game port listens.
serverStopserverβ€”On graceful shutdown (console quit, admin panel restart/stop, update, SIGTERM/CTRL+C): after playerLeave(..., "shutdown") for every player, before resources stop.
playerPreConnectionserverpWhen an admitted client asks to join, before any slot is given.
playerJoinserver, clientplayerId, nameServer: the player has a slot and is in the session (after admission).
playerLeaveserver, clientplayerId, name, reason, detail, clientThe player left the session.
playerSpawnserver, clientplayerId, position, heading, model, firstClient: the local player spawned (lsmp.spawn, auto spawn, respawn).
playerDeathserver, clientplayerId, killerId, weaponHash, position, flags, killerEntityServer: the victim's client reported its death (deduplicated, rate-limited, killer resolved by the server).
playerDimensionChangeserver, clientplayerId, oldDimension, newDimensionA player changed dimension.
entityDimensionChangeservernetId, oldDimension, newDimensionAn entity changed dimension.
entityOwnerChangeservernetId, oldOwner, newOwner, reasonSimulation of an entity moved.
entityAdoptclientnetIdThe local client starts simulating an entity.
entityReleaseclientnetIdThe local client stops simulating an entity.
entityStreamInclientnetId, entityA networked entity got a game instance here.
entityStreamOutclientnetIdA networked entity lost its game instance here (its handle is already invalid).
voiceStartserver, clientplayerIdA player starts transmitting.
voiceStopserver, clientplayerIdA player stops transmitting.
pickupCollectserverplayerId, netId, pickupHash, amount, serverCreatedThe server granted a pickup to a player.
playerPermsChangeserver, clientplayerIdServer: a player's effective permissions changed.
weatherChangeserver, clienttype, previous, transitionMsThe target synchronized weather type changed (client: also when a local override starts/ends).
benefitGrantserverlsmpId, benefitA connected account has a benefit to apply (once per session until consumed).
benefitRevokeserverlsmpId, benefitA benefit was revoked and must be taken back.
metaChangeserver, clientscope, target, key, value, source, clientA script-visible meta value changed (server: any writer; client: replicated change received, own writes included).
selectionChangecliententity, geomKey, validThe picked entity/geometry changed.
syncSceneStartclientsceneId, netIdAn entity of the session starts a synchronized scene.
syncSceneStopclientsceneId, netIdIt stops.
serverMessageclienttextThe server console ran say.
browser:loadclienturlThe page (main frame) finished loading.
browser:loadErrorclienturl, codeNavigation failed or the URL was refused.
browser:focusLostclientβ€”The player took focus back (escape hatch) or another page took it.
browser:crashclientreasonThe page renderer crashed.

Resources and server

resourceStart

SharedLua Β· JS
luaLua
lsmp.on("resourceStart", function(name) end)
jsJavaScript
lsmp.on("resourceStart", (name) => {})

A resource has just reached the "started" state.

Fired after the resource's entry scripts ran (and, in JavaScript, after their module-level awaits completed). The resource receives its own resourceStart too: handlers it registered while loading are called. This is the usual place to initialize.

A resource that starts later only sees later starts; use lsmp.getResources() for the current set.

Parameters
ParameterTypeDescription
namenameThe resource that started.
Example
luaLua
lsmp.on("resourceStart", function(name)
  if name == lsmp.getResourceName() then
    lsmp.log("ready")
  end
end)
jsJavaScript
lsmp.on("resourceStart", (name) => {
  if (name === lsmp.getResourceName()) lsmp.log("ready");
});

resourceStop

SharedLua Β· JS
luaLua
lsmp.on("resourceStop", function(name) end)
jsJavaScript
lsmp.on("resourceStop", (name) => {})

A resource is about to stop.

The stopping resource's own handlers run first, then those of the other resources. During the dispatch, the stopping resource's objects (entities, browsers, storage, MySQL pools) are still alive: save what you need here.

Handlers may suspend or await, for up to ResourceStopGraceMs on the server (default 2000 ms) and 1000 ms on the client. Then the resource is torn down anyway.

Parameters
ParameterTypeDescription
namenameThe resource that stops.
Example
luaLua
lsmp.on("resourceStop", function(name)
  if name ~= lsmp.getResourceName() then return end
  lsmp.storage.set("lastStop", lsmp.nowMs())
  lsmp.storage.flush() -- suspends until the store is on disk
end)
jsJavaScript
lsmp.on("resourceStop", async (name) => {
  if (name !== lsmp.getResourceName()) return;
  lsmp.storage.set("lastStop", lsmp.nowMs());
  await lsmp.storage.flush();
});

serverStart

ServerLua Β· JS
luaLua
lsmp.on("serverStart", function() end)
jsJavaScript
lsmp.on("serverStart", () => {})

Once, when every resource has started (or failed) and the game port listens.

Every resource receives it: on the server, resources start only with the server.

serverStop

ServerLua Β· JS
luaLua
lsmp.on("serverStop", function() end)
jsJavaScript
lsmp.on("serverStop", () => {})

The server is shutting down gracefully.

Fired on console quit, a stop or restart from the admin panel, an update, or a termination signal (CTRL+C). It comes after playerLeave(..., "shutdown") for every player, before the resources stop.

Handlers may suspend or await: the server waits until they all finish, or until ShutdownGraceMs (default 5000 ms). MySQL queries started before or during this time complete; storage stores are flushed afterwards. It is not fired when the server crashes.

Players

playerPreConnection

ServerLua Β· JS
luaLua
lsmp.on("playerPreConnection", function(p) end)
jsJavaScript
lsmp.on("playerPreConnection", (p) => {})

A player asks to join, before getting a slot. Your handlers can refuse them.

This is the only engine event whose outcome depends on the handlers:

- Every handler of every resource runs. Any p.deny(reason) refuses the player; the reason (256 bytes at most) is shown to them.
- A handler answers when it returns (Lua: when its coroutine ends; JavaScript: when the Promise it returns settles). Returning without denying means no objection. A handler can therefore wait for a database before deciding.
- A handler that raises or rejects counts as no objection (and is logged).
- The verdict is given when all handlers answered, or after PreConnectionTimeoutMs (default 10000 ms). Late handlers then refuse the player ("server check timed out"), and the log names them.

Parameters
ParameterTypeDescription
pPreConnectionThe connecting player (fields below). JavaScript: a frozen object.
FieldTypeDescription
lsmpIdinteger?LS:MP account; nil/null for a guest.
namestringThe name the player connects with.
verifiedbooleantrue when the server verified the account with LS:MP.
guestbooleantrue for a player without an account.
ipstring?IP address. nil/null unless the resource holds the players.identity capability.
hwidstring?Hardware identifier. Same rule as ip.
deny(reason)functionRefuses the connection. In Lua, call it as p.deny(reason) (no colon).
Example
luaLua
lsmp.on("playerPreConnection", function(p)
  if p.guest then
    p.deny("This server needs an LS:MP account.")
    return
  end
  local banned = lsmp.storage.get("ban:" .. p.lsmpId)
  if banned then p.deny("You are banned: " .. banned) end
end)
jsJavaScript
lsmp.on("playerPreConnection", async (p) => {
  if (p.guest) return p.deny("This server needs an LS:MP account.");
  const banned = lsmp.storage.get(`ban:${p.lsmpId}`);
  if (banned) p.deny(`You are banned: ${banned}`);
});

playerJoin

SharedLua Β· JS
luaLua
lsmp.on("playerJoin", function(playerId, name) end)
jsJavaScript
lsmp.on("playerJoin", (playerId, name) => {})

A player is in the session.

Server: the player was admitted and has a slot. Client: another player appears in the local session. It is not fired for the local player: at resource start, read lsmp.getLocalPlayer() and lsmp.getPlayers(), which also lists the players already present (they are not announced).

Parameters
ParameterTypeDescription
playerIdplayerIdThe new player.
namestringTheir name.

playerLeave

SharedLua Β· JS
luaLua
lsmp.on("playerLeave", function(playerId, name, reason, detail, client) end)
jsJavaScript
lsmp.on("playerLeave", (playerId, name, reason, detail, client) => {})

A player left the session.

During the dispatch the leaving player is still readable: getPlayerName, getPlayerLsmpId, isPlayerGuest, getPlayerDimension, getPlayerMeta and getPlayerIdentifier(s) answer as just before the departure. playerExists already returns false, and writes to the player (setPlayerMeta, emitClient, callClient...) return false. The playerId is given to a new player only after every handler ran. Pending callClient calls to the player fail with disconnected.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player who left.
namestringTheir name.
reasonstring"quit", "kick", "ban", "timeout", "shutdown" or "error" (lsmp.LeaveReason).
detailstring?Server: the text given to the kick, the ban or the client's disconnect, if any. Always nil/null on the client.
Example
luaLua
lsmp.on("playerLeave", function(playerId, name, reason, detail)
  local money = lsmp.getPlayerMeta(playerId, "money") -- still readable here
  local account = lsmp.getPlayerLsmpId(playerId)
  if account and money then lsmp.storage.set("money:" .. account, money) end
  lsmp.log(name .. " left (" .. reason .. ")")
end)
jsJavaScript
lsmp.on("playerLeave", (playerId, name, reason, detail) => {
  const money = lsmp.getPlayerMeta(playerId, "money"); // still readable here
  const account = lsmp.getPlayerLsmpId(playerId);
  if (account !== null && money !== null) lsmp.storage.set(`money:${account}`, money);
  lsmp.log(`${name} left (${reason})`);
});

playerSpawn

SharedLua Β· JS
luaLua
lsmp.on("playerSpawn", function(playerId, position, heading, model, first) end)
jsJavaScript
lsmp.on("playerSpawn", (playerId, position, heading, model, first) => {})

A player spawned.

Client: the local player spawned (lsmp.spawn, automatic spawn, respawn); only the local player. Server: the client reported its spawn. On the server this is what the client declares: use it for information, not for trust.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
positionVector3Spawn position.
headingheadingSpawn heading, in degrees.
modelhashPed model (unsigned).
firstbooleantrue for the first spawn of the session.

playerDeath

SharedLua Β· JS
luaLua
lsmp.on("playerDeath", function(playerId, killerId, weaponHash, position, flags, killerEntity) end)
jsJavaScript
lsmp.on("playerDeath", (playerId, killerId, weaponHash, position, flags, killerEntity) => {})

A player died.

Server: the victim's client reported its death; duplicates are dropped and the killer is resolved by the server. Client: the server relays it to every client.

Parameters
ParameterTypeDescription
playerIdplayerIdThe victim.
killerIdplayerId?The killing player; nil/null when not killed by a player.
weaponHashhashWeapon (unsigned); 0 if unknown.
positionVector3Where the victim died.
flagsintegerBits of lsmp.DeathFlag (Headshot = 1).
killerEntitynetId?The entity that killed (ped, vehicle); nil/null for the environment.
Example
luaLua
lsmp.on("playerDeath", function(victim, killerId, weaponHash, position, flags)
  if killerId then
    local headshot = (flags & lsmp.DeathFlag.Headshot) ~= 0
    lsmp.log(lsmp.getPlayerName(killerId) .. " killed " .. lsmp.getPlayerName(victim) .. (headshot and " (headshot)" or ""))
  end
end)
jsJavaScript
lsmp.on("playerDeath", (victim, killerId, weaponHash, position, flags) => {
  if (killerId === null) return;
  const headshot = (flags & lsmp.DeathFlag.Headshot) !== 0;
  lsmp.log(`${lsmp.getPlayerName(killerId)} killed ${lsmp.getPlayerName(victim)}${headshot ? " (headshot)" : ""}`);
});

playerDimensionChange

SharedLua Β· JS
luaLua
lsmp.on("playerDimensionChange", function(playerId, oldDimension, newDimension) end)
jsJavaScript
lsmp.on("playerDimensionChange", (playerId, oldDimension, newDimension) => {})

A player changed dimension.

Client: local player only. See Dimensions.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.
oldDimensiondimensionBefore.
newDimensiondimensionAfter.

playerPermsChange

SharedLua Β· JS
luaLua
lsmp.on("playerPermsChange", function(playerId) end)
jsJavaScript
lsmp.on("playerPermsChange", (playerId) => {})

A player's permissions changed.

Server: the effective permissions of a player changed. Client: the local permission snapshot changed (lsmp.perms.isReady and isComplete give its state). See Permissions.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.

Entities

entityDimensionChange

ServerLua Β· JS
luaLua
lsmp.on("entityDimensionChange", function(netId, oldDimension, newDimension) end)
jsJavaScript
lsmp.on("entityDimensionChange", (netId, oldDimension, newDimension) => {})

An entity changed dimension.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
oldDimensiondimensionBefore.
newDimensiondimensionAfter.

entityOwnerChange

ServerLua Β· JS
luaLua
lsmp.on("entityOwnerChange", function(netId, oldOwner, newOwner, reason) end)
jsJavaScript
lsmp.on("entityOwnerChange", (netId, oldOwner, newOwner, reason) => {})

The player simulating an entity changed.

See Ownership and AI intents.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
oldOwnerplayerId?Previous owner; nil/null if it was orphan.
newOwnerplayerId?New owner; nil/null if it becomes orphan.
reasonstringOne of lsmp.OwnerChangeReason: "adopt", "migrate", "leaseExpired", "disconnect", "demand", "script", "release".

entityAdopt

ClientLua Β· JS
luaLua
lsmp.on("entityAdopt", function(netId) end)
jsJavaScript
lsmp.on("entityAdopt", (netId) => {})

The local client starts simulating an entity.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.

entityRelease

ClientLua Β· JS
luaLua
lsmp.on("entityRelease", function(netId) end)
jsJavaScript
lsmp.on("entityRelease", (netId) => {})

The local client stops simulating an entity.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.

entityStreamIn

ClientLua Β· JS
luaLua
lsmp.on("entityStreamIn", function(netId, entity) end)
jsJavaScript
lsmp.on("entityStreamIn", (netId, entity) => {})

A networked entity got a game instance on this client.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.
entityhandleIts game handle, valid during the dispatch (it can disappear later).

entityStreamOut

ClientLua Β· JS
luaLua
lsmp.on("entityStreamOut", function(netId) end)
jsJavaScript
lsmp.on("entityStreamOut", (netId) => {})

A networked entity lost its game instance on this client.

Its handle is already invalid when the event arrives.

Parameters
ParameterTypeDescription
netIdnetIdThe entity.

pickupCollect

ServerLua Β· JS
luaLua
lsmp.on("pickupCollect", function(playerId, netId, pickupHash, amount, serverCreated) end)
jsJavaScript
lsmp.on("pickupCollect", (playerId, netId, pickupHash, amount, serverCreated) => {})

The server granted a pickup to a player.

Parameters
ParameterTypeDescription
playerIdplayerIdThe collector.
netIdnetIdThe pickup.
pickupHashhashPickup type (unsigned).
amountintegerAmount granted.
serverCreatedbooleantrue for a pickup created by lsmp.createPickup; false for one dropped by the game on a client, whose amount is what the client declares.

syncSceneStart

ClientLua Β· JS
luaLua
lsmp.on("syncSceneStart", function(sceneId, netId) end)
jsJavaScript
lsmp.on("syncSceneStart", (sceneId, netId) => {})

An entity of the session starts a synchronized scene.

See Synchronized scenes.

Parameters
ParameterTypeDescription
sceneIdintegerThe scene.
netIdnetIdThe participating entity.

syncSceneStop

ClientLua Β· JS
luaLua
lsmp.on("syncSceneStop", function(sceneId, netId) end)
jsJavaScript
lsmp.on("syncSceneStop", (sceneId, netId) => {})

An entity stops playing a synchronized scene.

Parameters
ParameterTypeDescription
sceneIdintegerThe scene.
netIdnetIdThe participating entity.

selectionChange

ClientLua Β· JS
luaLua
lsmp.on("selectionChange", function(entity, geomKey, valid) end)
jsJavaScript
lsmp.on("selectionChange", (entity, geomKey, valid) => {})

The picked entity or geometry changed.

See Outlines and picking.

Parameters
ParameterTypeDescription
entityhandle?The picked entity; nil/null if none.
geomKeyinteger?The picked geometry, if any.
validbooleanWhether the selection is valid.

Meta

metaChange

SharedLua Β· JS
luaLua
lsmp.on("metaChange", function(scope, target, key, value, source) end)
jsJavaScript
lsmp.on("metaChange", (scope, target, key, value, source) => {})

A meta value changed.

Server: any write, by a script or by a client. Client: a replicated change was received, the client's own writes included. A write with the same value as before does not fire.

Pass a filter as third argument of lsmp.on to receive only what you need: the engine does not even decode the value for handlers whose filter does not match. Fields present in the filter must match; a mistyped field raises. See Meta.

Parameters
ParameterTypeDescription
scopestring"global", "player" or "entity".
targetinteger?The playerId or netId; nil/null for a global value.
keystringThe key.
valuevalue?The new value; nil/null when it was deleted.
sourceplayerId?Server: the player who wrote it, nil/null when a server script wrote it. Always nil/null on the client, which does not know the writer.
Filter fieldTypeMatches
scopestring"global", "player" or "entity".
keystringOne key.
targetintegerOne playerId or netId.
Example
luaLua
lsmp.on("metaChange", function(scope, target, key, value, source)
  lsmp.log("player " .. target .. " has " .. tostring(value) .. " money")
end, { scope = "player", key = "money" })
jsJavaScript
lsmp.on("metaChange", (scope, target, key, value, source) => {
  lsmp.log(`player ${target} has ${value} money`);
}, { scope: "player", key: "money" });

Voice, weather, benefits

voiceStart

SharedLua Β· JS
luaLua
lsmp.on("voiceStart", function(playerId) end)
jsJavaScript
lsmp.on("voiceStart", (playerId) => {})

A player starts transmitting voice.

See Voice.

Parameters
ParameterTypeDescription
playerIdplayerIdThe talking player.

voiceStop

SharedLua Β· JS
luaLua
lsmp.on("voiceStop", function(playerId) end)
jsJavaScript
lsmp.on("voiceStop", (playerId) => {})

A player stops transmitting voice.

Parameters
ParameterTypeDescription
playerIdplayerIdThe player.

weatherChange

SharedLua Β· JS
luaLua
lsmp.on("weatherChange", function(type, previous, transitionMs) end)
jsJavaScript
lsmp.on("weatherChange", (type, previous, transitionMs) => {})

The target synchronized weather changed.

On the client it also fires when a local override starts or ends. See Weather and time.

Parameters
ParameterTypeDescription
typestringThe new weather type.
previousstring?The previous type; nil/null if unchanged.
transitionMsmsDuration of the transition.

benefitGrant

ServerLua Β· JS
luaLua
lsmp.on("benefitGrant", function(lsmpId, benefit) end)
jsJavaScript
lsmp.on("benefitGrant", (lsmpId, benefit) => {})

A connected account has an in-game benefit to apply.

Fired once per session until the benefit is consumed. Delivered only to resources holding the benefits.read capability. See In-game benefits.

Parameters
ParameterTypeDescription
lsmpIdintegerThe account.
benefitBenefit{ id, key, quantity, purchasedAtMs, status }.

benefitRevoke

ServerLua Β· JS
luaLua
lsmp.on("benefitRevoke", function(lsmpId, benefit) end)
jsJavaScript
lsmp.on("benefitRevoke", (lsmpId, benefit) => {})

A benefit was revoked and must be taken back.

Delivered only to resources holding benefits.read.

Parameters
ParameterTypeDescription
lsmpIdintegerThe account.
benefitBenefit{ id, key, quantity, purchasedAtMs, status }.

serverMessage

ClientLua Β· JS
luaLua
lsmp.on("serverMessage", function(text) end)
jsJavaScript
lsmp.on("serverMessage", (text) => {})

The server console ran say.

When no client resource listens to it, LS:MP shows the text in its notification feed.

Parameters
ParameterTypeDescription
textstringThe message.

Browser events

These four events are received on a browser handle with browser:on (Lua) or browser.on (JavaScript), not with lsmp.on. Only that handle receives them, and a page cannot emit them. See Browsers.

browser:load

ClientLua Β· JS
luaLua
browser:on("load", function(url) end)
jsJavaScript
browser.on("load", (url) => {})

The page (main frame) finished loading.

Events emitted to the page before this point are delivered right after it.

Parameters
ParameterTypeDescription
urlstringThe loaded address.

browser:loadError

ClientLua Β· JS
luaLua
browser:on("loadError", function(url, code) end)
jsJavaScript
browser.on("loadError", (url, code) => {})

Navigation failed or the address was refused.

Parameters
ParameterTypeDescription
urlstringThe address.
codestring"refused-url", "network", "http-<status>" or "aborted".

browser:focusLost

ClientLua Β· JS
luaLua
browser:on("focusLost", function() end)
jsJavaScript
browser.on("focusLost", () => {})

The player took the focus back, or another page took it (2D browsers).

browser:crash

ClientLua Β· JS
luaLua
browser:on("crash", function(reason) end)
jsJavaScript
browser.on("crash", (reason) => {})

The page renderer crashed.

The browser stays valid: setUrl loads it again.

Parameters
ParameterTypeDescription
reasonstringWhat happened.

Constants

lsmp.LeaveReason

SharedLua Β· JS
luaLua
lsmp.LeaveReason
jsJavaScript
lsmp.LeaveReason

The reason values of playerLeave.

lsmp.LeaveReason.Quit = "quit" Β· lsmp.LeaveReason.Kick = "kick" Β· lsmp.LeaveReason.Ban = "ban" Β· lsmp.LeaveReason.Timeout = "timeout" Β· lsmp.LeaveReason.Shutdown = "shutdown" Β· lsmp.LeaveReason.Error = "error"

lsmp.DeathFlag

SharedLua Β· JS
luaLua
lsmp.DeathFlag
jsJavaScript
lsmp.DeathFlag

Bits of the flags argument of playerDeath.

lsmp.DeathFlag.Headshot = 1

Reference

Error codes

The closed list of run-time failure codes, what each one means and what usually causes it.

When a call fails at run time (the player left, the file is missing, the quota is reached), it does not raise: it returns a failure, and the failure carries one of the codes below. The list is closed: no function invents its own code. Programming errors (wrong types, out-of-range values) raise instead; see Errors and failures.

Reading the code

CallLuaJavaScript
synchronous actionlocal ok, code = lsmp.fn(...)if (!lsmp.fn(...)) code = lsmp.getLastError()
synchronous readlocal v, code = lsmp.fn(...)if (lsmp.fn(...) === null) code = lsmp.getLastError()
asynchronous, callbacklsmp.fn(..., function(result, code, details) end)β€”
asynchronous, coroutinelocal result, code, details = lsmp.fn(...)try { await lsmp.fn(...) } catch (e) { e.code }
luaLua
-- server
lsmp.onCall("bank:balance", function(source)
  local account = lsmp.getPlayerLsmpId(source)
  if not account then return nil end
  return lsmp.storage.get("balance:" .. account) or 0
end)

-- client, in a host coroutine
local balance, code = lsmp.callServer("bank:balance")
if code == lsmp.ErrorCode.NoHandler then
  lsmp.warn("the bank resource is not running")
end
jsJavaScript
// server
lsmp.onCall("bank:balance", (source) => {
  const account = lsmp.getPlayerLsmpId(source);
  if (account === null) return null;
  return lsmp.storage.get(`balance:${account}`) ?? 0;
});

// client
async function readBalance() {
  try {
    return await lsmp.callServer("bank:balance");
  } catch (e) {
    if (e.code === lsmp.ErrorCode.NoHandler) lsmp.warn("the bank resource is not running");
    return null;
  }
}

The codes

Codelsmp.ErrorCodeMeaningTypical causes
not-foundNotFoundThe target does not exist.Unknown player, entity, resource, scene, file or product; callClient to a player who is not connected.
timeoutTimeoutNo answer within the deadline.An RPC handler slower than timeoutMs; an HTTP request or a MySQL query over its timeout; playerPreConnection handlers too slow.
no-handlerNoHandlerNobody handles that name on the other side.A call (call, callServer, callClient) to a name without onCall on the side it reaches (resource not started, typo, wrong side); a page call without a handler.
errorErrorThe operation failed on the other end.The remote RPC handler raised or returned a value that cannot be sent; SQL error; a resource failed to start; invalid JSON in an HTTP response read as json. The details stay in the other side's log; a client never receives a server error message.
permissionPermissionNot allowed.A capability refused to the resource, a sandbox rule, an object or entity that belongs to another resource, a client meta write on an entity it does not own.
limitLimitA quota, size, rate or count limit is reached.Too many pending RPC calls, a resource storage that is full, too many entities, a file too large, a rate limit. See Limits and quotas.
disconnectedDisconnectedNot in a session, or the player left.Client call while not connected; the player left before answering a callClient.
invalidInvalidRefused by the current state.Entity and player in different dimensions, a stale cursor, an empty cart, a directory where a file was expected, conflicting options.
unavailableUnavailableThe service is off or not ready.LS:MP network services disabled on the server, renderer not ready, store disabled.
cancelledCancelledStopped before the end.The calling resource stops while it waits; the owner of the operation was destroyed; a MySQL pool closed.
ioIoDisk or network transport failure.Unreadable file or store, connection lost, write failed.
existsExistsIt already exists.fs.mkdir on an existing folder, fs.writeFile with exclusive.
deniedDeniedThe player refused.A purchase or a permission prompt declined by the player.

Each function lists the codes it can return. A code you do not handle can be logged as is: it is a short stable string.

Details

  • Some asynchronous failures come with details: a third value in Lua, extra fields of the Error in JavaScript. Functions that provide them say so (for example MySQL { errno, sqlState, message }, files and HTTP { message }).
  • In JavaScript the rejection message reads lsmp.fn: <code>: <detail>; always test e.code, not the message.
  • lsmp.getLastError() returns the code of the last synchronous call of the resource that failed, or nil/null when the last such call succeeded.

Constant

lsmp.ErrorCode

SharedLua Β· JS
luaLua
lsmp.ErrorCode
jsJavaScript
lsmp.ErrorCode

Every failure code, by name: lsmp.ErrorCode.NotFound == "not-found".

lsmp.ErrorCode.NotFound = "not-found" Β· lsmp.ErrorCode.Timeout = "timeout" Β· lsmp.ErrorCode.NoHandler = "no-handler" Β· lsmp.ErrorCode.Error = "error" Β· lsmp.ErrorCode.Permission = "permission" Β· lsmp.ErrorCode.Limit = "limit" Β· lsmp.ErrorCode.Disconnected = "disconnected" Β· lsmp.ErrorCode.Invalid = "invalid" Β· lsmp.ErrorCode.Unavailable = "unavailable" Β· lsmp.ErrorCode.Cancelled = "cancelled" Β· lsmp.ErrorCode.Io = "io" Β· lsmp.ErrorCode.Exists = "exists" Β· lsmp.ErrorCode.Denied = "denied"

Reference

Limits and quotas

Sizes, counts, rates and timeouts a script can reach, and what happens beyond them.

Every limit a script can reach, with what happens when it is reached. Sizes of values are measured encoded, in the compact form used to send and store them: about one byte per small integer, the length of a string plus one or two bytes, nine bytes per float.

"Raises" means a programming error (RangeError in JavaScript, a Lua error), nothing is sent or stored. "limit" means the failure code limit. Keys marked server.cfg can be changed by the operator (see server.cfg).

Names

WhatLimitBeyond
Event and RPC name1 to 128 bytes of UTF-8, no NUL; lsmp: prefix reservedraises
Meta key1 to 128 bytes of UTF-8, no NUL; lsmp: prefix reservedraises
Storage key1 to 256 bytesraises
Command name1 to 64 characters among A-Z a-z 0-9 _ . : - (a leading / is ignored), case-insensitiveraises
Lua module name (require)1 to 128 characters among A-Z a-z 0-9 _ - .raises
Synchronized scene dict and clip1 to 63 bytesthe scene is refused
playerPreConnection deny reason256 bytescut to fit

Events and remote calls

WhatLimitBeyond
Arguments of emit, emitServer, emitClient*, call, callServer, callClient, browser:emit/call, page lsmp.emit/call32raises
Nesting of lists and maps in a value32 levelsraises
One map key4096 bytesraises
emit and local call (same side), arguments and result16 MiB encodedraises
Server β†’ client (emitClient, emitAllClients, emitDimensionClients, callClient request, answer to a callServer)16 MiB encodedemitClient* raises; a callClient request fails with limit; an answer that does not fit makes the caller fail with error
Client β†’ server (emitServer, callServer, answer to a callClient)4 MiB βˆ’ 1 KiB encodedraises
Lists, maps and byte arrays in one client β†’ server message65 536 in totalthe message is dropped, a line is logged
Script ↔ page message120 000 UTF-16 code units of JSONraises
Nested synchronous emit calls32raises lsmp.emit: recursion limit (32) reached
Handlers per resource (on, once, onServer, onClient)4096raises
RPC handlersone per name per side, for all resources and both enginesa second onCall raises
Pending outgoing calls per resource (call, callServer, callClient)4096limit
Calls from one player being handled at the same time1024the client's call fails with limit
Calls being answered at the same time by one resource on the client (callClient requests and local call)4096the call fails with limit; a server call not answered within 300 s is dropped
Call names (onCall) per resource on the client256raises
RPC timeoutMs1 to 300 000 ms, default 10 000 msraises; at the deadline the caller gets timeout
Client β†’ server script traffic per player (emitServer and callServer)ScriptEventBytesPerSec (server.cfg, default 1 MiB/s, four-second burst)events dropped on the server, warning in the log (once a minute per player)
Queued output to one clientMaxClientSendQueueBytes (server.cfg, default 64 MiB)the client is disconnected
βœ“
Large data

For large or frequent data, send what changed rather than the whole state, or serve files over HTTP routes and send their address.

Meta and storage

WhatLimitBeyond
One meta value8192 bytes encodedraises
Meta keys per player or entity, written by clientsMetaMaxKeys (server.cfg, default 256)the client write is refused
Meta bytes per player or entity, written by clientsMetaMaxBlobBytes (server.cfg, default 64 KiB)the client write is refused
Client meta write rateMetaWriteBytesPerSec (server.cfg, default 64 KiB/s, four-second burst)limit
One stored value64 KiB encodedraises
Storage of one resource16 MiB; each entry counts 64 bytes on top of its key and value (about 260 000 entries at most)limit
Storage write to diskwithin about 750 ms of the changeuse lsmp.storage.flush() to wait for it
lsmp.fs.readFile512 MiB per filelimit
lsmp.readResourceFile64 MiB per filelimit
lsmp.randomBytes1 to 65 536 bytesraises

Databases and HTTP

WhatLimitBeyond
MySQL pools per resource8 (JavaScript)limit
MySQL connectionLimit1 to 64raises
MySQL queryTimeoutMsdefault 0 (none)the query fails with timeout and its connection is closed
HTTP route per resource (lsmp.http.serve)onea second route replaces or is refused, see HTTP routes
HTTP route request body (maxBodyBytes)default 1 MiB, at most 16 MiBthe request is answered 413 without calling the handler
HTTP route answer time (timeoutMs)default 10 000 ms, at most 300 000 msthe client gets 504
HTTP requests being handled, whole server1024the client gets 503
HTTP requests being handled by one resource's route256the client gets 503
HTTP requests being handled from one client address64 (loopback not counted)the client gets 429
Outgoing HTTP requests in flight, sandboxed server resource256limit
lsmp.fs operations waiting, sandboxed server resource128 operations or 64 MiB of datalimit

Limits of the HTTP client (lsmp.http.get...) are on the HTTP client page.

Entities and scenes

WhatLimitBeyond
Pickup lifetimeMs0 (never) to 86 400 000 ms (24 h); removed at most 1 s after expiryraises
Pickup collectors64 playersraises
Synchronized scene participants1 to 8the scene is refused
Distance between the participants of a scene50 minvalid
Synchronized scenes running at once1024limit

Client resources

WhatLimitBeyond
2D browsers16 per resource, 128 on the clientnil/null with limit
3D browsers4 per resource, 64 on the clientnil/null with limit
Handlers on one browser (browser:on)1024raises
Messages from one page in one frame256 messages and 524 288 characters of JSONan emit is dropped, a call fails with limit; logged once a minute
lsmp.http on the client8 requests in flight and 20 per second per resource; 32 in flight and 128 MiB of response bodies for the whole clientlimit
Names given to lsmp.resources.invalidateArchives / restoreArchives1 to 4096 per call, each 1 to 512 bytes; 8192 archives invalidated at once on the clientraises (count, length); error beyond 8192

Time and memory

WhatLimitBeyond
Lua and JavaScript on the server: one run (handler, timer, file body) without suspendingSandboxWatchdogSec (server.cfg, default 10 s; 0 turns it off)sandboxed resources are interrupted with script interrupted: time budget exceeded, logged with the resource name; unsandboxed resources only get warnings
Lua and JavaScript on the client: one run (handler, timer, tick)250 msthe run is interrupted, the error is logged with the resource name
Script time of one resource per frame (client)100 ms in totalthe remaining timers and wake-ups wait for the next frame; 30 frames over budget within 10 s stop the resource (logged)
Timers per resource (setTimeout, setInterval)65 536raises too many timers in this resource (65536)
Waiting coroutines per resource (Lua) / pending lsmp.wait per resource (JS)65 536raises
Lua memory per resource (server)LuaMemoryLimitMiB (server.cfg, default 256 MiB)the allocation fails with a memory error in the resource
JavaScript heap (server, all resources together)JsHeapLimitMiB (server.cfg, default: chosen by the engine)an out-of-memory error in the script that allocates
resourceStop handlersResourceStopGraceMs (server.cfg, default 2000 ms); 1000 ms on the clientthe resource is torn down anyway
serverStop handlersShutdownGraceMs (server.cfg, default 5000 ms)resources are stopped anyway
Module-level awaits of a starting resourceResourceStartTimeoutMs (server.cfg, default 30 000 ms)the resource is marked failed
playerPreConnection verdictPreConnectionTimeoutMs (server.cfg, default 10 000 ms)the player is refused
setInterval periodat least 1 msa smaller period is raised to 1 ms
onTick errors (client)8 in a rowthe tick handler is disabled

Tutorials

Tutorial Β· Lua & JS

Tutorial: a /car command

A complete small feature: a player types /car adder, the server checks and creates the vehicle, and the player sits in it.

You will write one resource with a client script and a server script, talking through a remote call, and protect the command with a permission. It takes about fifteen minutes. The bundled vehicle-spawner resource is a fuller version of the same idea.

What happens

  1. The client checks that the name is a vehicle model (only the game knows) and computes a spot in front of the player.
  2. It asks the server with lsmp.callServer. Network entities are created by the server: every player nearby sees the same car.
  3. The server checks the permission and the distance (a client chooses what it sends), creates the vehicle owned by the player, and answers with its netId.
  4. The client waits for the car to exist in its game, then puts the player in the driver seat.

1. The resource folder

resources/
└─ car/
   β”œβ”€ manifest.json
   β”œβ”€ client/
   β”‚  └─ main.lua        # or main.js
   └─ server/
      └─ main.lua        # or main.js
jsonresources/car/manifest.json
{
  "title": "Car spawner",
  "description": "/car <model> spawns a vehicle in front of you.",
  "client_scripts": "client/main.lua",
  "server_scripts": "server/main.lua"
}

For JavaScript, name the files main.js and list them instead. The folder name, car, is the resource name. See Resource layout and manifest.

2. The server script

The server owns the decision. It declares the permission so that the server owner finds it in the admin panel, and answers each request with { netId } or { error }.

luaLua
-- resources/car/server/main.lua
local MAX_DISTANCE = 15
local spawned = {}   -- playerId -> netId of the car we made for them

lsmp.perms.declare("car.spawn", "Spawn a vehicle with /car")

lsmp.onCall("car:spawn", function(source, model, position, heading)
  if source == nil then return { error = "For players only." } end
  if not lsmp.perms.has(source, "car.spawn") then return { error = "You may not spawn vehicles." } end
  if math.type(model) ~= "integer" or type(position) ~= "table" or type(heading) ~= "number" then
    return { error = "Bad request." }
  end

  -- The position comes from the client: compare it with where the server knows the player is.
  local ped = lsmp.getPlayerPed(source)
  local here = ped and lsmp.getEntityCoords(ped)
  if not here then return { error = "You have not spawned yet." } end
  local dx, dy, dz = here.x - position.x, here.y - position.y, here.z - position.z
  if math.sqrt(dx * dx + dy * dy + dz * dz) > MAX_DISTANCE then
    return { error = "Too far from you." }
  end

  -- One car per player.
  if spawned[source] then lsmp.deleteEntity(spawned[source]) end

  local netId = lsmp.createEntity(lsmp.EntityType.Vehicle, model, position, {
    heading = heading,
    owner = source,                          -- simulated by this player from the first frame
    dimension = lsmp.getPlayerDimension(source),
    lifePolicy = lsmp.LifePolicy.WithCreator, -- removed when the player leaves
  })
  if not netId then return { error = "Could not create the vehicle (" .. lsmp.getLastError() .. ")." } end

  spawned[source] = netId
  return { netId = netId }
end)

lsmp.on("playerLeave", function(playerId)
  spawned[playerId] = nil
end)
jsJavaScript
// resources/car/server/main.js
const MAX_DISTANCE = 15;
const spawned = new Map();   // playerId -> netId of the car we made for them

lsmp.perms.declare('car.spawn', 'Spawn a vehicle with /car');

const isVec3 = (v) => v !== null && typeof v === 'object' && [v.x, v.y, v.z].every(Number.isFinite);

lsmp.onCall('car:spawn', (source, model, position, heading) => {
  if (source === null) return { error: 'For players only.' };
  if (!lsmp.perms.has(source, 'car.spawn')) return { error: 'You may not spawn vehicles.' };
  if (!Number.isInteger(model) || !isVec3(position) || !Number.isFinite(heading)) return { error: 'Bad request.' };

  // The position comes from the client: compare it with where the server knows the player is.
  const ped = lsmp.getPlayerPed(source);
  const here = ped !== null ? lsmp.getEntityCoords(ped) : null;
  if (!here || Math.hypot(here.x - position.x, here.y - position.y, here.z - position.z) > MAX_DISTANCE)
    return { error: 'Too far from you.' };

  // One car per player.
  if (spawned.has(source)) lsmp.deleteEntity(spawned.get(source));

  const netId = lsmp.createEntity(lsmp.EntityType.Vehicle, model, position, {
    heading,
    owner: source,                            // simulated by this player from the first frame
    dimension: lsmp.getPlayerDimension(source),
    lifePolicy: lsmp.LifePolicy.WithCreator,  // removed when the player leaves
  });
  if (netId === null) return { error: `Could not create the vehicle (${lsmp.getLastError()}).` };

  spawned.set(source, netId);
  return { netId };
});

lsmp.on('playerLeave', (playerId) => {
  spawned.delete(playerId);
});

3. The client script

The client registers /car in the F8 console, asks the server, and waits for the vehicle: the netId is valid at once, but the game builds the car over the next frames.

luaLua
-- resources/car/client/main.lua
local DRIVER_SEAT = -1

lsmp.registerCommand("car", {
  help = "Spawn a vehicle in front of you",
  params = { { name = "model", help = "Vehicle model, such as adder", optional = true } },
}, function(args)
  local name = (args[1] or "sultan"):lower()
  local model = lsmp.hash(name)
  if not isModelInCdimage(model) or not isModelAVehicle(model) then
    lsmp.log(name .. " is not a vehicle model")
    return
  end

  local ped = playerPedId()
  local pos = getEntityCoords(ped, true)
  local fwd = getEntityForwardVector(ped)
  local spot = { x = pos.x + fwd.x * 5, y = pos.y + fwd.y * 5, z = pos.z + 0.5 }

  local answer, err = lsmp.callServer("car:spawn", model, spot, getEntityHeading(ped))
  if not answer then
    lsmp.log("the server did not answer: " .. err)
    return
  end
  if answer.error then
    lsmp.log(answer.error)
    return
  end

  for _ = 1, 50 do
    local vehicle = lsmp.getEntityFromNetId(answer.netId)
    if vehicle then
      setPedIntoVehicle(playerPedId(), vehicle, DRIVER_SEAT)
      return
    end
    lsmp.wait(100)
  end
end)
jsJavaScript
// resources/car/client/main.js
const DRIVER_SEAT = -1;

lsmp.registerCommand('car', {
  help: 'Spawn a vehicle in front of you',
  params: [{ name: 'model', help: 'Vehicle model, such as adder', optional: true }],
}, async (args) => {
  const name = (args[0] || 'sultan').toLowerCase();
  const model = lsmp.hash(name);
  if (!isModelInCdimage(model) || !isModelAVehicle(model)) {
    lsmp.log(`${name} is not a vehicle model`);
    return;
  }

  const ped = playerPedId();
  const pos = getEntityCoords(ped, true);
  const fwd = getEntityForwardVector(ped);
  const spot = { x: pos.x + fwd.x * 5, y: pos.y + fwd.y * 5, z: pos.z + 0.5 };

  let answer;
  try {
    answer = await lsmp.callServer('car:spawn', model, spot, getEntityHeading(ped));
  } catch (err) {
    lsmp.log(`the server did not answer: ${err.code}`);
    return;
  }
  if (answer.error) {
    lsmp.log(answer.error);
    return;
  }

  for (let i = 0; i < 50; i++) {
    const vehicle = lsmp.getEntityFromNetId(answer.netId);
    if (vehicle !== null) {
      setPedIntoVehicle(playerPedId(), vehicle, DRIVER_SEAT);
      return;
    }
    await lsmp.wait(100);
  }
});

4. Give the permission and test

  1. Load the resource

    Restart the server (quit in its console, then start it again): resources are loaded when the server starts.

  2. Give the permission

    In the admin panel, Permissions tab, allow car.spawn to a group you are in (or to default for every player). A script can do it too: lsmp.perms.allow("group:default", "car.spawn").

  3. Try it

    In game, open the F8 console and type /car adder. Without the permission, the server answers "You may not spawn vehicles."

βœ“
Going further

Add a /dv command that deletes the player's car through another lsmp.onCall, and a cooldown per player on the server. The bundled vehicle-spawner resource does both: see Bundled example resources.

Tutorials

Tutorial: your first web UI

Build an ATM in twenty minutes: a web page in game that shows the player's balance and lets them withdraw cash, with the server deciding every amount.

You need a running server and to have done the Quick start. We build a resource named atm. Its three parts talk in a line, never around it: page ⇄ client script ⇄ server script. The page asks the client script, which asks the server, which decides.

  1. Create the folder and the manifest

    web/ is served to your pages at rsc://atm/.

    Lua only:

    resources/
    └─ atm/
       β”œβ”€ manifest.json
       β”œβ”€ server/
       β”‚  └─ main.lua
       β”œβ”€ client/
       β”‚  └─ main.lua
       └─ web/
          β”œβ”€ index.html
          β”œβ”€ style.css
          └─ app.js

    JavaScript only:

    resources/
    └─ atm/
       β”œβ”€ manifest.json
       β”œβ”€ server/
       β”‚  └─ main.js
       β”œβ”€ client/
       β”‚  └─ main.js
       └─ web/
          β”œβ”€ index.html
          β”œβ”€ style.css
          └─ app.js

    Lua only:

    jsonmanifest.json
    {
      "title": "ATM",
      "server_scripts": "server/main.lua",
      "client_scripts": "client/main.lua",
      "webui": "web"
    }

    JavaScript only:

    jsonmanifest.json
    {
      "title": "ATM",
      "server_scripts": "server/main.js",
      "client_scripts": "client/main.js",
      "webui": "web"
    }
  2. The server owns the money

    Two remote calls: one reads the balance, one withdraws. The server checks the amount: a page or a client can send anything. The balance lives in memory to keep the tutorial short; Storing data shows how to keep it.

    luaserver/main.lua
    local balances = {}   -- playerId -> dollars
    
    lsmp.on("playerJoin", function(playerId)
      balances[playerId] = 5000
    end)
    
    lsmp.on("playerLeave", function(playerId)
      balances[playerId] = nil
    end)
    
    lsmp.onCall("atm:balance", function(source)
      return balances[source] or 0
    end)
    
    lsmp.onCall("atm:withdraw", function(source, amount)
      local balance = balances[source] or 0
      if math.type(amount) ~= "integer" or amount < 1 or amount > 2000 then
        return { ok = false, reason = "Choose between $1 and $2,000." }
      end
      if amount > balance then
        return { ok = false, reason = "Not enough money." }
      end
      balances[source] = balance - amount
      lsmp.log(lsmp.getPlayerName(source) .. " withdrew $" .. amount)
      return { ok = true, balance = balances[source] }
    end)
    jsserver/main.js
    const balances = new Map();   // playerId -> dollars
    
    lsmp.on('playerJoin', (playerId) => balances.set(playerId, 5000));
    lsmp.on('playerLeave', (playerId) => balances.delete(playerId));
    
    lsmp.onCall('atm:balance', (source) => balances.get(source) ?? 0);
    
    lsmp.onCall('atm:withdraw', (source, amount) => {
      const balance = balances.get(source) ?? 0;
      if (!Number.isInteger(amount) || amount < 1 || amount > 2000) {
        return { ok: false, reason: 'Choose between $1 and $2,000.' };
      }
      if (amount > balance) return { ok: false, reason: 'Not enough money.' };
      balances.set(source, balance - amount);
      lsmp.log(`${lsmp.getPlayerName(source)} withdrew $${amount}`);
      return { ok: true, balance: balance - amount };
    });
  3. The page

    A small panel in the middle of a transparent, full-screen page. It asks for the balance when it opens, and for a withdrawal when the player presses the button. It never decides anything.

    htmlweb/index.html
    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <link rel="stylesheet" href="style.css">
    </head>
    <body>
      <main class="atm">
        <h1>ATM</h1>
        <p class="balance">Balance: <b id="balance">…</b></p>
        <input id="amount" type="number" min="1" max="2000" value="100">
        <button id="withdraw">Withdraw</button>
        <p id="message"></p>
        <button id="close" class="ghost">Close</button>
      </main>
      <script src="app.js"></script>
    </body>
    </html>
    cssweb/style.css
    html, body { margin: 0; height: 100%; background: transparent; font-family: system-ui, sans-serif; }
    body { display: grid; place-items: center; }
    .atm {
      width: 22rem; padding: 1.5rem; border-radius: 12px;
      background: rgba(12, 16, 24, .92); color: #fff; box-shadow: 0 10px 40px #0008;
    }
    .atm h1 { margin: 0 0 1rem; font-size: 1.3rem; }
    .atm input, .atm button { width: 100%; box-sizing: border-box; padding: .7rem; margin-top: .6rem; font: inherit; border-radius: 8px; border: 0; }
    .atm button { background: #2e9d5b; color: #fff; cursor: pointer; }
    .atm button.ghost { background: transparent; color: #aaa; }
    #message { min-height: 1.2em; color: #ffcf5a; }
    jsweb/app.js
    const $ = (id) => document.getElementById(id);
    const dollars = (n) => `$${n.toLocaleString(lsmp.language)}`;
    
    // The client script sends 'open' each time the ATM opens.
    lsmp.on('open', async () => {
      $('message').textContent = '';
      $('balance').textContent = dollars(await lsmp.call('balance'));
      $('amount').focus();
    });
    
    $('withdraw').addEventListener('click', async () => {
      try {
        const result = await lsmp.call('withdraw', Number($('amount').value));
        if (result.ok) {
          $('balance').textContent = dollars(result.balance);
          $('message').textContent = 'Take your cash.';
        } else {
          $('message').textContent = result.reason;
        }
      } catch (err) {
        $('message').textContent = `The bank is unavailable (${err.code}).`;
      }
    });
    
    $('close').addEventListener('click', () => lsmp.emit('close'));
    document.addEventListener('keydown', (e) => { if (e.key === 'Escape') lsmp.emit('close'); });
  4. The client script connects them

    It opens the page hidden, shows it on the /atm command, and forwards the page's calls to the server. In Lua, the handler may wait for the server: it runs in a coroutine. In JavaScript, it returns a Promise.

    luaclient/main.lua
    local atm = lsmp.createBrowser("rsc://atm/index.html", { visible = false })
    
    local function setOpen(open)
      atm:setVisible(open)
      atm:setFocus(open)
      if open then atm:emit("open") end
    end
    
    lsmp.registerCommand("atm", { help = "open the ATM" }, function()
      setOpen(true)
    end)
    
    -- Page -> client -> server, and the answer goes back the same way.
    atm:on("balance", function()
      local balance = lsmp.callServer("atm:balance")
      return balance or 0
    end)
    
    atm:on("withdraw", function(amount)
      local result, err = lsmp.callServer("atm:withdraw", amount)
      if not result then
        return { ok = false, reason = "The bank did not answer (" .. err .. ")." }
      end
      return result
    end)
    
    atm:on("close", function() setOpen(false) end)
    atm:on("focusLost", function() setOpen(false) end)   -- Ctrl+Alt+Backspace
    jsclient/main.js
    const atm = lsmp.createBrowser('rsc://atm/index.html', { visible: false });
    
    function setOpen(open) {
      atm.setVisible(open);
      atm.setFocus(open);
      if (open) atm.emit('open');
    }
    
    lsmp.registerCommand('atm', { help: 'open the ATM' }, () => setOpen(true));
    
    // Page -> client -> server, and the answer goes back the same way.
    atm.on('balance', () => lsmp.callServer('atm:balance'));
    
    atm.on('withdraw', async (amount) => {
      try {
        return await lsmp.callServer('atm:withdraw', amount);
      } catch (err) {
        return { ok: false, reason: `The bank did not answer (${err.code}).` };
      }
    });
    
    atm.on('close', () => setOpen(false));
    atm.on('focusLost', () => setOpen(false));   // Ctrl+Alt+Backspace
  5. Start it and try

    Restart the server so it loads atm, then join. In game, open the client console (F8) and type atm. Withdraw $100: the balance drops, and the server console prints the withdrawal. Try $99999: the server refuses, and the page shows why.

    textserver console
    [atm] Jane withdrew $100
  6. Change and reload

    Edit the page or a script, then restart the server and join again. To iterate faster on the page and the client scripts, run them as local resources in Story mode. To inspect the page (elements, console, network), open DevTools.

βœ“
What you used

webui and rsc:// (Resource layout), createBrowser, setVisible, setFocus, emit and on (Browsers), the page's lsmp.on, lsmp.call and lsmp.emit (Page API), and server calls (Events and RPC).

  • Keep the balance across restarts with storage.
  • Open the ATM when the player stands at a real ATM prop instead of a command: World helpers.
  • Translate the page with lsmp.language.
  • Read Web interfaces for frameworks, hot reload and 3D screens.
Tutorial Β· Lua & JS

Tutorial: a shop with remote calls and storage

A weapon shop where the server keeps each account's money, answers the client's questions with remote calls, and saves everything across restarts.

Two rules shape this tutorial:

- Money lives on the server. The client asks, the server decides. A client can be modified; the server cannot.
- Saved data is keyed on the account (lsmpId), never on the playerId, which the next player gets when this one leaves. Guests have no account, so they cannot buy.

We use calls for the questions (lsmp.callServer on the client, lsmp.onCall on the server) and storage for the wallets.

resources/
└─ shop/
   β”œβ”€ manifest.json      # client_scripts: client/main.lua, server_scripts: server/main.lua
   β”œβ”€ client/
   β”‚  └─ main.lua        # or main.js
   └─ server/
      └─ main.lua        # or main.js

1. The server: catalogue, wallets, purchases

The catalogue is a table on the server: the client never sends a price. Each wallet is one storage entry, wallet:<lsmpId>, holding a number. lsmp.storage.set is visible to the next get at once and written to disk shortly after.

luaLua
-- resources/shop/server/main.lua
local START_MONEY = 5000

local ITEMS = {
  pistol  = { label = "Pistol",       price = 800,  weapon = "WEAPON_PISTOL",       ammo = 60 },
  smg     = { label = "SMG",          price = 2500, weapon = "WEAPON_SMG",          ammo = 120 },
  carbine = { label = "Carbine rifle", price = 4200, weapon = "WEAPON_CARBINERIFLE", ammo = 180 },
}

local function walletKey(source)
  local account = lsmp.getPlayerLsmpId(source)
  return account and ("wallet:" .. account)
end

local function balanceOf(key)
  return lsmp.storage.get(key) or START_MONEY
end

-- What the shop sells, and what this player has.
lsmp.onCall("shop:list", function(source)
  local key = source and walletKey(source)
  local list = {}
  for id, item in pairs(ITEMS) do
    list[#list + 1] = { id = id, label = item.label, price = item.price }
  end
  table.sort(list, function(a, b) return a.price < b.price end)
  return { items = list, balance = key and balanceOf(key) }
end)

-- A purchase: everything is checked here.
lsmp.onCall("shop:buy", function(source, id)
  local key = source and walletKey(source)
  if not key then return { error = "Only players with an LS:MP account can buy." } end
  local item = type(id) == "string" and ITEMS[id]
  if not item then return { error = "No such item." } end

  local balance = balanceOf(key)
  if balance < item.price then return { error = "Not enough money.", balance = balance } end

  balance = balance - item.price
  lsmp.storage.set(key, balance)
  lsmp.log(("%s bought %s, %d left"):format(lsmp.getPlayerName(source), id, balance))
  return { balance = balance, weapon = item.weapon, ammo = item.ammo }
end)
jsJavaScript
// resources/shop/server/main.js
const START_MONEY = 5000;

const ITEMS = {
  pistol:  { label: 'Pistol',        price: 800,  weapon: 'WEAPON_PISTOL',       ammo: 60 },
  smg:     { label: 'SMG',           price: 2500, weapon: 'WEAPON_SMG',          ammo: 120 },
  carbine: { label: 'Carbine rifle', price: 4200, weapon: 'WEAPON_CARBINERIFLE', ammo: 180 },
};

function walletKey(source) {
  const account = lsmp.getPlayerLsmpId(source);
  return account !== null ? `wallet:${account}` : null;
}

const balanceOf = (key) => lsmp.storage.get(key) ?? START_MONEY;

// What the shop sells, and what this player has.
lsmp.onCall('shop:list', (source) => {
  const key = source !== null ? walletKey(source) : null;
  const items = Object.entries(ITEMS)
    .map(([id, item]) => ({ id, label: item.label, price: item.price }))
    .sort((a, b) => a.price - b.price);
  return { items, balance: key ? balanceOf(key) : null };
});

// A purchase: everything is checked here.
lsmp.onCall('shop:buy', (source, id) => {
  const key = source !== null ? walletKey(source) : null;
  if (!key) return { error: 'Only players with an LS:MP account can buy.' };
  const item = typeof id === 'string' && Object.hasOwn(ITEMS, id) ? ITEMS[id] : null;
  if (!item) return { error: 'No such item.' };

  let balance = balanceOf(key);
  if (balance < item.price) return { error: 'Not enough money.', balance };

  balance -= item.price;
  lsmp.storage.set(key, balance);
  lsmp.log(`${lsmp.getPlayerName(source)} bought ${id}, ${balance} left`);
  return { balance, weapon: item.weapon, ammo: item.ammo };
});
⚠
Check what the client sends

Arguments of a remote call keep their type, but the client chooses them. Here id is looked up in the server's own table; a string such as toString or __index finds nothing. Never trust a price, an amount or a position coming from a client.

2. The client: /shop and /buy

The client only displays and asks. When the server accepts a purchase it answers with the weapon to give, and the client gives it to its own ped.

luaLua
-- resources/shop/client/main.lua
lsmp.registerCommand("shop", { help = "List what the shop sells" }, function()
  local res, err = lsmp.callServer("shop:list")
  if not res then
    lsmp.log("the shop is closed: " .. err)
    return
  end
  for _, item in ipairs(res.items) do
    lsmp.log(("%-8s %-14s $%d"):format(item.id, item.label, item.price))
  end
  lsmp.log(res.balance and ("you have $" .. res.balance) or "guests cannot buy")
end)

lsmp.registerCommand("buy", {
  help = "Buy an item: /buy pistol",
  params = { { name = "item" } },
}, function(args)
  local res, err = lsmp.callServer("shop:buy", args[1])
  if not res then
    lsmp.log("the shop did not answer: " .. err)
  elseif res.error then
    lsmp.log(res.error)
  else
    giveWeaponToPed(playerPedId(), lsmp.hash(res.weapon), res.ammo, false, true)
    lsmp.log("bought, $" .. res.balance .. " left")
  end
end)
jsJavaScript
// resources/shop/client/main.js
lsmp.registerCommand('shop', { help: 'List what the shop sells' }, async () => {
  try {
    const res = await lsmp.callServer('shop:list');
    for (const item of res.items) lsmp.log(`${item.id.padEnd(8)} ${item.label.padEnd(14)} $${item.price}`);
    lsmp.log(res.balance !== null ? `you have $${res.balance}` : 'guests cannot buy');
  } catch (err) {
    lsmp.log(`the shop is closed: ${err.code}`);
  }
});

lsmp.registerCommand('buy', {
  help: 'Buy an item: /buy pistol',
  params: [{ name: 'item' }],
}, async (args) => {
  let res;
  try {
    res = await lsmp.callServer('shop:buy', args[0]);
  } catch (err) {
    lsmp.log(`the shop did not answer: ${err.code}`);
    return;
  }
  if (res.error) {
    lsmp.log(res.error);
    return;
  }
  giveWeaponToPed(playerPedId(), lsmp.hash(res.weapon), res.ammo, false, true);
  lsmp.log(`bought, $${res.balance} left`);
});

3. Try it

  1. Load the resource

    Restart the server: resources are loaded when it starts.

  2. Shop

    In game, F8 console: /shop, then /buy pistol.

  3. Restart and check

    Restart the server, join again and type /shop: the balance is still there, read back from the storage.

Going further

  • Give money: a server command that adds to a wallet (lsmp.storage.set(key, balanceOf(key) + amount)), protected by a permission.
  • Show the shop in a web interface instead of the console: the page calls the client script, which calls the server the same way.
  • Sell real benefits, bought on Summum from your store or in game: see In-game benefits.
  • Many items or many players: move the wallets to MySQL and do the check and the update in one transaction.
Tutorials

Recipe: server-spawned AI

Spawn AI peds from the server and keep their behaviour when another player takes over their simulation.

This recipe spawns AI peds from the server and keeps them behaving the same way whoever simulates them: guards around a building, and a ped driven by your own client code. It uses entities, ownership and intents, meta and the entityAdopt event.

β„Ή
Why intents

A ped's AI runs in the game of the player who simulates it. When that player walks away or leaves, another player takes over and the game task is lost. An intent is stored with the entity on the server, and every new owner applies it again.

Guards with a built-in intent

  1. Spawn the peds

    lifePolicy = "keep" keeps the guards alive when nobody is around. They are deleted with the resource when it stops.

    luaLua
    local POST = { x = -1037.0, y = -2737.0, z = 20.17 }
    local guards = {}
    
    lsmp.on("resourceStart", function(name)
      if name ~= lsmp.getResourceName() then return end
      for i = 1, 3 do
        local pos = { x = POST.x + i * 2.0, y = POST.y, z = POST.z }
        local ped, err = lsmp.createEntity("ped", "s_m_m_security_01", pos, { heading = 180.0, lifePolicy = "keep" })
        if ped then guards[#guards + 1] = ped else lsmp.warn("guard not created: " .. err) end
      end
    end)
    jsJavaScript
    const POST = { x: -1037, y: -2737, z: 20.17 };
    const guards = [];
    
    lsmp.on("resourceStart", (name) => {
      if (name !== lsmp.getResourceName()) return;
      for (let i = 1; i <= 3; i++) {
        const pos = { x: POST.x + i * 2, y: POST.y, z: POST.z };
        const ped = lsmp.createEntity("ped", "s_m_m_security_01", pos, { heading: 180, lifePolicy: "keep" });
        if (ped !== null) guards.push(ped);
        else lsmp.warn(`guard not created: ${lsmp.getLastError()}`);
      }
    });
  2. Give them an intent

    A "guard" intent keeps each ped within radius of position and makes it attack what comes close. keepTask stops ambient events from replacing the task; mission keeps the game from cleaning the ped up.

    luaLua
    for _, ped in ipairs(guards) do
      lsmp.setEntityIntent(ped, {
        type = "guard", position = POST, radius = 12.0,
        accuracy = 40, keepTask = true, mission = true, hatesPlayers = true,
      })
    end
    jsJavaScript
    for (const ped of guards) {
      lsmp.setEntityIntent(ped, {
        type: "guard", position: POST, radius: 12,
        accuracy: 40, keepTask: true, mission: true, hatesPlayers: true,
      });
    }
  3. Change orders later

    Set a new intent at any time; the current owner applies it, and so will the next ones.

    luaLua
    lsmp.registerCommand("alarm", function(args, raw, source)
      for _, ped in ipairs(guards) do
        lsmp.setEntityIntent(ped, { type = "combat", target = "nearestPlayer", accuracy = 60, keepTask = true, run = true })
      end
    end)
    jsJavaScript
    lsmp.registerCommand("alarm", (args, raw, source) => {
      for (const ped of guards) {
        lsmp.setEntityIntent(ped, { type: "combat", target: "nearestPlayer", accuracy: 60, keepTask: true, run: true });
      }
    });

Your own AI with a custom intent

With type = "custom", LS:MP applies no task. The client that takes over the ped receives entityAdopt and gives the orders itself, with game natives. Store what the client needs in the entity's meta.

  1. Server: mark the ped
    luaLua
    local ped = lsmp.createEntity("ped", "a_m_y_hipster_01", { x = 200.0, y = -930.0, z = 30.7 }, { lifePolicy = "keep" })
    if ped then
      lsmp.setEntityMeta(ped, "ai:scenario", "WORLD_HUMAN_MUSICIAN")
      lsmp.setEntityIntent(ped, { type = "custom", keepTask = true, mission = true })
    end
    jsJavaScript
    const ped = lsmp.createEntity("ped", "a_m_y_hipster_01", { x: 200, y: -930, z: 30.7 }, { lifePolicy: "keep" });
    if (ped !== null) {
      lsmp.setEntityMeta(ped, "ai:scenario", "WORLD_HUMAN_MUSICIAN");
      lsmp.setEntityIntent(ped, { type: "custom", keepTask: true, mission: true });
    }
  2. Client: apply it when adopting

    entityAdopt fires on the client that starts simulating the entity, each time ownership moves to it.

    luaLua
    lsmp.on("entityAdopt", function(netId)
      local scenario = lsmp.getEntityMeta(netId, "ai:scenario")
      if not scenario then return end
      local ped = lsmp.getEntityFromNetId(netId)
      if ped then taskStartScenarioInPlace(ped, scenario, 0, true) end
    end)
    jsJavaScript
    lsmp.on("entityAdopt", (netId) => {
      const scenario = lsmp.getEntityMeta(netId, "ai:scenario");
      if (!scenario) return;
      const ped = lsmp.getEntityFromNetId(netId);
      if (ped) taskStartScenarioInPlace(ped, scenario, 0, true);
    });

Good to know

  • Owners change: never keep AI state only in one client. Keep it in the intent or in meta.
  • To keep one ped on one player (an escort, a pet), create it with owner = playerId and set its owner policy to "pinned".
  • A ped you move only from the server (no game AI) uses the owner policy "server".
  • Peds of other resources need the entities.foreign capability to be given intents.
Tutorial Β· Lua & JS

Bundled example resources

The resources shipped with the server: what each one does, which part of the API it shows, and how to install them.

The server download holds two folders: lsmp-server/, the server itself, and resource_samples/, the resources of this page. Each script starts with a few lines that say what it does, and is commented where it matters. Some are essentials a server needs (arrival, chat, death, voice), others are samples of one part of the API each, and two are tools. Most are written in JavaScript; four also exist in Lua.

Installing them

  • Nothing in resource_samples/ runs by itself. Copy the folders you want into the resources/ folder of your server, then restart the server: every folder of resources/ starts with it.
  • To turn one off without deleting it, use resources.json or the admin panel's Resources tab, then restart the server: { "resources": { "emptymap": { "enabled": false } } }.
  • They are yours to edit. Rename the folder if you turn one into something of your own: the folder name is the resource's name.
  • Commands written /like this are typed in the game's F8 console; the others in the server console. With the chat resource, a line that starts with / in the chat runs a server command with the player's permissions.
⚠
One resource must spawn the players

A server with an empty resources/ folder lets players in, but nothing places them in the world: they stay on the loading screen. Install spawn-mgr, or a resource of your own that spawns players. See Local player, spawn and death.

Essentials

ResourceWhat it doesShows
spawn-mgrPlaces each arriving player at a random point of shared/config.js. /spawn [number|list] to move.The auto spawn handler, lsmp.spawn, the playerSpawn event, shared scripts.
chatText chat: T to type, Enter to send. Lines starting with / run server commands with the player's permissions. /shout, /clearchat.A web interface with browser.emit/on, rate limiting on the server, executeCommand.
death-mgrRespawn near the place of death after a few seconds, and a kill feed for the players of the same dimension.playerDeath on both sides, lsmp.resurrect, emitDimensionClients.
voice-mgrProximity voice with whisper, normal and shout ranges (K), and radio frequencies with /radio <1-999> (Caps Lock to talk).The whole Voice API: channels, roles, ranges, mutes (vmute, vunmute, vchannels in the server console).
admin-toolsModeration commands for the server console and, with permissions, the chat: online, ids, kickplayer, ban, unban, whitelist, announce.Admission and moderation, commands with permissions.
scoreboardKills and deaths of every player; hold Z to see them.Global meta as shared state, metaChange on the client.
player-blipsA map blip on every player streamed near you. /blips toggles them.getEntitiesInRadius, the entityStreamOut event, blip natives.

Samples

ResourceTry itShows
hello-worldJoin, then /hello; hello some words in the server console.The smallest complete resource: a shared file, events both ways, a remote call, a command on each side. Start here.
admission-sampleEdit server/config.json (maintenance, name rules), then connect.The playerPreConnection event and p.deny.
browser3d-sample/screen3d on, /screen3d say <text>, /screen3d off.A web page rendered into a texture and shown in place of a texture of the map (3D browsers, replaceTexture).
death-respawnRun it without death-mgr, then die.A client-driven respawn at the closest point of a list, game notifications. Steps aside while death-mgr runs.
dimensions-sample/dim <n>, /instance, /dimwho, /dim 0.Moving players and their vehicle between dimensions, a private dimension without traffic.
discord-sampleLook at your Discord profile while playing. /presence off.The Discord presence functions (Discord presence).
event-loggerevlog in the server console, /evlog in F8.Every engine event on both sides, with its arguments.
events-sample/rpc 2 3, /blob, /bigdata, /localevent hello.Remote calls, bytes, a large payload, local events.
http-sample/httpget, /httppost; http-test in the server console; open /res/http-sample/status on the server's HTTP port.The HTTP client on both sides and an HTTP route.
hud-sampleLook at the bottom right corner. /hud hides it.A HUD drawn by a web page fed by the client script (Web interfaces).
identity-sample/whoami, /who <playerId>.playerId against lsmpId, guests, avatars, identifiers (Players).
in-game-benefitFirst create its two products in your Summum store (see shared/config.js). Then /shop vip, /shop cash 3, /wallet; benefit-pending <lsmpId> in the server console.In-game benefits: a cart opened in game, each purchase applied exactly once and confirmed, refunds taken back.
metasync-sample/status <text>, /label <text> in a vehicle, /motd.Player, entity and global meta, checked by the server with metaChange.
modules-sampletip in the server console.Local modules, JSON files, Node core modules and resource files (runtimes).
nametags-sample/nametags far, near, off, reset, info; /beacon <playerId>.Styling the names above players, for everybody or for one player (Nametags).
npc-sample/npc wander, follow, flee, hostile, idle, /npc clear.Server-spawned peds with AI intents that survive owner changes (Ownership and AI intents).
outline-sample/highlight vehicles, /highlight peds, /highlight off.Entity outlines coloured by owner (Outlines and picking).
ownership-sampleStand next to a vehicle: /owner, /fix.Asking for the ownership of an entity before changing it (Client entities).
perms-sample/myperms, /can <permission>, /perk in F8; /whoami, /promote <playerId> in the chat.Groups, rules, session memberships, the client copy (Permissions).
picker-sample/picker, /pickertool.Picking what is under the crosshair (Outlines and picking).
pickups-sampleGo to Legion Square and walk over the pickups.createPickup and the pickupCollect event (Entities and pickups).
spatial-sample/near, /aim, /labels; near <playerId> in the server console.Queries around a point on both sides, a raycast from the camera, netIds and handles (Spatial queries).
storage-sample/playtime in F8, playtime-top in the server console.Persistent storage, keyed on accounts.
teleport-sample/pos, /tp x y [z], /tpm, /goto <playerId>.Moving the local player, waiting for collisions, a server lookup through a remote call.
texture-sample/texture file, /texture pixels, /texture info, /texture off.An image file of the resource and pixels computed by the script, shown in place of a texture of the map (Textures).
vehicle-spawner/car [model], /dv.Server-created vehicles owned by a player; the tutorial builds a smaller one.
weather-sampleweather, weather RAIN 10, weather cycle in the server console; /sky SNOW, /sky off in F8.Reading and forcing the synchronized weather, a local sky for one player.

Lua versions

The same samples in Lua. Their commands, events and permissions end in -lua, so they run next to the JavaScript ones. hello-world-lua is written in Lua on both sides; the three others have their server half in Lua and keep a JavaScript client.

ResourceTry itLua version of
hello-world-lua/hello-lua; hello-lua some words in the server console.hello-world
events-sample-lua/rpc-lua, /blob-lua, /bigdata-lua.events-sample
storage-sample-lua/playtime-lua, playtime-top-lua in the server console.storage-sample
perms-sample-lua/whoami-lua, /promote-lua <playerId>, /demote-lua <playerId>.perms-sample

Tools

Two resources for testing maps. Leave them out of a public server.

ResourceTry itWhat for
emptymap/unloadmap [group...], /reloadmap, /mapstate, /maprelease.Unloads the base map while playing (Hot resources, stream sets and archives).
streamset-sample/loadset <resource> <set>, /unloadset, /setstate.Loads and unloads the stream sets of any resource.