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
- Run a server
- Build resources
- Publish
- Shared API
- Server API
- Client API
- Page API
- Natives
- Reference
- Tutorials
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, leaving | Engine events with lsmp.on |
| Send data between server and clients | Events (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 sees | Entities, with ownership and dimensions |
| Store data | Meta for live replicated values, storage, MySQL and files to keep them |
| Show an interface | Web pages in 2D or on a surface of the world (browsers) |
| Talk to players by voice | Voice channels driven by your scripts |
| Call web services | The HTTP client, and HTTP routes on the server |
| Drive the game itself | About 6,700 game natives, as global functions in client scripts |
| Ship models, maps and vehicles | Assets and streaming |
Start here
Coming from FiveM
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.
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.
- 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.Helloormy modwould be refused, with a suggested name in the console. Names starting withlsmpare 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 gameJavaScript only:
resources/ ββ hello/ ββ manifest.json ββ server/ β ββ main.js # runs on the server only ββ client/ ββ main.js # sent to every player, runs in their game - Write the manifest
manifest.jsonlists which files run where. Each list takes a string or an array, and accepts patterns such as"client/*.lua". A side can mix.luaand.jsfiles. 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"] } - Write the scripts
The server listens for the client's
hello:pingevent and answers withhello:pongto that player only. It also handles the remote callhello: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) endjsserver/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}`)); - Start the resource
The server loads its resources when it starts: restart it so it loads
hello(typequitin 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. - 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. - Go further
You have the whole loop: files in a folder, a manifest, both sides, events and a remote call.
- Core concepts: the ideas behind every page, in a few minutes.
- Events and RPC: events, remote calls, and when to use which.
- Your first web UI: a page in game that talks to your scripts.
- Storing data: meta, storage, MySQL and files.
- A /car command: a small complete feature, with a permission and an entity.
- Debugging: logs, DevTools and common errors.
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.
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
| Side | Where it runs | Typical job |
|---|---|---|
| Server | On your server, once. | The authority: rules, money, permissions, persistent data, entities everyone shares. |
| Client | In each player's game, sent with the resource. | What one player sees and does: natives, HUD, input, camera, local effects. |
| Page | In 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
| Name | What it identifies | Valid |
|---|---|---|
playerId | A connected player, for this session. Given by the server, the same on every side. | until the player leaves |
lsmpId | A player's LS:MP account. nil / null for a guest. | forever |
netId | A networked entity (vehicle, ped, object), the same on the server and on every client. | while the entity exists |
| handle | An 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 |
dimension | A 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.
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)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
| Meta | Storage | |
|---|---|---|
| What | Live values attached to the server (global), a player or an entity. | Your resource's persistent key/value store. |
| Where | Replicated: every client reads them, and gets notified when they change. | On the server only. |
| How long | Until the player leaves, the entity goes, or the server stops. | Kept across restarts. |
| For | A 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
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.
| Windows | Linux | |
|---|---|---|
| System | Windows x64 | x64 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. |
| Program | lsmp-server.exe | ./lsmp-server |
| Ports | 2086 TCP (HttpPort), 9530 TCP and UDP (GamePort) | the same |
Install
- 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.bashLinuxcd /home/lsmp/server chmod +x lsmp-server - 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 commentedserver.cfgwith every default, packs the resources, opens its ports and prints a framed SETUP REQUIRED message with a one-time code. Leave it running.textserver consoleSETUP 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 - Open the ports
Open
HttpPort(2086) in TCP, andGamePort(9530) in TCP and UDP. Behind a home router, also forward them to this machine. The commands for each system are in Go public. - Run the setup page
Open
http://<server-ip>:2086/lsadminin 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:- Terms: read the LS:MP EULA to the end and accept it. It is the text of
eula.txt, next toserver.cfg. - 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
Tokenby itself. You can skip this step and link the server later. - Server: name, description, maximum players and map. A linked server can turn on the public listing here.
- Access: how administrators sign in. LS:MP sign-in only is recommended; a local account needs a password of 8 characters or more.
- Finish: review, press Finish setup, then Restart now. Everything is written to
server.cfgand applies at this restart.
- Terms: read the LS:MP EULA to the end and accept it. It is the text of
- 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.
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
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
- 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. - It reads
resources.json, then scansresources/. Every valid folder becomes a resource named after the folder; a folder with an invalid name is refused, with the name to use instead. - 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.
- It starts every enabled resource, dependencies first, then delivers
serverStart. - It opens the game port (
GamePort, TCP and UDP) and serves HTTP onHttpPort: 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.
[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.targetsudo systemctl daemon-reload
sudo systemctl enable --now lsmpTroubleshooting
| Symptom | Cause and fix |
|---|---|
The Linux program does not start, with a GLIBC or library error | The system is too old, or libcurl or brotli is missing: see the table at the top of this page. |
/ answers 404 on the HTTP port | Normal: the panel is at /lsadmin. |
| The panel page is blank or broken | The uiadmin/ folder is not next to the program, or the server was not started from its folder. |
| The setup code is lost | A 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 exits | The two ports must differ: fix server.cfg. |
MaxPlayers is lower than what you set | It is capped by the plan of the server's owner, with a line in the log. |
| Players connect, then nothing moves | GamePort is open in TCP but not in UDP. |
| Players cannot reach the server at all | Check HttpPort from outside your network, and that players use ip:HttpPort. See Go public. |
| A resource does not start | The 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 start | Another instance is running. To run two servers, give each one its own folder, HttpPort and GamePort. |
Tune server.cfg, learn the console and admin panel, go public, and write a resource.
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.
# 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=Valueper line. Spaces around the key and the value are ignored. A line starting with#or;is a comment. - Key names are case-sensitive:
GamePort, notgameport. When a key appears twice, the last line wins. - Booleans:
true/false,yes/no,on/offor1/0, in any case. - Lists: comma-separated values; an empty value means an empty list.
- Text (
Name,Description, Discord texts):\n,\r,\tand\\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:
| Problem | What the log says | What the server does |
|---|---|---|
| Invalid value (type, range, malformed list) | [server.cfg] line 12: 'MaxPlayers' = 'lots' is invalid (expected β¦), using default 64 | Uses 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 HttpPort | HttpPort (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=value | Ignores the line. |
| Missing file | server.cfg created with default settings | Writes a commented file with every default. |
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
| Key | Type | Default | Range / values | Description |
|---|---|---|---|---|
Eula | bool | false | true accepts the LS:MP gameserver EULA (eula.txt). The setup page writes it for you. | |
Name | text | LS:MP Server | up to 256 UTF-8 bytes | Display name in the server browser. |
Description | text | empty | up to 16384 UTF-8 bytes | Shown under the name. Use \n for a new line. |
MaxPlayers | int | 64 | 1..4096 players | Maximum connected players. Capped at startup by the plan of the server's owner, with a line in the log. |
Map | enum | mp | mp \| sp | The world players load: mp is the multiplayer map, with every multiplayer location; sp is the story-mode map. |
Token | text | empty | printable ASCII | Your private LS:MP network token, from My Servers. Never share it. See Go public. |
PublicList | bool | false | Advertise the server in the public server browser. Needs a valid Token. Switched from the admin panel on a linked server, it applies at once. | |
LsmpNetwork | bool | true | Link 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. | |
AutoUpdate | bool | true | Install new server versions by itself once no player has been connected for 5 minutes. Applies at once from the admin panel. See Updates. | |
UpdateChannel | text | stable | a-z, 0-9 and - | Release channel of the self-updater. Change it only if LS:MP asks you to. |
Network and ports
| Key | Type | Default | Range / values | Description |
|---|---|---|---|---|
GamePort | port | 9530 | 1..65535 | Game port, TCP and UDP. Must differ from HttpPort. |
HttpPort | port | 2086 | 1..65535 | HTTP port, TCP: the address players join, the downloads, the admin panel (/lsadmin) and the HTTP routes of your resources. |
PublicAddress | text | empty | IP:port or [IPv6]:port | Address 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. |
ClientIdleTimeoutSec | uint | 15 | 0..86400 s | Seconds without traffic before a player is disconnected. 0 turns the check off. |
MaxTcpConnectionsPerIp | uint | 16 | 0..4294967295 | Simultaneous game TCP connections per source IP. 0 = no limit. |
MaxPkgStreamsPerIp | uint | 4 | 0..4294967295 | Simultaneous package downloads per source IP. 0 = no limit. |
MaxPkgStreams | uint | 0 | 0..4294967295 | Simultaneous package downloads in total. 0 = max(64, 2 Γ MaxPlayers). |
Players and protection
| Key | Type | Default | Range / values | Description |
|---|---|---|---|---|
RequireAdmission | bool | true | Players need a valid admission from LS:MP to join. Turn it off only for development or a LAN. | |
AllowGuests | bool | true | Let 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. | |
VerifyLsmpIntegrity | bool | false | Have LS:MP verify every joining player. Needs a Token and the matching subscription. | |
PermsTrustDeclaredIds | bool | false | Let 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. | |
MaxClientPayloadBytes | uint | 4194304 | 65536..268435456 bytes | Largest single request from an authenticated client. |
MaxPreAuthPayloadBytes | uint | 1024 | 0, or 512..MaxClientPayloadBytes bytes | Largest request before authentication. 0 = same as MaxClientPayloadBytes. |
MaxClientSendQueueBytes | uint | 67108864 | 0..4294967295 bytes | Outgoing bytes queued per player. 0 = no limit. |
ScriptEventBytesPerSec | uint | 1048576 | 0..4294967295 bytes/s | Budget 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. |
MetaMaxKeys | uint | 256 | 0..65535 | Meta keys a client may write per player or entity. 0 = no limit. |
MetaMaxBlobBytes | uint | 65536 | 0..4294967295 bytes | Meta bytes a client may write per player or entity. 0 = no limit. |
MetaMaxEntriesPerWrite | uint | 256 | 0..65535 | Meta entries in one client write. 0 = no limit. |
MetaWriteBytesPerSec | uint | 65536 | 0..4294967295 bytes/s | Meta written by each client, with a 4-second burst. 0 = no limit. |
MaxCreatedEntitiesPerPlayer | uint | 2048 | 0..65535 | Living entities created by one client. 0 = no limit. |
MaxAdoptedPerPlayer | uint | 48 | 0..65535 | Ordinary entities simulated by one client. 0 = no limit. |
Peer-to-peer and sync
| Key | Type | Default | Range / values | Description |
|---|---|---|---|---|
P2P | bool | true | Nearby players exchange movement updates directly over UDP; the server keeps authority. | |
P2PMaxPeers | uint | 16 | 1..64 peers | Direct peers per player (the closest ones). More peers mean more upload for each player. |
P2PRangeMeters | uint | 250 | 50..1000 m | Two players link up when they are closer than this. |
MaxSyncRateHz | uint | 60 | 15..120 Hz | Highest rate at which a player may send each entity's state. Clients normally send at 40 Hz. |
World
| Key | Type | Default | Range / values | Description |
|---|---|---|---|---|
DefaultDimension | uint | 0 | 0..65535 | Dimension every new player lands in. 0 is the shared world. |
DefaultDimensionPopulation | bool | true | Ambient population is allowed in dimensions unless a script says otherwise. | |
DefaultDimensionClientEntities | bool | true | Whether 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. | |
PickupSync | bool | true | Dropped weapons, cash and other pickups are shared by every player, and the server decides who collects them. | |
PickupLifetimeSec | uint | 180 | 0..86400 s | Time 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.
| Key | Type | Default | Range / values | Description |
|---|---|---|---|---|
Population | bool | false | Turns synchronized ambient population on. The dimension policy also applies. | |
PopulationVehicles | bool | true | Moving traffic. | |
PopulationParked | bool | true | Parked vehicles. | |
PopulationPeds | bool | true | Walking pedestrians and animals. | |
PopulationScenario | bool | true | Scenario pedestrians (sitting, workingβ¦). | |
PopulationVehicleDensity | float | 1 | 0..1 | Requested moving-vehicle density. Clients lower it to fit their budgets. |
PopulationParkedDensity | float | 1 | 0..1 | Requested parked-vehicle density. |
PopulationPedDensity | float | 1 | 0..1 | Requested pedestrian density. |
PopulationScenarioDensity | float | 1 | 0..1 | Requested scenario density. |
PopulationBudgetPeds | uint | 140 | 0..1000 | Pedestrians a client keeps in total: players, scripts and population. |
PopulationBudgetVehicles | uint | 120 | 0..1000 | Vehicles a client keeps in total: scripts and population. |
PopulationBudgetObjects | uint | 2500 | 0..60000 | Object count at which population thins out. 0 ignores objects. |
PopulationMaxOwned | uint | 96 | 0..1000 | Population entities simulated by one client. 0 = no limit. |
PopulationReserveIds | uint | 64 | 16..255 | IDs reserved per client to create population without waiting for the server. |
PopulationRangeMeters | float | 400 | 250..800 m | Distance at which players receive population generated by other players. |
PopulationAreaVehicles | uint | 120 | 0..1000 | Population vehicles within 160 m. Keep it at least at the client vehicle budget. 0 = no cap. |
PopulationAreaPeds | uint | 160 | 0..1000 | Population pedestrians within 160 m. Keep it at least at the client pedestrian budget. 0 = no cap. |
PopulationCreateRatePerSec | uint | 60 | 1..1000 /s | Population creations per second per player. |
PopulationCrowdStart | uint | 8 | 0..4095 players | Nearby players at which population starts thinning out. |
PopulationCrowdEnd | uint | 32 | 0..4096 players | Nearby 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.
| Key | Type | Default | Range / values | Description |
|---|---|---|---|---|
DiscordPresence | bool | true | Show this server in the player's Discord profile. | |
DiscordJoinable | bool | true | Offer a Join button. Players must also allow sharing the server address. | |
DiscordAppId | text | empty | decimal ID | Your own Discord application, for your own branding. Needs the matching subscription. |
DiscordLargeImage | text | empty | asset key (32 bytes) or https:// URL | Large image. |
DiscordLargeText | text | empty | up to 128 UTF-8 bytes | Tooltip of the large image. |
DiscordSmallImage | text | empty | asset key (32 bytes) or https:// URL | Small image. |
DiscordSmallText | text | empty | up to 128 UTF-8 bytes | Tooltip of the small image. |
DiscordButtonLabel | text | empty | up to 32 UTF-8 bytes | Label of a link button, shown when there is no Join button. |
DiscordButtonUrl | text | empty | https:// URL, up to 512 bytes | Target of that button. |
DiscordLinkHosts | list | empty | 8 domains at most | Domains (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.
| Key | Type | Default | Range / values | Description |
|---|---|---|---|---|
LuaMemoryLimitMiB | uint | 256 | 0..1048576 MiB | Memory quota of each Lua resource. 0 = no quota. Applies when a resource starts. |
JsHeapLimitMiB | uint | 0 | 0..1048576 MiB | JavaScript heap shared by all server JS resources. 0 = sized from the machine's memory. |
Sandbox | bool | true | Sandbox for server resources, Lua and JavaScript. false trusts every resource with full machine access. | |
SandboxAudit | bool | false | Log restricted operations instead of refusing them. For diagnosis only. | |
SandboxWatchdogSec | uint | 10 | 0..3600 s | Seconds 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. |
SandboxFsRead | list | empty | folders | Extra folders sandboxed resources may read, absolute or relative to the server. Write paths as they are, without escaping backslashes. |
SandboxFsWrite | list | empty | folders | Extra folders they may read and write. Their own data folder is always allowed. |
SandboxNetConnect | list | * | rules | Outgoing connections they may open. * allows everything, an empty list nothing. An invalid list allows nothing. |
SandboxNetListen | list | empty | IP:port, port, CIDR, unix:/path, pipe:name | Sockets they may listen on. Empty allows none. |
SandboxEnv | list | NODE_ENV, TZ, LANG, LC_ALL | names; a trailing * matches a prefix | Environment variables they can see. Empty hides all. |
Resource lifecycle and console
| Key | Type | Default | Range / values | Description |
|---|---|---|---|---|
ResourceStartTimeoutMs | uint | 30000 | 1000..600000 ms | Longest wait for the top-level awaits of a starting resource. Past it, the resource is marked failed. |
ResourceStopGraceMs | uint | 2000 | 0..30000 ms | Time given to the resourceStop handlers of a stopping resource. |
ShutdownGraceMs | uint | 5000 | 0..60000 ms | Time given to resources at shutdown (serverStop handlers, pending MySQL queries) before they are stopped anyway. |
PreConnectionTimeoutMs | uint | 10000 | 1000..19000 ms | Deadline of the playerPreConnection verdict. A handler that answers later refuses the player. |
ConsoleStdin | bool | true | Read console commands from the terminal. Set false under a service manager that closes the input. |
Admin panel
| Key | Type | Default | Range / values | Description |
|---|---|---|---|---|
AdminLsmpIds | list | empty | decimal LS:MP IDs | Who may sign in to /lsadmin with Continue with LS:MP, besides the server's owner. Read at each sign-in. |
AdminPublicUrl | text | empty | http(s):// origin | Address 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:
- It keeps a copy
The original file is saved next to it as
server.cfg.bak. - It rewrites the file
Each old key line gets its new name and keeps its value.
ClientIdleTimeoutMsis converted to seconds (rounded up), andRoutingBucketLockdownbecomesoff(0) orstrict(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. - 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 key | Key now |
|---|---|
PlayPort | GamePort |
Port | HttpPort |
SemiP2P, SemiP2PMaxPeers, SemiP2PRange | P2P, P2PMaxPeers, P2PRangeMeters |
MaxSyncRate | MaxSyncRateHz |
LuaMemoryLimitMb | LuaMemoryLimitMiB |
ScriptHeapLimitMb | JsHeapLimitMiB |
ClientIdleTimeout, ClientIdleTimeoutMs | ClientIdleTimeoutSec |
RoutingBucket, RoutingBucketPopulation, RoutingBucketLockdown, DefaultDimensionLockdown | DefaultDimension, DefaultDimensionPopulation, DefaultDimensionClientEntities |
PickupLifetime | PickupLifetimeSec |
PopulationRange, PopulationCreateRate | PopulationRangeMeters, PopulationCreateRatePerSec |
SandboxWatchdog | SandboxWatchdogSec |
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.
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
| Command | What it does |
|---|---|
help [command] | Lists the built-in commands, or explains one. |
status | Server version, uptime, ports, players connected / maximum, resources counted by state, and the memory of the server process (Lua and JS hosts included). |
players | Connected players: player ID, name, LS:MP ID (or guest), dimension, ping (- until measured), time connected. |
resources | Every 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. |
> 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,restartorrefresh: resources start with the server and run until it stops. Typed anyway, they printunknown 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:
registerCommandraises.
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.
-- 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)// 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.
- 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. - Work in the tabs
Monitor, moderate and reconfigure without touching the shell: see the table below.
- 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.
| Tab | What it does |
|---|---|
| Overview | Live CPU, memory and network of the server. The version in the sidebar checks for updates. |
| Players | Connected 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. |
| Benefits | The in-game benefits sold for this server, and their deliveries. |
| Network | How full the network ID space is, and a list of network entities. |
| Statistics | History charts, sampled every minute, from the last hour to two years. |
| P2P Map | With P2P on: which players exchange their updates directly. |
| Resources | Every 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. |
| Console | The live log, with severity filters, a History mode for earlier sessions, and a command box that runs the console commands. |
| Permissions | Groups, members, online players, checks and the journal: see Permissions. Every change applies at once. |
| Settings | A 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). |
| Administration | Who may sign in: AdminLsmpIds and the local accounts. |
| Restart / Shutdown | Restart the server in place, or stop it cleanly. |
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.
| Problem | Fix |
|---|---|
| Lost access to the panel | Stop 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-in | Too many failed logins from your address: wait, then try again. |
| A switch of the Resources tab did nothing | It 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.
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.
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.
| Key | Default | Protocol | Carries |
|---|---|---|---|
HttpPort | 2086 | TCP | The address players join, resource downloads, the admin panel, your resources' HTTP routes. |
GamePort | 9530 | TCP and UDP | The game session: movement, events, voice. |
- 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 terminalnetsh 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=9530bashLinux, with ufwsudo ufw allow 2086/tcp sudo ufw allow 9530/tcp sudo ufw allow 9530/udpbashLinux, 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 - Forward the ports (home connection)
Behind a home router, forward
2086TCP and9530TCP and UDP to this machine's local address. If the address players should use is not the one the server sees (NAT, reverse proxy), setPublicAddress=<public-ip>:2086inserver.cfg. - 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=inserver.cfg, then restart. The token identifies your server on the LS:MP network: keep it secret, never commit it to a repository. - Turn the listing on
Switch Public listing on in Settings: on a linked, running server it applies at once. Setting
PublicList=trueby hand applies at the next start. Without it, the server runs fine and players reach it by address. - 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
| Symptom | Cause and fix |
|---|---|
| Nobody can reach the server | HttpPort is closed from outside, or players use the game port. Test http://<public-ip>:2086/lsadmin from another network. |
| Players connect, then nothing moves | GamePort is open in TCP but not in UDP. |
| Friends on the Internet are refused, players on the LAN are fine | Behind NAT the server does not know its public address: set PublicAddress. |
| The server is not in the browser | PublicList=true needs a valid Token the server started with. Look for Token or listing errors in the log. |
MaxPlayers is lower than set | It is capped by the plan of the server's owner. |
Give yourself the admin rights (Permissions), secure the admin panel, and check RequireAdmission is on: it is the default.
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.
- 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). - 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.
- 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. - 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.
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 want | Do this |
|---|---|
| Updates whenever the server is empty | Nothing: AutoUpdate=true is the default. |
| To pick the moment yourself | Set 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 you | Set 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.cfgthat changed name is migrated by itself; anything the server cannot use is reported with its line.
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.ydrJavaScript 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.ydrLua only:
{
"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:
{
"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 withlsmp-orlsmp_, 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'. titlein 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
| Key | Type | Default | What it does |
|---|---|---|---|
title | string | the resource name | Display name, up to 64 characters. Never an identity. |
description | string | "" | Display only, up to 1024 characters. |
author | string | "" | Display only, up to 128 characters. |
version | string | "" | Display only, up to 64 characters. Marketplace versions are managed by lsmp.gg. |
shared_scripts | string \| string[] | [] | Scripts run on both sides, before the side-specific ones. |
server_scripts | string \| string[] | [] | Scripts run on the server: .lua, .js, .mjs, .cjs. Never sent to players. |
client_scripts | string \| string[] | [] | Scripts run in each player's game: .lua or .js, in this order. |
files | string \| string[] | [] | Extra files sent to players, not run: data read with lsmp.readResourceFile, modules loaded with require. |
webui | string \| string[] | [] | Folders served to the resource's pages at rsc://<name>/ (below). |
dependencies | string \| string[] | [] | Resources that must be started first, on both sides. |
server_dependencies | string \| string[] | [] | Same, on the server only. |
client_dependencies | string \| string[] | [] | Same, in the player's game only. |
data_files | array | [] | Game data files mounted in the player's game with the resource: "data/vehicles.meta", or { "path", "type", "set", "language" } (below). |
stream_sets | array | [] | 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,.svnand.hgfolders are never sent to players. The server keeps thenode_modulesat the root and underserver/.
Scripts and their order
- On each side,
shared_scriptsrun 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
startedwhen every file has run to its end, or to its first wait (lsmp.wait, a pending call). A file that raises makes the whole resourcefailed. - On the server, a resource may mix
.luaand.jsfiles. 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 withlsmp.emitandlsmp.call. - Client scripts can be
.luaor.jstoo, 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.
{
"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" }
]
}| Field | Meaning |
|---|---|
path | The file, relative to the resource. Required. |
type | The game's data file type (VEHICLE_METADATA_FILE, CARCOLS_FILEβ¦). Deduced from the file name when absent. |
set | Name of a stream set: the file is mounted and unmounted with that set instead of the resource. |
language | For 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.
{
"title": "My island",
"client_scripts": "client/main.lua",
"stream_sets": [
{ "name": "club", "folder": "stream/night_club", "load": "manual" },
{ "name": "winter", "folder": "stream/winter" }
]
}| Field | Type | Default | Meaning |
|---|---|---|---|
name | string | required | The set's name for scripts: 1 to 64 characters among a-z, 0-9, _ and -, unique in the resource. |
folder | string | required | Folder relative to the resource root, like every path of the manifest, and inside stream/: "stream/night_club"; "stream" is the whole stream/. |
load | string | "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/mapandstream/map/nightcutsnightout ofmap. - A resource holds at most 256 sets. A name declared twice keeps the first.
Dependencies
- By exact resource name.
dependenciesapply to both sides;server_dependenciesandclient_dependenciesto one side only, so the player's game never waits for a server-only resource. - A dependency that is missing, disabled in
resources.jsonor failed keeps the resource from starting: it isfailed, with a message such asdependency '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
afterinresources.json.
Mistakes and warnings
| In manifest.json | What happens |
|---|---|
| Invalid JSON | The resource does not start: resource 'shop': manifest.json is not valid JSON (line 7, column 3), not loaded. |
| Unknown key | Warning, key ignored: 'client_script' is not a manifest key, ignored (did you mean 'client_scripts'?). |
| Key of the wrong type | Warning, key ignored: 'dependencies' must be a string or an array of strings, ignored. |
| Key that no longer exists | Warning, key ignored, with what to use (table below). |
No manifest.json | Only 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 deeply | The resource does not start. |
| Key | Use instead |
|---|---|
name | Nothing: 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_script | client_scripts, server_scripts, shared_scripts. |
dependency | dependencies (a string is accepted). |
scripts | List scripts in client_scripts, server_scripts or shared_scripts. |
webui_dirs, webui_domain | webui. Pages are always served at rsc://<resource name>/. |
files_mount | data_files. |
stream-sets | stream_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.
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.
{
"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
| Field | Type | Default | Meaning |
|---|---|---|---|
enabled | boolean | true | false: the resource is not packed, not started, and not sent to players. |
sandbox | boolean | true | false trusts the resource: its server scripts get full machine access and lsmp.mysql. Only for code you trust. See Capabilities and sandbox. |
clientMount | string | "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). |
after | string[] | [] | 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 change | It applies |
|---|---|
| Any field, from the admin panel | At the next server start. The panel shows a banner until then. |
| The file, by hand | At the next server start: resources and their settings are read once, when the server starts. |
Mistakes
| Problem | What happens |
|---|---|
| Unknown field | resources.json: 'shop': unknown setting "autoMount", ignored. |
| Wrong type | resources.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 JSON | Every resource uses the defaults, and the file is left as it is so that you can fix it. |
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.
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.
| Lua | JavaScript | |
|---|---|---|
| Server | Lua 5.5 | Node.js 24: CommonJS and ES modules, Node core modules, npm packages |
| Client | Lua 5.5 | V8, without Node: plain scripts, no Node modules |
| Isolation | one Lua state per resource | one 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 (3and3.0are different values). Use//for integer division. Vector3is a built-in value type of the engine, with fields.x,.yand.z(32-bit floats). Functions accept a plain{x, y, z}table as well.printislsmp.log.- The standard library functions that reach outside the resource (
io,os.execute,load,debug...) raise an error that names thelsmpalternative (lsmp.fs,lsmp.readResourceFile).debug.tracebackworks.
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.
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.
local M = {}
function M.format(n) return ("$%d"):format(n) end
return Mlocal money = require("lib.money")
lsmp.log(money.format(1500))JavaScript
console.log,info,warn,erroranddebuggo to the resource's log (see Logging).- Asynchronous
lsmpfunctions return Promises: useasync/await. Anasyncfunction is the JavaScript equivalent of a Lua thread. - Timers are the standard
setTimeout/setInterval/clearTimeout/clearInterval. On the server they are Node timers (Timeoutobjects); 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 apackage.json) both work, with Node's rules. requireandimportlook in the resource first, including anode_modulesfolder shipped inside the resource; then in Node's core modules and in npm packages installed next to the server.__filenameand__dirnameare paths inside the resource (/<resource>/server/main.js), not disk paths: read your own files withlsmp.readResourceFile, and write files inlsmp.getDataPath().- The process belongs to the server:
process.exit()andprocess.abort()raise. In the sandbox, child processes, native addons and internal bindings are refused, andos.tmpdir()is inside the resource's data folder. - An ES module may use top-level
await: the resource reaches"started"when it settles (at mostResourceStartTimeoutMs).
// 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 withlsmp.wait/await lsmp.wait(0). - Memory: each server Lua resource has a quota (
LuaMemoryLimitMiB, default 256 MiB); server JavaScript resources share the heap set byJsHeapLimitMiB. - Budgets are counted per resource: a resource is never cut for the time or memory another resource used. See Limits and quotas.
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
| Need | Tool | Why |
|---|---|---|
| React to the game or the server | lsmp.on("playerJoin", ...) | Engine events, same names on both sides. |
| Fire and forget, one side | lsmp.emit / lsmp.on | Synchronous for handlers in the same language, cheap. |
| Fire and forget, across the network | lsmp.emitServer β lsmp.onClient, lsmp.emitClient β lsmp.onServer | Ordered, no answer. |
| Ask and wait for an answer | lsmp.callServer, lsmp.callClient, lsmp.call β lsmp.onCall | One result or one error code, with a deadline. |
| Share a state everyone reads | Meta | Replicated, late joiners see it, metaChange notifies. |
A request from a client
- 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"); - The server checks everything
On the server, the first argument of an
onClienthandler 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); }); - 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) endjsJavaScript// 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.
-- 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)// 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}`);
}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.
-- 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" })// 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
sourcein a serveronClientoronCallhandler 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. Uselsmp.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.waitand 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.
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.
| Storage | Lives | Who reads it | Good for | Reference |
|---|---|---|---|---|
| Meta | until the player leaves, the entity is deleted or the server stops | every script, server and clients | state players see: job, team, fuel, a door lock | Meta |
| Storage | on disk, forever | the resource itself, on the server | settings, counters, small records per account | storage |
| MySQL | in your database | anything that connects to it (website, other servers) | large or relational data, data shared with a website | MySQL |
| Files | on disk | the resource (data folder), the operator | logs, exports, generated files | Files |
| Resource files | shipped with the resource, read-only | the resource | configuration, translations, templates | lsmp.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
- Load on join
Read the account's record and expose what clients need as meta.
luaLualsmp.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)jsJavaScriptlsmp.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); }); - Save on leave
In
playerLeave, the leaving player's account and meta are still readable.luaLualsmp.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)jsJavaScriptlsmp.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, }); }); - 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.luaLualsmp.on("resourceStop", function(name) if name == lsmp.getResourceName() then lsmp.storage.flush() end end)jsJavaScriptlsmp.on("resourceStop", async (name) => { if (name === lsmp.getResourceName()) await lsmp.storage.flush(); });
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.
- Create the pool onceluaLua
local db = lsmp.mysql.createPool({ user = "game", password = "secret", database = "lsmp" })jsJavaScriptconst db = lsmp.mysql.createPool({ user: "game", password: "secret", database: "lsmp" }); - Load and saveluaLua
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)jsJavaScriptlsmp.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.
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.
- Put the page in a webui folder
Declare the folder in the manifest. Its content is served at
rsc://<resource name>/: hereweb/index.htmlisrsc://hud/index.html.Lua only:
resources/ ββ hud/ ββ manifest.json ββ client/ β ββ main.lua ββ web/ ββ index.html ββ style.css ββ app.jsJavaScript only:
resources/ ββ hud/ ββ manifest.json ββ client/ β ββ main.js ββ web/ ββ index.html ββ style.css ββ app.jsLua 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" } - 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.lualocal hud = lsmp.createBrowser("rsc://hud/index.html") hud:on("load", function() hud:emit("money", 1500) end)jsclient/main.jsconst hud = lsmp.createBrowser('rsc://hud/index.html'); hud.on('load', () => { hud.emit('money', 1500); }); - Listen in the page
lsmpis 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.csshtml, 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.jslsmp.on('money', (amount) => { document.getElementById('money').textContent = `$${amount.toLocaleString()}`; }); - 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 want | Script side | Page side |
|---|---|---|
| Push data to the page | browser:emit("money", 1500) | lsmp.on('money', fn) |
| Tell the script something happened | browser:on("close", fn) | lsmp.emit('close') |
| Ask the script, wait for the answer | browser:on("buy", fn) returns the answer | await lsmp.call('buy', id) |
| Ask the page, wait for the answer | browser:call("getForm") | lsmp.on('getForm', fn) returns the answer |
| Reach the server | The client script calls the server (lsmp.callServer, lsmp.emitServer) and forwards the result | Never directly |
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.
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+Backspaceconst 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+Backspacedocument.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:
zIndexorders 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.
- 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" } - 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 torsc://before you ship: on a server,http://is refused.luaclient/main.lualocal DEV = lsmp.gameType() == "SP" local url = DEV and "http://localhost:5173/" or "rsc://hud/index.html" local hud = lsmp.createBrowser(url)jsclient/main.jsconst DEV = lsmp.gameType() === 'SP'; const url = DEV ? 'http://localhost:5173/' : 'rsc://hud/index.html'; const hud = lsmp.createBrowser(url); - 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
| Symptom | Cause and fix |
|---|---|
createBrowser raises URL refused | http:// on a server, or a typo in the scheme. Use rsc://<resource>/β¦ or https://. |
loadError with http-404 | The 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 nothing | You 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-handler | The script has no browser:on handler for that name on this browser. |
| The game no longer reacts to the keyboard | A page kept the focus. Call setFocus(false) when your menu closes; players can always press Ctrl+Alt+Backspace. |
| Clicks go through the page | It has no focus, or took the keyboard only (cursor set to false): setFocus(true). |
alert does nothing, stored data is missing | 2D 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 game | The page paints a background: set background: transparent on html and body. |
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{
"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" }
]
}| Key | Meaning |
|---|---|
stream_sets[].name | The set's name for scripts: [a-z0-9_-], 1 to 64 characters. |
stream_sets[].folder | Folder 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_files | Game 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.
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.
-- 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)// 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:
invalidateArchivesswitches whole archives of the game off: their maps and collisions disappear, the way a map DLC removes what it replaces.unregisterAssetstakes named assets out, and frees their place in the game's asset stores: that is what makes room for many new models and textures.
- 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.
- Switch the game's pieces off
Call
invalidateArchiveswith every archive of the area in one list, thenunregisterAssetsfor the models and textures you need room for. Ship the lists as JSON files of the resource (filesin the manifest) and read them withlsmp.readResourceFile. - 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.
- Undo
Stopping the resource that made the changes restores the archives it switched off. Leaving the server restores everything.
-- 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)// 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}`));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
| Symptom | Cause |
|---|---|
| A replaced model still shows the old one | The old model is still in use: an entity draws it, or a script requested it. It switches once released. |
unregisterAssets reports failed > 0 | Those names are in use, or no asset has that name. Check the names with getAssetState. |
loadStreamSet rejects with not-found | The 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 ground | A collision (.ybn) or a map was removed under them. Do the swap behind a loading screen. |
An archive counts in failed | It is a data archive, not a streaming one, or its name is not the one the game registered. |
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.
- Drop your folder
Create
resourcesnext 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/ - 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.
- 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.jsonkeeps the resource from mounting, and My mods says why, with the line and column.
| On a server | Local folder | |
|---|---|---|
| Content | Frozen when the server packs it | Read from the disk each time the resource is mounted |
| On or off | enabled in the server's resources.json | The switch in My mods |
| Server scripts | Run | Ignored |
| Page addresses | rsc:// and https:// | Also http://localhost, for a dev server with hot reload |
| DevTools | For developers the server allows | Always, 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.
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)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,.ytdor.ymapof 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
mountResourceandunmountResource, 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.
| Key | Deduced from |
|---|---|
title | The folder name. |
shared_scripts, client_scripts, server_scripts | The usual folders (shared/, client/, server/) as patterns; elsewhere, a script filed by its folder (src/client/x.js) or its name (cl_*, sv_*, sh_*). |
files | What client/ and shared/ hold besides code. |
data_files | Game metadata recognised by its name (vehicles.meta, handling.metaβ¦), and the data file lines of a FiveM fxmanifest.lua. |
webui | The 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.luaat the root) is not declared, and aconfig.jsonat the root is not added tofiles. - 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 intostream/. - 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.
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
| From | Read it in |
|---|---|
Server scripts, server packaging, server.cfg | The 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 scripts | The client console: F8 in game. |
| Web pages | The page's own console, in DevTools. |
- Every line written by a resource starts with its name:
[shop] β¦. Uselsmp.log,lsmp.warn,lsmp.errorandlsmp.debug;lsmp.setLogLevelhides 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/falseon a run-time failure leaves its code inlsmp.getLastError(). Codes are listed in Error codes. resourcesin the server console lists every resource with its state:started,failed,stoppedβ¦
A fast loop
- Run a local server
On your own machine, with
RequireAdmission=falseandPublicList=false, so you can join it at127.0.0.1:2086. - Edit, then restart the server
The server reads its resources once, when it starts: after a change, restart it (
quitin its console, then start it again) and join again. For client scripts and pages, local resources reload in seconds in Story mode. - Read both consoles
The server console for the server half, F8 for the client half, DevTools for pages.
- 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
| Message | Cause and fix |
|---|---|
resource folder 'MyShop' is not a valid name (β¦): use 'myshop', not loaded | Rename the folder: names are lowercase. |
resource 'shop': manifest.json is not valid JSON (line 7, column 3), not loaded | A 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 ignored | Scripts 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 files | A script raised while loading. Everything the resource had registered is removed; fix the file and restart the server. |
A resource is failed after 30 seconds | A top-level await never finished: ResourceStartTimeoutMs (server.cfg). |
resource 'x' is disabled in resources.json | Set "enabled": true in resources.json, then restart the server. |
| A server script is refused a file, a connection or a module | The 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 seconds | It 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 out | A playerPreConnection handler did not answer within PreConnectionTimeoutMs. The warning names the resource. |
| Events from a client stop arriving under heavy use | That player went over ScriptEventBytesPerSec: excess events are dropped. Send less, or less often. |
A call (call, callServer, callClient) fails with no-handler | No 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-404 | See 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 is | DevTools |
|---|---|
| Story mode, local resources | Always allowed. |
| On a server | Only 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. |
- On a server, allow yourself
Put yourself in a group with
lsmp.devtoolsin the Permissions tab of the admin panel, or mark your developers from a server script:luaserver/main.lualocal 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.jsconst DEVELOPERS = new Set([1234567]); // LS:MP IDs lsmp.on('playerJoin', (playerId) => { if (DEVELOPERS.has(lsmp.getPlayerLsmpId(playerId))) { lsmp.setPlayerDev(playerId, true); } }); - Press Ctrl+Shift+I in game
Or type
devtoolsin 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. - 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 as | What 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 #id | One entry per 3D browser. |
| Console command (F8) | What it does |
|---|---|
devtools | Opens 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 status | Whether you are allowed, whether the access is open and where, and how many pages are listed. |
devtools close | Closes 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.
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 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 mod | Paid mod or subscription | |
|---|---|---|
| Where | lsmp.gg β your profile β My creations β Publish mod | On Summum, the LS:MP store: create the product there. Your Summum mods are also listed in My creations, with a link to manage them. |
| Upload | The same uploader, the same checks | The same uploader, the same checks |
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.jsonat 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,.gitand 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
- 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. - Media
Images and videos for the mod's page; the first one is the cover. Optional: you can add them later from My creations.
- Folder
Drop the folder, or browse to it. The upload is encrypted.
- 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.
- 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.
- 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.jsonmust 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
resourcesconsole list as amod. Its resource name, the one scripts see (lsmp.getResourceName(),rsc://, dependencies, logs), is its slug followed by its mod id:las-venturas-41for the modlas-venturaswith id 41. - Its settings in the server's
resources.jsonand its data (data folder, storage, capabilities) are keyedmod.<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.
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.
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
.asiplugin. - 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.
| Default | To change it | |
|---|---|---|
| Position | Legion Square: 195.0, -933.7, 30.7, heading 145 | setEntityCoordsNoOffset, setEntityHeading: below |
| Health | Invincible | setPlayerInvincible(playerId(), false) |
| Wanted level | Capped at 0 | setMaxWantedLevel |
| Clock | 13:00, paused | setClockTime, pauseClock(false) |
| Weather | EXTRASUNNY, persistent | setWeatherTypeNowPersist, clearWeatherTypePersist |
| Death, arrest | If 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.
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)
endif (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);
}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.
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.
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.
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.
- 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-monthorcash-100k(lowercase letters, digits and hyphens between words). Restart the server once after its first benefit: selling is switched on at start. - 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.
- Apply it
When the buyer is connected, the
benefitGrantevent gives your server script the purchase, wherever it was bought. Apply it in your own data (a rank, a balance...). - Confirm it
Call
lsmp.benefits.consumewith the purchase id once your change is saved. Until then, the purchase is presented again at each of the player's sessions.
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.
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
| Status | Meaning | Your script |
|---|---|---|
pending | Paid, not yet received by this server. | Apply it, then consume. |
delivered | Received by this server. | Apply it, then consume. |
consumed | Applied and confirmed. | Nothing. |
revoked | Refunded before it was confirmed. | Nothing to take back. |
revoking | Refunded after it was confirmed. | Take it back, then consumeRevocation. |
reversed | Taken back and confirmed. | Nothing. |
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 Β· JSlsmp.benefits.fetch(lsmpId [, opts] [, cb]) --> {Benefit}, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
lsmpId | lsmpId | The account: the number from getPlayerLsmpId, or its string form. |
opts opt | BenefitFetchOptions | See BenefitFetchOptions. |
{Benefit}, err: A list of Benefit, or nil and a failure code.Promise<Benefit[]>: Resolves with a list of Benefit; rejects with a failure code.| Failure code | When |
|---|---|
unavailable | This server sells no benefits, or the LS:MP network cannot be reached. |
limit | Too many requests in a short time. |
timeout | No answer in time. |
invalid | The account or the cursor is not valid. |
permission | The resource does not hold benefits.read. |
-- 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// 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 Β· JSlsmp.benefits.consume(id [, lsmpId] [, cb]) --> BenefitConsumeResult, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
id | int | The purchase id. |
lsmpId opt | lsmpId | The account it was applied to. |
BenefitConsumeResult, err: A BenefitConsumeResult, or nil and a failure code.Promise<BenefitConsumeResult>: Resolves with a BenefitConsumeResult; rejects with a failure code.| Failure code | When |
|---|---|
not-found | Not a purchase of this server. |
invalid | Not this account's purchase, or the id is not valid. |
unavailable | This server sells no benefits. |
io | The confirmation could not be written to the server's disk: keep your own record and try again. |
permission | The resource does not hold benefits.consume. |
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)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 Β· JSlsmp.benefits.consumeRevocation(id [, lsmpId] [, cb]) --> BenefitConsumeResult, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
id | int | The purchase id. |
lsmpId opt | lsmpId | The account it was taken back from. |
BenefitConsumeResult, err: A BenefitConsumeResult, or nil and a failure code.Promise<BenefitConsumeResult>: Resolves with a BenefitConsumeResult; rejects with a failure code.| Failure code | When |
|---|---|
not-found | Not a purchase of this server. |
invalid | The purchase is not refunded, or not this account's. |
unavailable | This server sells no benefits. |
io | The confirmation could not be written to the server's disk. |
permission | The resource does not hold benefits.consume. |
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)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.
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 Β· JSlsmp.createCart() --> Cartlsmp.createCart(): CartCreate 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.
Cart: A new, empty cart, in the "idle" state.cart.add
ClientLua Β· JScart:add(key [, quantity]) --> Cartcart.add(key: string, quantity: number = 1): CartAdd 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).
| Parameter | Type | Description |
|---|---|---|
key | string | The benefit server key, exactly as set in the product editor (for example "vip-month"): 1 to 63 letters, digits, _ or -. Case matters. |
quantity opt | int | How many to add, 1 to 99. Default: 1 |
Cart: The cart itself, so that calls can be chained.cart.remove
ClientLua Β· JScart:remove(key) --> booleancart.remove(key: string): booleanRemove a benefit line.
| Parameter | Type | Description |
|---|---|---|
key | string | The key of the benefit to remove. |
boolean: true if the benefit was in the cart.cart.clear
ClientLua Β· JScart:clear() --> Cartcart.clear(): CartRemove every benefit.
Cart: The cart itself, so that calls can be chained.cart.getItems
ClientLua Β· JScart:getItems() --> {CartItem}cart.getItems(): CartItem[]The lines of the cart, in the order they were added.
CartItem[]: A list of CartItem, new on each call: changing it does not change the cart.cart.getState
ClientLua Β· JScart:getState() --> stringcart.getState(): stringWhere the cart stands.
string: "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 Β· JScart:open([cb]) --> string, errcart.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:
string, err: "player", "script" or "error"; nil and a code when the window could not be shown.Promise<string>: Resolves with "player", "script" or "error"; rejects with a code when the window could not be shown.| Code | Meaning |
|---|---|
invalid | The cart is empty, or a key is not a benefit on sale on this server. |
limit | This cart, or another one, already has a window open or being prepared; or too many openings or purchases in a short time. |
denied | The player is a guest or not signed in to LS:MP, or the opening was cancelled by cart.close. |
unavailable | The 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. |
error | Anything else that kept the window from appearing. |
-- /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)// /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 Β· JScart:close() --> booleancart.close(): booleanClose 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.
boolean: 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.
-- 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)-- /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)// 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}`);
}
});// /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
| Field | Type | Default | Description |
|---|---|---|---|
id | int | β | The purchase id: unique across LS:MP, increasing. Use it to apply each purchase once. |
key | string | β | The key you gave the benefit on lsmp.gg. Ignore the keys your resource does not handle. |
quantity | int | β | How many units were bought. |
purchasedAtMs | epochMs | β | When it was paid. Compute any expiry from it. |
status | string | β | See the life of a purchase. |
BenefitFetchOptions
| Field | Type | Default | Description |
|---|---|---|---|
after | int | 0 | Return only purchases with a greater id (the next page). |
BenefitConsumeResult
| Field | Type | Default | Description |
|---|---|---|---|
id | int | β | The purchase id. |
status | string | β | The status after the call, or "queued" when the confirmation waits for the network. |
applied | boolean | β | false when the purchase was already in that state (a repeated call). |
queued | boolean | β | true when the confirmation is kept and will be sent later. |
CartItem
| Field | Type | Default | Description |
|---|---|---|---|
key | string | β | The benefit server key. |
quantity | int | β | How many, 1 to 99. |
Shared API
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 to | Use |
|---|---|
| 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 answer | lsmp.call / callServer / callClient |
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 Β· JSlsmp.on(name, fn [, filter]) --> functionlsmp.on(name: string, fn: Function, filter?: MetaFilter): () => booleanSubscribes 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.
| Parameter | Type | Description |
|---|---|---|
name | event | Event name. Engine event names are allowed here. |
fn | fn | The handler, fn(...args). |
filter opt | MetaFilter | Only for metaChange: { scope, key, target }. See metaChange. |
function: The unsubscribe function; it returns true if it removed the handler.() => boolean: The unsubscribe function; it returns true if it removed the handler.lsmp.on("shop:purchase", function(playerId, item, price)
lsmp.log(("%d bought %s for $%d"):format(playerId, item, price))
end)lsmp.on("shop:purchase", (playerId, item, price) => {
lsmp.log(`${playerId} bought ${item} for $${price}`);
});lsmp.once
SharedLua Β· JSlsmp.once(name, fn [, filter]) --> functionlsmp.once(name: string, fn: Function, filter?: MetaFilter): () => booleanLike lsmp.on, but the handler is removed just before its first call.
| Parameter | Type | Description |
|---|---|---|
name | event | Event name. Engine event names are allowed. |
fn | fn | The handler, called at most once. |
filter opt | MetaFilter | Only for metaChange. |
function: The unsubscribe function.() => boolean: The unsubscribe function.lsmp.off
SharedLua Β· JSlsmp.off(name, fn) --> booleanlsmp.off(name: string, fn: Function): booleanRemoves 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.
| Parameter | Type | Description |
|---|---|---|
name | event | Event name. |
fn | fn | The registered handler. |
boolean: true if a handler was removed.lsmp.emit
SharedLua Β· JSlsmp.emit(name, ...)lsmp.emit(name: string, ...args: Value[]): voidEmits 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.
| Parameter | Type | Description |
|---|---|---|
name | event | Event name: 1 to 128 bytes of UTF-8, case-sensitive. See Reserved names. |
...args opt | value | Up to 32 transportable values. |
- 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.
-- 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)// 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 Β· JSlsmp.emitServer(name, ...) --> booleanlsmp.emitServer(name: string, ...args: Value[]): booleanSends an event to the server.
Nothing is queued when the client is not in a session: the call returns false.
| Parameter | Type | Description |
|---|---|---|
name | event | Event name: 1 to 128 bytes of UTF-8, case-sensitive. See Reserved names. |
...args opt | value | Up to 32 transportable values. |
boolean: false when not in a session.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.
lsmp.emitServer("chat:send", "hello")lsmp.emitServer("chat:send", "hello");lsmp.onClient
ServerLua Β· JSlsmp.onClient(name, fn) --> functionlsmp.onClient(name: string, fn: Function): () => booleanSubscribes 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).
| Parameter | Type | Description |
|---|---|---|
name | event | Event name (engine event names are refused). |
fn | fn | fn(source, ...args). |
function: The unsubscribe function.() => boolean: The unsubscribe function.-- 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)// 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 Β· JSlsmp.offClient(name, fn) --> booleanlsmp.offClient(name: string, fn: Function): booleanRemoves a client-event handler of this resource.
| Parameter | Type | Description |
|---|---|---|
name | event | Event name. |
fn | fn | The registered handler. |
boolean: true if a handler was removed.From the server to clients
lsmp.emitClient
ServerLua Β· JSlsmp.emitClient(target, name, ...) --> booleanlsmp.emitClient(target: number | number[], name: string, ...args: Value[]): booleanSends an event to one player or to a list of players.
The target comes first, as in callClient.
| Parameter | Type | Description |
|---|---|---|
target | playerId | list | One playerId, or a list of playerIds. |
name | event | Event name: 1 to 128 bytes of UTF-8, case-sensitive. See Reserved names. |
...args opt | value | Up to 32 transportable values. |
boolean: true if at least one target was connected.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.
lsmp.emitClient(playerId, "hud:notify", "Welcome!")
lsmp.emitClient({ 1, 4, 7 }, "race:start", { laps = 3 })lsmp.emitClient(playerId, "hud:notify", "Welcome!");
lsmp.emitClient([1, 4, 7], "race:start", { laps: 3 });lsmp.emitAllClients
ServerLua Β· JSlsmp.emitAllClients(name, ...) --> integerlsmp.emitAllClients(name: string, ...args: Value[]): numberSends an event to every connected player.
| Parameter | Type | Description |
|---|---|---|
name | event | Event name: 1 to 128 bytes of UTF-8, case-sensitive. See Reserved names. |
...args opt | value | Up to 32 transportable values. |
integer: The number of players reached.number: The number of players reached.lsmp.emitAllClients("weather:alert", "storm in 5 minutes")lsmp.emitAllClients("weather:alert", "storm in 5 minutes");lsmp.emitDimensionClients
ServerLua Β· JSlsmp.emitDimensionClients(dimension, name, ...) --> integerlsmp.emitDimensionClients(dimension: number, name: string, ...args: Value[]): numberSends an event to every player currently in a dimension.
| Parameter | Type | Description |
|---|---|---|
dimension | dimension | The dimension, 0..65535. |
name | event | Event name: 1 to 128 bytes of UTF-8, case-sensitive. See Reserved names. |
...args opt | value | Up to 32 transportable values. |
integer: The number of players reached.number: The number of players reached.lsmp.emitDimensionClients(12, "arena:countdown", 3)lsmp.emitDimensionClients(12, "arena:countdown", 3);lsmp.onServer
ClientLua Β· JSlsmp.onServer(name, fn) --> functionlsmp.onServer(name: string, fn: Function): () => booleanSubscribes to an event sent by the server.
| Parameter | Type | Description |
|---|---|---|
name | event | Event name (engine event names are refused). |
fn | fn | fn(...args). |
function: The unsubscribe function.() => boolean: The unsubscribe function.lsmp.onServer("chat:message", function(name, text)
lsmp.log(name .. ": " .. text)
end)lsmp.onServer("chat:message", (name, text) => {
lsmp.log(`${name}: ${text}`);
});lsmp.offServer
ClientLua Β· JSlsmp.offServer(name, fn) --> booleanlsmp.offServer(name: string, fn: Function): booleanRemoves a server-event handler of this resource.
| Parameter | Type | Description |
|---|---|---|
name | event | Event name. |
fn | fn | The registered handler. |
boolean: true if a handler was removed.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.callcalls 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.
| Caller | Function | Handler | Handler receives |
|---|---|---|---|
| any resource, same side | lsmp.call(name, ...) | onCall of this side | server: source = nil/null, then the arguments; client: the arguments |
| client | lsmp.callServer(name, ...) | server onCall | source (the calling player), then the arguments |
| server resource | lsmp.callClient(playerId, name, ...) | that player's client onCall | the arguments |
Rules
- One handler per name and per side, across all resources and both engines: the same handler answers
lsmp.callfrom this side and calls from the other side. A secondonCallwith 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 getstimeout; 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
errorand later calls withno-handler. When the calling resource stops, its pending calls end withcancelled.
| Code | When |
|---|---|
timeout | No answer before the deadline. |
no-handler | Nobody handles this name on the side that was called. |
error | The handler raised, rejected, or returned a value that cannot be sent. |
disconnected | The client is not in a session, or the player left before answering. |
not-found | callClient to a player who is not connected. |
limit | 4096 calls of the resource are already pending, or the request is too large to send. |
cancelled | The calling resource stopped. |
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 Β· JSlsmp.onCall(name, fn) --> functionlsmp.onCall(name: string, fn: Function): () => booleanRegisters 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.
| Parameter | Type | Description |
|---|---|---|
name | event | Callable name (1 to 128 bytes; engine event names and the lsmp: prefix are refused). |
fn | fn | The handler; its return value (or resolved Promise) is the result. |
function: The unregister function.() => boolean: The unregister function.-- 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)// 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 Β· JSlsmp.offCall(name, fn) --> booleanlsmp.offCall(name: string, fn: Function): booleanUnregisters this resource's handler of a name.
Calls already received still answer; later calls get no-handler.
| Parameter | Type | Description |
|---|---|---|
name | event | Callable name. |
fn | fn | The registered handler. |
boolean: true if the handler was removed.lsmp.call
SharedLua Β· JSlsmp.call(name, ... [, cb]) --> any, errlsmp.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).
| Parameter | Type | Description |
|---|---|---|
name | event | CallOptions | The name, or { name, timeoutMs } (timeoutMs 1 to 300 000, default 10 000). |
...args opt | value | Up to 32 transportable values. |
any, err: The handler's result. Failure codes: see Rules.Promise<Value>: The handler's result. Failure codes: see Rules.-- 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// 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 Β· JSlsmp.callServer(name, ... [, cb]) --> any, errlsmp.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).
| Parameter | Type | Description |
|---|---|---|
name | event | CallOptions | The name, or { name, timeoutMs } (timeoutMs 1 to 300 000, default 10 000). |
...args opt | value | Up to 32 transportable values. |
any, err: The handler's result. Failure codes: see Rules.Promise<Value>: The handler's result. Failure codes: see Rules.-- 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// 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 Β· JSlsmp.callClient(playerId, name, ... [, cb]) --> any, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player whose client is called. |
name | event | CallOptions | The name, or { name, timeoutMs }. |
...args opt | value | Up to 32 transportable values. |
any, err: The client handler's result.Promise<Value>: The client handler's result.The request can be up to 16 MiB encoded; the answer from the client up to 4 MiB β 1 KiB.
-- 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// 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);
}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 Β· JSlsmp.log(...)lsmp.log(...values: any[]): voidWrites an information line.
| Parameter | Type | Description |
|---|---|---|
...values opt | any | Values to write, separated by a tab. Strings are written as they are. |
lsmp.log("players online:", #lsmp.getPlayers())lsmp.log("players online:", lsmp.getPlayers().length);lsmp.warn
SharedLua Β· JSlsmp.warn(...)lsmp.warn(...values: any[]): voidWrites a warning line.
| Parameter | Type | Description |
|---|---|---|
...values opt | any | Values to write, separated by a tab. Strings are written as they are. |
lsmp.error
SharedLua Β· JSlsmp.error(...)lsmp.error(...values: any[]): voidWrites an error line. It does not raise.
| Parameter | Type | Description |
|---|---|---|
...values opt | any | Values to write, separated by a tab. Strings are written as they are. |
lsmp.debug
SharedLua Β· JSlsmp.debug(...)lsmp.debug(...values: any[]): voidWrites a debug line, hidden unless the resource's level is "debug".
| Parameter | Type | Description |
|---|---|---|
...values opt | any | Values to write, separated by a tab. Strings are written as they are. |
lsmp.setLogLevel
SharedLua Β· JSlsmp.setLogLevel(level)lsmp.setLogLevel(level: string): voidSets the lowest level written for this resource only.
Errors raised by the resource's handlers are always written, whatever the level.
| Parameter | Type | Description |
|---|---|---|
level | string | "debug", "info" (default), "warn", "error" or "off". |
lsmp.setLogLevel("debug")lsmp.setLogLevel("debug");lsmp.getLogLevel
SharedLua Β· JSlsmp.getLogLevel() --> stringlsmp.getLogLevel(): stringThe current level of this resource ("info" by default).
stringErrors
lsmp.getLastError
SharedLua Β· JSlsmp.getLastError() --> string?lsmp.getLastError(): string | nullThe 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.
string?: A code such as "not-found" or "permission".string | null: A code such as "not-found" or "permission".local ok = lsmp.deleteEntity(netId)
if not ok then lsmp.warn(lsmp.getLastError()) endif (!lsmp.deleteEntity(netId)) lsmp.warn(lsmp.getLastError());Threads and waiting
lsmp.wait
SharedLua Β· JSlsmp.wait([ms])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.
| Parameter | Type | Description |
|---|---|---|
ms opt | ms | Milliseconds to wait. Default: 0 |
lsmp.createThread(function()
while true do
lsmp.emitAllClients("clock:tick", lsmp.nowMs())
lsmp.wait(60000)
end
end)(async () => {
for (;;) {
lsmp.emitAllClients("clock:tick", lsmp.nowMs());
await lsmp.wait(60000);
}
})();lsmp.createThread
SharedLualsmp.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.
| Parameter | Type | Description |
|---|---|---|
fn | fn | The thread body. |
...args opt | any | Arguments 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 Β· JSsetTimeout(fn [, ms, ...]) --> integersetTimeout(fn: Function, ms: number = 0, ...args: any[]): numberCalls fn(...args) once after ms milliseconds.
| Parameter | Type | Description |
|---|---|---|
fn | fn | The callback. |
ms opt | ms | Delay. 0 runs it at the next turn. Default: 0 |
...args opt | any | Arguments passed to fn. |
integer: The timer id (an integer above 0, unique in the resource; a Node Timeout object in JavaScript on the server).number: The timer id (an integer above 0, unique in the resource; a Node Timeout object in JavaScript on the server).local id = setTimeout(function(name) lsmp.log("hello " .. name) end, 1000, "world")const id = setTimeout((name) => lsmp.log(`hello ${name}`), 1000, "world");setInterval
SharedLua Β· JSsetInterval(fn [, ms, ...]) --> integersetInterval(fn: Function, ms: number = 1, ...args: any[]): numberCalls 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.
| Parameter | Type | Description |
|---|---|---|
fn | fn | The callback. |
ms opt | ms | Period. Default: 1 |
...args opt | any | Arguments passed to fn. |
integer: The timer id.number: The timer id.clearTimeout
SharedLua Β· JSclearTimeout([id])clearTimeout(id?: number): voidCancels a timer of this resource.
An unknown id, or the id of another resource's timer, does nothing.
| Parameter | Type | Description |
|---|---|---|
id opt | integer | The timer id. A missing id does nothing. |
clearInterval
SharedLua Β· JSclearInterval([id])clearInterval(id?: number): voidSame function as clearTimeout.
| Parameter | Type | Description |
|---|---|---|
id opt | integer | The timer id. A missing id does nothing. |
lsmp.onTick
ClientLua Β· JSlsmp.onTick(fn) --> functionlsmp.onTick(fn: Function): () => booleanCalls 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.
| Parameter | Type | Description |
|---|---|---|
fn | fn | fn(dtMs). |
function: The unsubscribe function.() => boolean: The unsubscribe function.lsmp.onTick(function(dtMs)
drawText(0.5, 0.05, "FPS: " .. math.floor(1000 / math.max(dtMs, 1)))
end)lsmp.onTick((dtMs) => {
drawText(0.5, 0.05, `FPS: ${Math.floor(1000 / Math.max(dtMs, 1))}`);
});lsmp.offTick
ClientLua Β· JSlsmp.offTick(fn) --> booleanlsmp.offTick(fn: Function): booleanRemoves a tick handler of this resource.
| Parameter | Type | Description |
|---|---|---|
fn | fn | The handler. |
boolean: true if it was removed.Clocks
lsmp.getTickCount
SharedLua Β· JSlsmp.getTickCount() --> integerlsmp.getTickCount(): numberA monotonic clock in milliseconds. Only differences between two values mean something.
integernumberlocal t0 = lsmp.getTickCount()
doWork()
lsmp.debug("took " .. (lsmp.getTickCount() - t0) .. " ms")const t0 = lsmp.getTickCount();
doWork();
lsmp.debug(`took ${lsmp.getTickCount() - t0} ms`);lsmp.nowMs
SharedLua Β· JSlsmp.nowMs() --> integerlsmp.nowMs(): numberThe wall-clock time in milliseconds since the Unix epoch.
Use it for timestamps you store or send (untilMs, atMs...).
integernumberHashing and random
lsmp.hash
SharedLua Β· JSlsmp.hash(name) --> integerlsmp.hash(name: string): numberThe 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.
| Parameter | Type | Description |
|---|---|---|
name | string | The name to hash. |
integernumberif lsmp.getEntityModel(netId) == lsmp.hash("adder") then
lsmp.log("an Adder")
endif (lsmp.getEntityModel(netId) === lsmp.hash("adder")) lsmp.log("an Adder");lsmp.joaat
SharedLua Β· JSlsmp.joaat(name) --> integerlsmp.joaat(name: string): numberAlias of lsmp.hash: same function, same result. Prefer lsmp.hash.
lsmp.randomBytes
SharedLua Β· JSlsmp.randomBytes(n) --> stringlsmp.randomBytes(n: number): Uint8ArrayCryptographically secure random bytes.
Use it for tokens, salts and identifiers that must not be guessed. math.random and Math.random are predictable.
| Parameter | Type | Description |
|---|---|---|
n | integer | Number of bytes, 1 to 65 536. |
string: The bytes.Uint8Array: The bytes.local token = lsmp.randomBytes(16):gsub(".", function(c) return ("%02x"):format(c:byte()) end)const token = Buffer.from(lsmp.randomBytes(16)).toString("hex"); // server (Node)lsmp.bytes
SharedLualsmp.bytes(s) --> BytesLua 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.
| Parameter | Type | Description |
|---|---|---|
s | string | The data. |
Bytes: 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
SharedLualsmp.json.encode(value [, opts]) --> stringLua 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.
| Parameter | Type | Description |
|---|---|---|
value | any | The value. |
opts opt | JsonEncodeOptions | { pretty = false }: indented output. |
stringlocal text = lsmp.json.encode({ name = "Ada", tags = { "admin" } })lsmp.json.decode
SharedLualsmp.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.
| Parameter | Type | Description |
|---|---|---|
text | string | JSON text. |
value | nil, "invalid"local cfg, err, details = lsmp.json.decode(lsmp.readResourceFile("config.json"))
if not cfg then lsmp.error("bad config.json: " .. details.message) endlsmp.json.array
SharedLualsmp.json.array(t) --> tableLua only: marks a table so json.encode writes it as an array, even when empty.
Not available in JavaScript.
| Parameter | Type | Description |
|---|---|---|
t | table | The table. |
table: 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 Β· JSlsmp.getResourceName() --> stringlsmp.getResourceName(): stringThe name of the calling resource.
stringlsmp.getResourceState
SharedLua Β· JSlsmp.getResourceState(name) --> ResourceState?lsmp.getResourceState(name: string): ResourceState | nullThe state of a resource on this side.
| Parameter | Type | Description |
|---|---|---|
name | name | Resource name. |
ResourceState?: "starting", "started", "failed", "stopping" or "stopped"; nil/null if unknown.ResourceState | null: "starting", "started", "failed", "stopping" or "stopped"; nil/null if unknown.if lsmp.getResourceState("mysql-accounts") ~= "started" then
lsmp.warn("accounts are not available")
endif (lsmp.getResourceState("mysql-accounts") !== "started") lsmp.warn("accounts are not available");lsmp.getResources
SharedLua Β· JSlsmp.getResources() --> {ResourceInfo}lsmp.getResources(): ResourceInfo[]Every resource known on this side, in load order.
{ResourceInfo}: A list of { name, state }.ResourceInfo[]: A list of { name, state }.lsmp.readResourceFile
SharedLua Β· JSlsmp.readResourceFile(path [, opts]) --> string|string?lsmp.readResourceFile(path: string, opts?: ReadFileOptions): string | Uint8Array | nullReads 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.
| Parameter | Type | Description |
|---|---|---|
path | string | Path inside the resource, for example "config/shop.json". |
opts opt | ReadFileOptions | { binary = true } returns bytes (Uint8Array in JavaScript; Lua strings hold bytes anyway). |
string?: The content, or nil/null if the file is not in the package.string | Uint8Array | null: The content, or nil/null if the file is not in the package.local prices = lsmp.json.decode(lsmp.readResourceFile("config/prices.json"))const prices = JSON.parse(lsmp.readResourceFile("config/prices.json"));lsmp.resourceFileExists
SharedLua Β· JSlsmp.resourceFileExists(path) --> booleanlsmp.resourceFileExists(path: string): booleanWhether the calling resource's package holds a file.
| Parameter | Type | Description |
|---|---|---|
path | string | Path inside the resource. |
booleanlsmp.gameType
SharedLua Β· JSlsmp.gameType() --> stringlsmp.gameType(): stringThe 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").
stringlsmp.getVersion
SharedLua Β· JSlsmp.getVersion() --> VersionInfolsmp.getVersion(): VersionInfoVersion information.
VersionInfo: { lsmp, game, gameBuild }: the LS:MP version, and on a client the game version and build number (nil/null on the server).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 Β· JSlsmp.ResourceStatelsmp.ResourceStateThe 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"
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.
| Server | Client | |
|---|---|---|
| Schemes | https:// and http:// | https:// only |
| Addresses | Any, 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 flight | Sandboxed resource: 256; more fail with limit | 8 per resource (20 per second), 32 for the whole client, 128 MiB of response bodies held at once; more fail with limit |
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 Β· JSlsmp.http.request(opts [, cb]) --> HttpResponse, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
opts | HttpRequest | The request: see HttpRequest. |
HttpResponse, err: The response (see HttpResponse); nil and a failure code when no response came back.Promise<HttpResponse>: Resolves with the HttpResponse; rejects with a failure code when no response came back.| Failure code | When |
|---|---|
timeout | No complete response within timeoutMs. |
io | Name resolution, connection, TLS or protocol error. |
permission | Destination refused: on a client, a host name that resolves to a private or reserved address; on the server, outside the sandbox rules. |
limit | The response body is larger than maxBytes. |
error | With 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). |
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
endasync 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 Β· JSlsmp.http.get(url [, opts] [, cb]) --> HttpResponse, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
url | string | The address, query string included or added with the query option. |
opts opt | HttpRequest | Headers, query, timeout, response type...: see HttpRequest. |
HttpResponse, err: The response, or nil and a failure code.Promise<HttpResponse>: Resolves with the response; rejects with a failure code.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)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 Β· JSlsmp.http.post(url [, opts] [, cb]) --> HttpResponse, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
url | string | The address. |
opts opt | HttpRequest | Body, headers, timeout...: see HttpRequest. |
HttpResponse, err: The response, or nil and a failure code.Promise<HttpResponse>: Resolves with the response; rejects with a failure code.-- 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// 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.
| Field | Type | Default | Description |
|---|---|---|---|
url | string | β | Required for request. https://... (http:// on the server only). No spaces or control characters. |
method | string | "GET" | GET, POST, PUT, PATCH, DELETE, HEAD or OPTIONS. request only. |
headers | table | β | Header names to values. A value is a string or a finite number. |
query | table | β | Parameters added to the URL, encoded for you. Values: strings or finite numbers. |
body | string | bytes | β | Raw request body. Not with json, never on GET/HEAD. |
json | value | β | A value sent as JSON, with Content-Type: application/json unless you set one. |
timeoutMs | ms | 30000 | Whole request, 1 to 300000. |
responseType | string | "text" | "text" (a string), "bytes" (JS Uint8Array, Lua string) or "json" (the decoded value). |
followRedirects | boolean | true | Follow 3xx redirections. |
http3 | boolean | false | Try HTTP/3 first. |
maxBytes | int | 67108864 | Largest response body accepted (64 MiB at most). Larger: failure limit. |
HttpResponse
| Field | Type | Default | Description |
|---|---|---|---|
ok | boolean | β | true for a status from 200 to 299. |
status | int | β | The HTTP status. |
statusText | string | β | The reason phrase sent by the server, possibly empty. |
headers | table | β | Header names in lower case. A repeated header is joined with ", ", except set-cookie, which is a list. |
body | string | bytes | value | β | As asked by responseType. |
url | string | β | 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.okorres.statusbefore 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.
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.
| Identifier | Lives | Use it for |
|---|---|---|
playerId | One session. Reused after the player leaves. | Every API call, events, network messages. |
lsmpId | Forever. The same on every server. | Saved data, bans, permissions. nil/null for a guest. |
| Name | Chosen by the player, may change. | Display only. Never a key. |
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 Β· JSlsmp.getPlayers() --> {integer}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.
{integer}: A list of playerIds, possibly empty.number[]: A list of playerIds, possibly empty.for _, id in ipairs(lsmp.getPlayers()) do
lsmp.log(id, lsmp.getPlayerName(id))
endfor (const id of lsmp.getPlayers()) {
lsmp.log(id, lsmp.getPlayerName(id));
}lsmp.playerExists
SharedLua Β· JSlsmp.playerExists(playerId) --> booleanlsmp.playerExists(playerId: number): booleanWhether 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player to test. |
boolean: true if the player is there.Name and account
lsmp.getPlayerName
SharedLua Β· JSlsmp.getPlayerName(playerId) --> string?lsmp.getPlayerName(playerId: number): string | nullThe name a player connected with.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
string?: The name, or nil/null if the player is unknown.string | null: The name, or nil/null if the player is unknown.lsmp.getPlayerLsmpId
SharedLua Β· JSlsmp.getPlayerLsmpId(playerId) --> integer?lsmp.getPlayerLsmpId(playerId: number): number | nullThe LS:MP account of a player, as a number.
The same number on every server and every session: key saved data on it.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
integer?: The account number, or nil/null for a guest or an unknown player.number | null: The account number, or nil/null for a guest or an unknown player.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)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 Β· JSlsmp.isPlayerGuest(playerId) --> boolean?lsmp.isPlayerGuest(playerId: number): boolean | nullWhether 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
boolean?: true for a guest, false for a registered player, nil/null if the player is unknown.boolean | null: true for a guest, false for a registered player, nil/null if the player is unknown.lsmp.getLsmpAvatarUrl
SharedLua Β· JSlsmp.getLsmpAvatarUrl(playerId) --> string?lsmp.getLsmpAvatarUrl(playerId: number): string | nullThe 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The current player handle. On the client, pass the result of lsmp.getLocalPlayer(). |
string?: An absolute HTTPS URL for the current avatar version, or nil/null when unavailable.string | null: An absolute HTTPS URL for the current avatar version, or nil/null when unavailable.lsmp.isPlayerDev
SharedLua Β· JSlsmp.isPlayerDev(playerId) --> boolean?lsmp.isPlayerDev(playerId: number): boolean | nullWhether 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
boolean?: true or false, or nil/null if the player is unknown.boolean | null: true or false, or nil/null if the player is unknown.lsmp.getPlayerDimension
SharedLua Β· JSlsmp.getPlayerDimension(playerId) --> integer?lsmp.getPlayerDimension(playerId: number): number | nullThe 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
integer?: The dimension, or nil/null if the player is unknown.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 Β· JSlsmp.getPlayerIdentifier(playerId, type) --> string?lsmp.getPlayerIdentifier(playerId: number, type: string): string | nullOne identifier of a connected player.
Can fail at run time: see error codes.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
type | string | "lsmp", "name", "ip" or "hwid". |
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.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 code | When |
|---|---|
permission | "ip" or "hwid" without the players.identity capability. |
lsmp.getPlayerIdentifiers
ServerLua Β· JSlsmp.getPlayerIdentifiers(playerId) --> table?lsmp.getPlayerIdentifiers(playerId: number): table | nullEvery 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
table?: The identifiers, or nil/null if the player is unknown.table | null: The identifiers, or nil/null if the player is unknown.local ids = lsmp.getPlayerIdentifiers(source)
if ids then
for kind, value in pairs(ids) do
lsmp.log(kind, value)
end
endconst 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 Β· JSlsmp.getPlayerPed(playerId) --> integer?lsmp.getPlayerPed(playerId: number): number | nullThe netId of a player's ped.
A player has no ped before their first spawn.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
integer?: The netId, or nil/null if the player has no ped yet or is unknown.number | null: The netId, or nil/null if the player has no ped yet or is unknown.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))
endconst 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 Β· JSlsmp.getPlayerPed(playerId) --> integer?lsmp.getPlayerPed(playerId: number): number | nullThe 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
integer?: The game handle, or nil/null while the ped is not on this client.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.
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)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})`);
});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.
| Scope | Read | Written by | Lives until |
|---|---|---|---|
| player | everywhere, getPlayerMeta | server scripts; a client for its own player | the player leaves |
| entity | everywhere, getEntityMeta | server scripts; the client that owns (simulates) the entity | the entity is deleted |
| global | everywhere, getGlobalMeta | server scripts only | the 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
metaChangeengine 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.
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.
-- 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" })// 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 Β· JSlsmp.getPlayerMeta(playerId, key) --> any?lsmp.getPlayerMeta(playerId: number, key: string): Value | nullA player's meta value.
Still readable inside playerLeave handlers for the leaving player.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
key | string | Key: 1 to 128 bytes of UTF-8, not starting with lsmp:. |
any?: The value, or nil/null if absent or if the player is unknown.Value | null: The value, or nil/null if absent or if the player is unknown.local job = lsmp.getPlayerMeta(playerId, "job")
if job and job.name == "police" then openArmory(playerId) endconst job = lsmp.getPlayerMeta(playerId, "job");
if (job?.name === "police") openArmory(playerId);lsmp.getEntityMeta
SharedLua Β· JSlsmp.getEntityMeta(netId, key) --> any?lsmp.getEntityMeta(netId: number, key: string): Value | nullAn entity's meta value.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
key | string | Key: 1 to 128 bytes of UTF-8, not starting with lsmp:. |
any?: The value, or nil/null if absent or if the entity is unknown.Value | null: The value, or nil/null if absent or if the entity is unknown.lsmp.getGlobalMeta
SharedLua Β· JSlsmp.getGlobalMeta(key) --> any?lsmp.getGlobalMeta(key: string): Value | nullA global meta value.
| Parameter | Type | Description |
|---|---|---|
key | string | Key: 1 to 128 bytes of UTF-8, not starting with lsmp:. |
any?: The value, or nil/null if absent.Value | null: The value, or nil/null if absent.Writing on the server
lsmp.setPlayerMeta
ServerLua Β· JSlsmp.setPlayerMeta(playerId, key, value) --> booleanlsmp.setPlayerMeta(playerId: number, key: string, value: Value): booleanSets or deletes a player's meta value, replicated to every client.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
key | string | Key: 1 to 128 bytes of UTF-8, not starting with lsmp:. |
value | value | Any transportable value up to 8192 bytes encoded. nil/null deletes the key. |
boolean: false (not-found) if the player is unknown.lsmp.setEntityMeta
ServerLua Β· JSlsmp.setEntityMeta(netId, key, value) --> booleanlsmp.setEntityMeta(netId: number, key: string, value: Value): booleanSets or deletes an entity's meta value, replicated to every client.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
key | string | Key: 1 to 128 bytes of UTF-8, not starting with lsmp:. |
value | value | Any transportable value up to 8192 bytes encoded. nil/null deletes the key. |
boolean: false (not-found) if the entity is unknown.lsmp.setEntityMeta(car, "fuel", 0.75)
lsmp.setEntityMeta(car, "locked", true)lsmp.setEntityMeta(car, "fuel", 0.75);
lsmp.setEntityMeta(car, "locked", true);lsmp.setGlobalMeta
ServerLua Β· JSlsmp.setGlobalMeta(key, value) --> booleanlsmp.setGlobalMeta(key: string, value: Value): booleanSets or deletes a global meta value, replicated to every client.
| Parameter | Type | Description |
|---|---|---|
key | string | Key: 1 to 128 bytes of UTF-8, not starting with lsmp:. |
value | value | Any transportable value up to 8192 bytes encoded. nil/null deletes the key. |
boolean: true when done.lsmp.setGlobalMeta("event:active", "carnival")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 Β· JSlsmp.setPlayerMeta(playerId, key, value) --> booleanlsmp.setPlayerMeta(playerId: number, key: string, value: Value): booleanSets or deletes a meta value on the local player.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | Must be the local player. |
key | string | Key: 1 to 128 bytes of UTF-8, not starting with lsmp:. |
value | value | Any transportable value up to 8192 bytes encoded. nil/null deletes the key. |
boolean: false with disconnected (not in a session) or limit (server budget or rate).lsmp.setEntityMeta
ClientLua Β· JSlsmp.setEntityMeta(netId, key, value) --> booleanlsmp.setEntityMeta(netId: number, key: string, value: Value): booleanSets or deletes a meta value on an entity this client owns.
| Parameter | Type | Description |
|---|---|---|
netId | netId | An entity simulated by this client. |
key | string | Key: 1 to 128 bytes of UTF-8, not starting with lsmp:. |
value | value | Any transportable value up to 8192 bytes encoded. nil/null deletes the key. |
boolean: false with permission (not the owner), not-found, disconnected or limit.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
| Field | Type | Default | Description |
|---|---|---|---|
maxRadius | meters | 0 | getClosestPlayer, getClosestEntity: ignore anything farther. 0 means no limit. |
types | list of strings | all | getClosestEntity, getEntitiesInRadius: any of "vehicle", "ped", "object", "playerPed". |
dimension | dimension | 0 | Server only: the dimension to search. |
Functions
lsmp.getClosestPlayer
SharedLua Β· JSlsmp.getClosestPlayer(position [, opts]) --> integer?lsmp.getClosestPlayer(position: Vec3Like, opts?: ClosestOptions): number | nullThe player whose ped is closest to a position.
On a client the local player is included: exclude it yourself if needed.
| Parameter | Type | Description |
|---|---|---|
position | vec3 | The center of the search. |
opts opt | ClosestOptions | { maxRadius, dimension }. |
integer?: A playerId, or nil/null if none.number | null: A playerId, or nil/null if none.local target = lsmp.getClosestPlayer(lsmp.getEntityCoords(lsmp.getPlayerPed(source)), { maxRadius = 3.0 })const target = lsmp.getClosestPlayer(lsmp.getEntityCoords(lsmp.getPlayerPed(source)), { maxRadius: 3 });lsmp.getClosestEntity
SharedLua Β· JSlsmp.getClosestEntity(position [, opts]) --> integer?lsmp.getClosestEntity(position: Vec3Like, opts?: ClosestOptions): number | nullThe networked entity closest to a position.
| Parameter | Type | Description |
|---|---|---|
position | vec3 | The center of the search. |
opts opt | ClosestOptions | { types, maxRadius, dimension }. |
integer?: A netId, or nil/null if none.number | null: A netId, or nil/null if none.local car = lsmp.getClosestEntity(position, { types = { "vehicle" }, maxRadius = 10.0 })const car = lsmp.getClosestEntity(position, { types: ["vehicle"], maxRadius: 10 });lsmp.getEntitiesInRadius
SharedLua Β· JSlsmp.getEntitiesInRadius(position, radius [, opts]) --> {integer}lsmp.getEntitiesInRadius(position: Vec3Like, radius: number, opts?: QueryOptions): Uint32ArrayEvery networked entity within a radius.
| Parameter | Type | Description |
|---|---|---|
position | vec3 | The center of the search. |
radius | meters | Search radius. |
opts opt | QueryOptions | { types, dimension }. |
{integer}: The netIds, in no particular order. A Uint32Array in JavaScript: use for...of or Array.from.Uint32Array: The netIds, in no particular order. A Uint32Array in JavaScript: use for...of or Array.from.for _, netId in ipairs(lsmp.getEntitiesInRadius(position, 25.0, { types = { "ped" } })) do
lsmp.setEntityIntent(netId, { type = "flee", target = "nearestPlayer" })
endfor (const netId of lsmp.getEntitiesInRadius(position, 25, { types: ["ped"] })) {
lsmp.setEntityIntent(netId, { type: "flee", target: "nearestPlayer" });
}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.
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 Β· JSlsmp.weather.get() --> WeatherState?lsmp.weather.get(): WeatherState | nullThe synchronized weather at this moment.
See WeatherState. On a client, nil/null until the first state arrived from the server, a moment after connecting.
WeatherState?: The current state.WeatherState | null: The current state.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
endconst 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 Β· JSlsmp.weather.getForecast([count]) --> {WeatherForecastEntry}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.
| Parameter | Type | Description |
|---|---|---|
count opt | int | How many upcoming changes, 1 to 32. Default: 6 |
{WeatherForecastEntry}: The upcoming changes, soonest first.WeatherForecastEntry[]: The upcoming changes, soonest first.lsmp.weather.getTypes
SharedLua Β· JSlsmp.weather.getTypes() --> {string}lsmp.weather.getTypes(): string[]The weather names set and setLocal accept.
For example "EXTRASUNNY", "RAIN", "THUNDER", "SNOW", "XMAS", "HALLOWEEN". Names are upper case.
{string}: Every weather name.string[]: Every weather name.Forcing the weather (server)
lsmp.weather.set
ServerLua Β· JSlsmp.weather.set(type [, opts]) --> booleanlsmp.weather.set(type: string, opts?: WeatherSetOptions): booleanForce 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.
| Parameter | Type | Description |
|---|---|---|
type | string | A name from getTypes. |
opts opt | WeatherSetOptions | See WeatherSetOptions. |
boolean: true if the weather was set.| Failure code | When |
|---|---|
permission | The resource does not hold world.weather. |
-- /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)// /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 Β· JSlsmp.weather.resumeCycle([opts]) --> booleanlsmp.weather.resumeCycle(opts?: WeatherTransitionOptions): booleanStop forcing the weather and go back to the cycle.
Needs the world.weather capability.
| Parameter | Type | Description |
|---|---|---|
opts opt | WeatherTransitionOptions | { transitionMs }: the fade back, 0 to 3600000 ms. |
boolean: true if a forced weather was lifted, false if the cycle was already running.| Failure code | When |
|---|---|
permission | The resource does not hold world.weather. |
lsmp.weather.setSeed
ServerLua Β· JSlsmp.weather.setSeed(seed) --> booleanlsmp.weather.setSeed(seed: number): booleanChoose 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.
| Parameter | Type | Description |
|---|---|---|
seed | uint | Any integer from 0 to 4294967295. |
boolean: true if the seed was set.| Failure code | When |
|---|---|
permission | The resource does not hold world.weather. |
A sky of your own (client)
lsmp.weather.setLocal
ClientLua Β· JSlsmp.weather.setLocal(type [, opts]) --> booleanlsmp.weather.setLocal(type: string, opts?: WeatherTransitionOptions): booleanShow 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.
| Parameter | Type | Description |
|---|---|---|
type | string | A name from getTypes. |
opts opt | WeatherTransitionOptions | { transitionMs }: the fade, 0 to 3600000 ms. |
boolean: true if the weather was applied.-- 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)// 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 Β· JSlsmp.weather.clearLocal([opts]) --> booleanlsmp.weather.clearLocal(opts?: WeatherTransitionOptions): booleanRemove this resource's local weather.
| Parameter | Type | Description |
|---|---|---|
opts opt | WeatherTransitionOptions | { transitionMs }: the fade back to the shared weather. |
boolean: true if this resource had a local weather.lsmp.weather.getState
ClientLua Β· JSlsmp.weather.getState() --> WeatherMixlsmp.weather.getState(): WeatherMixThe 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.
WeatherMix: 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
| Field | Type | Default | Description |
|---|---|---|---|
type | string | β | The weather fading in, or in place. |
previous | string? | β | The weather it replaces while a transition runs. |
transitionMs | ms | β | Total length of the transition in progress (0 when none). |
transitionTimeMs | ms | β | Time already elapsed in that transition. |
forced | boolean | β | true while a script forces the weather. |
forcedTimeLeftMs | ms? | β | Time before the cycle resumes; absent when forced with no duration, or not forced. |
next | string? | β | The next weather of the cycle. |
nextChangeMs | ms? | β | Time before that change. |
seed | uint | β | The seed of the cycle. |
localOverride | string? | β | Client only: the local weather set with setLocal, if any. |
WeatherForecastEntry
| Field | Type | Default | Description |
|---|---|---|---|
type | string | β | The weather of that segment. |
atMs | epochMs | β | When it starts fading in (Unix time, milliseconds). |
durationMs | ms? | β | How long the segment lasts, when known. |
transitionMs | ms | β | Length of its fade-in. |
WeatherSetOptions
| Field | Type | Default | Description |
|---|---|---|---|
transitionMs | ms | 0 | Fade from the current weather, 0 to 3600000. |
durationMs | ms | 0 | How long to keep it before the cycle resumes. 0: until changed. |
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
- Rules. A rule allows or denies a name, and covers everything below it: a rule on
vehiclecoversvehicle.spawn.tank.*covers everything;vehicle.*means the same asvehicle. - 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.
- Within a source, the most precise rule wins (
vehicle.tankbeforevehicle, before*). A group inherits the rules of its parent; its own rule wins over the parent's at the same precision. - Ties. Two sources of the same priority that disagree: the denial wins.
- 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.
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 Β· JSlsmp.perms.has(playerId, permission) --> booleanlsmp.perms.has(playerId: number, permission: string): booleanWhether a player holds a permission.
The answer is cached and costs next to nothing: call it on every request a player makes.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
permission | string | A permission name, without wildcard. |
boolean: true if a rule allows it; false otherwise, and for an unknown player.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)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 Β· JSlsmp.perms.explain(playerId, permission) --> PermExplain?lsmp.perms.explain(playerId: number, permission: string): PermExplain | nullWhy a player holds a permission, or not.
See PermExplain. Useful in a command that answers "why can't I...".
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
permission | string | A permission name. |
PermExplain?: The explanation, or nil/null for an unknown player.PermExplain | null: The explanation, or nil/null for an unknown player.lsmp.perms.getPlayerGroups
ServerLua Β· JSlsmp.perms.getPlayerGroups(playerId [, opts]) --> {PermGroupRef}?lsmp.perms.getPlayerGroups(playerId: number, opts?: InheritOptions): PermGroupRef[] | nullThe groups of a player, from the highest priority down.
Each entry is a PermGroupRef. default is always there.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
opts opt | InheritOptions | { inherited }: include the groups held only through a parent (default true). |
{PermGroupRef}?: The groups, or nil/null for an unknown player.PermGroupRef[] | null: The groups, or nil/null for an unknown player.lsmp.perms.inGroup
ServerLua Β· JSlsmp.perms.inGroup(playerId, group [, opts]) --> boolean?lsmp.perms.inGroup(playerId: number, group: string, opts?: InheritOptions): boolean | nullWhether a player is in a group.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
group | string | The group id. |
opts opt | InheritOptions | { inherited }: count membership through a parent (default true). |
boolean?: true or false, or nil/null for an unknown player.boolean | null: true or false, or nil/null for an unknown player.lsmp.perms.getPlayerIdentities
ServerLua Β· JSlsmp.perms.getPlayerIdentities(playerId) --> {string}?lsmp.perms.getPlayerIdentities(playerId: number): string[] | nullThe 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
{string}?: The identities, or nil/null for an unknown player.string[] | null: The identities, or nil/null for an unknown player.lsmp.perms.getPlayerIdentity
ServerLua Β· JSlsmp.perms.getPlayerIdentity(playerId [, type]) --> string?lsmp.perms.getPlayerIdentity(playerId: number, type: string = "lsmp"): string | nullOne 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
type opt | string | "lsmp" or "ip". Default: "lsmp" |
string?: The identity, or nil/null if the player is unknown or has none of that type (a guest has no lsmp identity).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 code | When |
|---|---|
permission | "ip" without the players.identity capability. |
Reading groups and identities (server)
lsmp.perms.getGroups
ServerLua Β· JSlsmp.perms.getGroups() --> {PermGroup}lsmp.perms.getGroups(): PermGroup[]Every group of the server.
Each entry is a PermGroup, without its rules.
{PermGroup}: The groups.PermGroup[]: The groups.lsmp.perms.getGroup
ServerLua Β· JSlsmp.perms.getGroup(id) --> PermGroup?lsmp.perms.getGroup(id: string): PermGroup | nullOne group, with its rules.
A PermGroup with rules: a table of permission patterns to true (allow) or false (deny).
| Parameter | Type | Description |
|---|---|---|
id | string | The group id. |
PermGroup?: The group, or nil/null if it does not exist.PermGroup | null: The group, or nil/null if it does not exist.lsmp.perms.getGroupMembers
ServerLua Β· JSlsmp.perms.getGroupMembers(id) --> {PermMember}?lsmp.perms.getGroupMembers(id: string): PermMember[] | nullThe 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.
| Parameter | Type | Description |
|---|---|---|
id | string | The group id. |
{PermMember}?: The members, or nil/null if the group does not exist.PermMember[] | null: The members, or nil/null if the group does not exist.lsmp.perms.getIdentity
ServerLua Β· JSlsmp.perms.getIdentity(identity) --> PermIdentity?lsmp.perms.getIdentity(identity: string): PermIdentity | nullWhat is attached to an identity.
{ identity, label, lastSeenMs, groups, rules }: groups lists { group, untilMs, note }, rules maps patterns to true or false.
| Parameter | Type | Description |
|---|---|---|
identity | string | An identity such as "lsmp:380201629467". |
PermIdentity?: The identity, or nil/null if nothing is attached to it.PermIdentity | null: The identity, or nil/null if nothing is attached to it.| Failure code | When |
|---|---|
permission | An ip: identity without the players.identity capability. |
Declaring permissions
lsmp.perms.declare
ServerLua Β· JSlsmp.perms.declare(permission [, description])lsmp.perms.declare(permission: string, description?: string): voidList 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.
| Parameter | Type | Description |
|---|---|---|
permission | string | The permission name. |
description opt | string | One sentence shown in the panel. |
lsmp.perms.declare("garage.tank", "Spawn a tank from the garage")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 Β· JSlsmp.perms.createGroup(id [, opts]) --> booleanlsmp.perms.createGroup(id: string, opts?: PermGroupOptions): booleanCreate 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.
| Parameter | Type | Description |
|---|---|---|
id | string | The group id: lower case, 32 characters at most. |
opts opt | PermGroupOptions | See PermGroupOptions. |
boolean: true if the group was created.| Failure code | When |
|---|---|
exists | A group with this id exists. |
permission | The resource does not hold perms.manage. |
if lsmp.perms.createGroup("vip", { label = "VIP", color = "#f1c40f", priority = 20 }) then
lsmp.perms.allow("group:vip", "garage.tank")
endif (lsmp.perms.createGroup('vip', { label: 'VIP', color: '#f1c40f', priority: 20 })) {
lsmp.perms.allow('group:vip', 'garage.tank');
}lsmp.perms.updateGroup
ServerLua Β· JSlsmp.perms.updateGroup(id, patch) --> booleanlsmp.perms.updateGroup(id: string, patch: PermGroupOptions): booleanChange the label, color, priority or parent of a group.
Only the fields given change.
Needs the perms.manage capability.
| Parameter | Type | Description |
|---|---|---|
id | string | The group id. |
patch | PermGroupOptions | See PermGroupOptions. |
boolean: true if the group was changed.| Failure code | When |
|---|---|
not-found | No such group. |
permission | The resource does not hold perms.manage. |
lsmp.perms.renameGroup
ServerLua Β· JSlsmp.perms.renameGroup(id, newId) --> booleanlsmp.perms.renameGroup(id: string, newId: string): booleanChange the id of a group.
Memberships, parents and rules that name the group follow the new id.
Needs the perms.manage capability.
| Parameter | Type | Description |
|---|---|---|
id | string | The current id. |
newId | string | The new id. |
boolean: true if the group was renamed.| Failure code | When |
|---|---|
not-found | No such group. |
exists | newId is taken. |
permission | The resource does not hold perms.manage. |
lsmp.perms.deleteGroup
ServerLua Β· JSlsmp.perms.deleteGroup(id) --> booleanlsmp.perms.deleteGroup(id: string): booleanDelete a group and its memberships.
The default group cannot be deleted.
Needs the perms.manage capability.
| Parameter | Type | Description |
|---|---|---|
id | string | The group id. |
boolean: true if the group was deleted.| Failure code | When |
|---|---|
not-found | No such group. |
permission | The resource does not hold perms.manage. |
lsmp.perms.allow
ServerLua Β· JSlsmp.perms.allow(target, rule) --> booleanlsmp.perms.allow(target: number | string, rule: string): booleanAdd a rule that allows a permission.
An existing rule on the same pattern for the same target is replaced.
Needs the perms.manage capability.
| Parameter | Type | Description |
|---|---|---|
target | playerId|string | A playerId (this session only), "group:<id>", or an identity such as "lsmp:380201629467". |
rule | string | A permission name, name.* or *. |
boolean: true if the rule was written.| Failure code | When |
|---|---|
permission | The resource does not hold perms.manage. |
lsmp.perms.deny
ServerLua Β· JSlsmp.perms.deny(target, rule) --> booleanlsmp.perms.deny(target: number | string, rule: string): booleanAdd a rule that denies a permission.
Useful to carve an exception: allow vehicle and deny vehicle.tank.
Needs the perms.manage capability.
| Parameter | Type | Description |
|---|---|---|
target | playerId|string | A playerId (this session only), "group:<id>", or an identity such as "lsmp:380201629467". |
rule | string | A permission name, name.* or *. |
boolean: true if the rule was written.| Failure code | When |
|---|---|
permission | The resource does not hold perms.manage. |
lsmp.perms.unset
ServerLua Β· JSlsmp.perms.unset(target, rule) --> booleanlsmp.perms.unset(target: number | string, rule: string): booleanRemove a rule, whether it allowed or denied.
Needs the perms.manage capability.
| Parameter | Type | Description |
|---|---|---|
target | playerId|string | A playerId (this session only), "group:<id>", or an identity such as "lsmp:380201629467". |
rule | string | The pattern of the rule. |
boolean: true if a rule was removed.| Failure code | When |
|---|---|
permission | The resource does not hold perms.manage. |
lsmp.perms.addToGroup
ServerLua Β· JSlsmp.perms.addToGroup(target, group [, opts]) --> booleanlsmp.perms.addToGroup(target: number | string, group: string, opts?: MembershipOptions): booleanPut 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.
| Parameter | Type | Description |
|---|---|---|
target | playerId|string | A playerId (this session only) or an identity. |
group | string | The group id. |
opts opt | MembershipOptions | See MembershipOptions. |
boolean: true once the target is in the group (also when it already was).| Failure code | When |
|---|---|
not-found | No such group, or the player is unknown. |
permission | The resource does not hold perms.manage. |
-- 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// 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 Β· JSlsmp.perms.removeFromGroup(target, group) --> booleanlsmp.perms.removeFromGroup(target: number | string, group: string): booleanTake a player or an identity out of a group.
Needs the perms.manage capability.
| Parameter | Type | Description |
|---|---|---|
target | playerId|string | A playerId (session membership) or an identity. |
group | string | The group id. |
boolean: true if a membership was removed.| Failure code | When |
|---|---|
permission | The resource does not hold perms.manage. |
lsmp.perms.deleteIdentity
ServerLua Β· JSlsmp.perms.deleteIdentity(identity) --> booleanlsmp.perms.deleteIdentity(identity: string): booleanForget every rule and membership of an identity.
Needs the perms.manage capability.
| Parameter | Type | Description |
|---|---|---|
identity | string | The identity. |
boolean: true if something was removed.| Failure code | When |
|---|---|
permission | The 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 Β· JSlsmp.perms.getCapabilities() --> {string}lsmp.perms.getCapabilities(): string[]The capabilities this resource holds.
{string}: Capability ids, such as "players.kick".string[]: Capability ids, such as "players.kick".lsmp.perms.hasCapability
ServerLua Β· JSlsmp.perms.hasCapability(capability) --> booleanlsmp.perms.hasCapability(capability: string): booleanWhether this resource holds a capability.
To adapt a feature before calling a function that would fail with permission.
| Parameter | Type | Description |
|---|---|---|
capability | string | A capability id. |
boolean: 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.
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 Β· JSlsmp.perms.has(permission) --> booleanlsmp.perms.has(permission: string): booleanWhether the local player holds a permission.
| Parameter | Type | Description |
|---|---|---|
permission | string | A permission name. |
boolean: true if allowed; false otherwise, and before the copy arrived.if lsmp.perms.has("garage.tank") then
lsmp.log("tanks are available in your garage")
endif (lsmp.perms.has('garage.tank')) lsmp.log('tanks are available in your garage');lsmp.perms.explain
ClientLua Β· JSlsmp.perms.explain(permission) --> PermExplainlsmp.perms.explain(permission: string): PermExplainWhy the local player holds a permission, or not.
See PermExplain.
| Parameter | Type | Description |
|---|---|---|
permission | string | A permission name. |
PermExplain: The explanation.lsmp.perms.getGroups
ClientLua Β· JSlsmp.perms.getGroups([opts]) --> {PermGroupRef}lsmp.perms.getGroups(opts?: InheritOptions): PermGroupRef[]The groups of the local player.
| Parameter | Type | Description |
|---|---|---|
opts opt | InheritOptions | { inherited }: include the groups held through a parent (default true). |
{PermGroupRef}: A list of PermGroupRef, empty before the copy arrived.PermGroupRef[]: A list of PermGroupRef, empty before the copy arrived.lsmp.perms.inGroup
ClientLua Β· JSlsmp.perms.inGroup(group [, opts]) --> booleanlsmp.perms.inGroup(group: string, opts?: InheritOptions): booleanWhether the local player is in a group.
| Parameter | Type | Description |
|---|---|---|
group | string | The group id. |
opts opt | InheritOptions | { inherited } (default true). |
boolean: true or false.lsmp.perms.isReady
ClientLua Β· JSlsmp.perms.isReady() --> booleanlsmp.perms.isReady(): booleanWhether the copy of the permissions has arrived.
It usually arrives before client scripts start. Until then every check answers false.
boolean: true once the copy is there.lsmp.perms.isComplete
ClientLua Β· JSlsmp.perms.isComplete() --> booleanlsmp.perms.isComplete(): booleanWhether 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.
boolean: 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
| Field | Type | Default | Description |
|---|---|---|---|
allowed | boolean | β | The answer. |
matched | boolean | β | false when no rule covers the permission (refused by default). |
source | string | β | Where the deciding rule comes from: "session", "identity" or "group"; "none" when no rule matched. |
group | string? | β | The group of the deciding rule. |
rule | string? | β | The pattern of the deciding rule. |
permission | string | β | The permission asked about, normalized. |
PermGroupRef
| Field | Type | Default | Description |
|---|---|---|---|
id | string | β | The group id. |
label | string | β | Its display name. |
color | string? | β | "#rrggbb". |
priority | int | β | Higher wins. |
direct | boolean | β | false when held only through a parent. |
PermGroup
| Field | Type | Default | Description |
|---|---|---|---|
id | string | β | The group id. |
label | string | β | Its display name. |
color | string? | β | "#rrggbb". |
priority | int | β | Higher wins. |
parent | string? | β | The group it inherits from. |
builtin | boolean | β | true for default. |
members | int | β | How many saved identities are members. |
rules | table | β | getGroup only: patterns to true (allow) or false (deny). |
PermGroupOptions
| Field | Type | Default | Description |
|---|---|---|---|
label | string | the id | Display name, 64 bytes at most. |
color | color | β | Any color form. |
priority | int | 0 | Higher wins when sources disagree. |
parent | string | β | A group to inherit rules from. |
MembershipOptions
| Field | Type | Default | Description |
|---|---|---|---|
durationMs | ms | β | Ends this long after the call. |
untilMs | epochMs | β | Ends at this time. Not with durationMs. |
note | string | β | Shown in the admin panel. |
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.
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
| Kind | Option | Heard |
|---|---|---|
| Flat | spatial: false (default) | At the same level everywhere: a radio, a phone call, a team channel. |
| 3D | spatial: true | From 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.
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).
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 Β· JSlsmp.VoiceRolelsmp.VoiceRoleThe 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 Β· JSlsmp.voice.createChannel(channel [, opts]) --> booleanlsmp.voice.createChannel(channel: string | number, opts?: VoiceChannelOptions): booleanCreate 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.
| Parameter | Type | Description |
|---|---|---|
channel | string|hashOut | A name (or a hash). |
opts opt | VoiceChannelOptions | See VoiceChannelOptions. |
boolean: true if the channel was created.| Failure code | When |
|---|---|
exists | The channel exists. |
limit | The server holds 4096 channels. |
permission | The resource does not hold voice.manage. |
-- 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)// 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 Β· JSlsmp.voice.setChannelOptions(channel, opts) --> booleanlsmp.voice.setChannelOptions(channel: string | number, opts: VoiceChannelOptions): booleanChange 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.
| Parameter | Type | Description |
|---|---|---|
channel | string|hashOut | A name or a hash. |
opts | VoiceChannelOptions | See VoiceChannelOptions. |
boolean: true if the channel was changed.| Failure code | When |
|---|---|
not-found | No such channel. |
permission | The resource does not hold voice.manage. |
lsmp.voice.getChannelOptions
ServerLua Β· JSlsmp.voice.getChannelOptions(channel) --> VoiceChannelOptions?lsmp.voice.getChannelOptions(channel: string | number): VoiceChannelOptions | nullThe options in force on a channel.
Every field is filled in, with the values the server applies after clamping.
| Parameter | Type | Description |
|---|---|---|
channel | string|hashOut | A name or a hash. |
VoiceChannelOptions?: The options, or nil/null if the channel does not exist.VoiceChannelOptions | null: The options, or nil/null if the channel does not exist.lsmp.voice.destroyChannel
ServerLua Β· JSlsmp.voice.destroyChannel(channel) --> booleanlsmp.voice.destroyChannel(channel: string | number): booleanDestroy 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.
| Parameter | Type | Description |
|---|---|---|
channel | string|hashOut | A name or a hash. |
boolean: true if the channel was destroyed.| Failure code | When |
|---|---|
not-found | No such channel. |
permission | The resource does not hold voice.manage. |
lsmp.voice.channelExists
ServerLua Β· JSlsmp.voice.channelExists(channel) --> booleanlsmp.voice.channelExists(channel: string | number): booleanWhether a channel exists.
| Parameter | Type | Description |
|---|---|---|
channel | string|hashOut | A name or a hash. |
boolean: true if it exists.lsmp.voice.getChannels
ServerLua Β· JSlsmp.voice.getChannels() --> {integer}lsmp.voice.getChannels(): number[]Every channel of the server, as hashes.
The channels of every resource. getChannelName gives a channel's name back.
{integer}: The channel hashes.number[]: The channel hashes.lsmp.voice.getChannelName
ServerLua Β· JSlsmp.voice.getChannelName(channel) --> string?lsmp.voice.getChannelName(channel: string | number): string | nullThe name a channel was created with.
| Parameter | Type | Description |
|---|---|---|
channel | string|hashOut | A name or a hash. |
string?: The name, or nil/null if the channel does not exist or was created from a hash.string | null: The name, or nil/null if the channel does not exist or was created from a hash.lsmp.voice.getChannelPlayers
ServerLua Β· JSlsmp.voice.getChannelPlayers(channel) --> {VoiceMember}lsmp.voice.getChannelPlayers(channel: string | number): VoiceMember[]The players on a channel.
| Parameter | Type | Description |
|---|---|---|
channel | string|hashOut | A name or a hash. |
{VoiceMember}: A list of { playerId, role }, empty for a channel that does not exist.VoiceMember[]: A list of { playerId, role }, empty for a channel that does not exist.lsmp.voice.getChannelId
SharedLua Β· JSlsmp.voice.getChannelId(name) --> integerlsmp.voice.getChannelId(name: string): numberThe 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.
| Parameter | Type | Description |
|---|---|---|
name | string | The channel name. |
integer: The hash.number: The hash.Players on channels (server)
lsmp.voice.setPlayerChannel
ServerLua Β· JSlsmp.voice.setPlayerChannel(playerId, channel, role) --> booleanlsmp.voice.setPlayerChannel(playerId: number, channel: string | number, role: string): booleanPut 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
channel | string|hashOut | A name or a hash. |
role | string | "listen", "talk" or "both" (lsmp.VoiceRole). |
boolean: true if the membership was set.| Failure code | When |
|---|---|
not-found | Unknown player or channel. |
limit | The player is on 8 channels. |
permission | The resource does not hold voice.manage. |
lsmp.voice.removePlayerChannel
ServerLua Β· JSlsmp.voice.removePlayerChannel(playerId, channel) --> booleanlsmp.voice.removePlayerChannel(playerId: number, channel: string | number): booleanTake a player off a channel.
Needs the voice.manage capability.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
channel | string|hashOut | A name or a hash. |
boolean: true if the player was on the channel.| Failure code | When |
|---|---|
not-found | The player was not on the channel. |
permission | The resource does not hold voice.manage. |
lsmp.voice.getPlayerChannel
ServerLua Β· JSlsmp.voice.getPlayerChannel(playerId, channel) --> string?lsmp.voice.getPlayerChannel(playerId: number, channel: string | number): string | nullA player's role on one channel.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
channel | string|hashOut | A name or a hash. |
string?: "listen", "talk" or "both", or nil/null if the player is not on the channel.string | null: "listen", "talk" or "both", or nil/null if the player is not on the channel.lsmp.voice.getPlayerChannels
ServerLua Β· JSlsmp.voice.getPlayerChannels(playerId) --> {VoiceMembership}?lsmp.voice.getPlayerChannels(playerId: number): VoiceMembership[] | nullEvery channel a player is on.
Each entry is { channel, role }, with channel as a hash.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
{VoiceMembership}?: The memberships, or nil/null for an unknown player.VoiceMembership[] | null: The memberships, or nil/null for an unknown player.lsmp.voice.clearPlayerChannels
ServerLua Β· JSlsmp.voice.clearPlayerChannels(playerId) --> booleanlsmp.voice.clearPlayerChannels(playerId: number): booleanTake 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
boolean: true if the player is known.| Failure code | When |
|---|---|
not-found | Unknown player. |
permission | The resource does not hold voice.manage. |
lsmp.voice.setPlayerRange
ServerLua Β· JSlsmp.voice.setPlayerRange(playerId, channel, meters) --> booleanlsmp.voice.setPlayerRange(playerId: number, channel: string | number, meters: number): booleanHow 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The speaker. |
channel | string|hashOut | A name or a hash. |
meters | meters | The range, 0 or more (500 at most is used). 0 goes back to the channel's range. |
boolean: true if the player is on the channel.| Failure code | When |
|---|---|
not-found | The player is not on the channel. |
permission | The resource does not hold voice.manage. |
-- 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)// 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 Β· JSlsmp.voice.getPlayerRange(playerId, channel) --> number?lsmp.voice.getPlayerRange(playerId: number, channel: string | number): number | nullThe range a player's voice carries on a 3D channel.
Their own range if one was set, otherwise the channel's.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The speaker. |
channel | string|hashOut | A name or a hash. |
number?: The range in metres, or nil/null if the player is not on the channel.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 Β· JSlsmp.voice.setPlayerMuted(playerId, muted) --> booleanlsmp.voice.setPlayerMuted(playerId: number, muted: boolean): booleanSilence 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
muted | boolean | true to mute, false to unmute. |
boolean: true if the player is known.| Failure code | When |
|---|---|
not-found | Unknown player. |
permission | The resource does not hold voice.manage. |
lsmp.voice.isPlayerMuted
ServerLua Β· JSlsmp.voice.isPlayerMuted(playerId) --> boolean?lsmp.voice.isPlayerMuted(playerId: number): boolean | nullWhether a player is muted by the server.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
boolean?: true or false, or nil/null for an unknown player.boolean | null: true or false, or nil/null for an unknown player.lsmp.voice.isPlayerTalking
SharedLua Β· JSlsmp.voice.isPlayerTalking(playerId) --> booleanlsmp.voice.isPlayerTalking(playerId: number): booleanWhether 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
boolean: 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
| Field | Type | Default | Description |
|---|---|---|---|
spatial | boolean | false | true for a 3D channel. Only volume and priority apply to a flat channel. |
range | meters | 20 | How far a voice carries, up to 500. |
refDistance | meters | 2 | Full volume up to this distance. |
rolloff | number | 0.6 | How fast the volume falls beyond refDistance, 0 to 10. |
distanceModel | string | "inverse" | "inverse" (natural), "linear" (straight down to silence at the range) or "exponential". |
volume | number | 1 | Channel gain, 0 to 4. |
directional | boolean | true | Left/right panning from where the speaker stands. |
muffle | boolean | true | A muffled sound from far away or from behind. |
priority | int | 0 | Which 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 Β· JSlsmp.VoiceInputModelsmp.VoiceInputModeHow the local microphone opens.
lsmp.VoiceInputMode.Off = "off" Β· lsmp.VoiceInputMode.PushToTalk = "pushToTalk" Β· lsmp.VoiceInputMode.VoiceActivity = "voiceActivity"
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 Β· JSlsmp.voice.setInputMode(mode)lsmp.voice.setInputMode(mode: string): voidRestrict 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.
| Parameter | Type | Description |
|---|---|---|
mode | string | "off", "pushToTalk" or "voiceActivity" (lsmp.VoiceInputMode). |
lsmp.voice.getInputMode
ClientLua Β· JSlsmp.voice.getInputMode() --> stringlsmp.voice.getInputMode(): stringThe microphone mode in force.
string: "off", "pushToTalk" or "voiceActivity".lsmp.voice.setTalking
ClientLua Β· JSlsmp.voice.setTalking(talking)lsmp.voice.setTalking(talking: boolean): voidHold 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.
| Parameter | Type | Description |
|---|---|---|
talking | boolean | true to transmit, false to stop. |
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)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 Β· JSlsmp.voice.isTransmitting() --> booleanlsmp.voice.isTransmitting(): booleanWhether the local microphone is sending.
For a microphone indicator. false while the player has no talk role on any channel.
boolean: true while sending.lsmp.voice.getMicLevel
ClientLua Β· JSlsmp.voice.getMicLevel() --> numberlsmp.voice.getMicLevel(): numberThe loudness of the local microphone.
For a level meter, or to help the player pick a threshold.
number: The level, 0 to 1.lsmp.voice.setMicGain
ClientLua Β· JSlsmp.voice.setMicGain(gain)lsmp.voice.setMicGain(gain: number): voidAmplify or soften the local microphone.
| Parameter | Type | Description |
|---|---|---|
gain | number | 0 to 4; 1 leaves it unchanged. |
lsmp.voice.setThreshold
ClientLua Β· JSlsmp.voice.setThreshold(rms)lsmp.voice.setThreshold(rms: number): voidHow loud the player must speak to transmit in voice activity mode.
| Parameter | Type | Description |
|---|---|---|
rms | number | The level, 0 to 1, compared with getMicLevel. |
lsmp.voice.setVolume
ClientLua Β· JSlsmp.voice.setVolume(volume)lsmp.voice.setVolume(volume: number): voidThe volume of every voice this player hears.
| Parameter | Type | Description |
|---|---|---|
volume | number | 0 to 4; 1 is normal. |
lsmp.voice.setPlayerVolume
ClientLua Β· JSlsmp.voice.setPlayerVolume(playerId, volume)lsmp.voice.setPlayerVolume(playerId: number, volume: number): voidThe 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The speaker. |
volume | number | 0 to 4; 0 silences them. |
lsmp.voice.setChannelVolume
ClientLua Β· JSlsmp.voice.setChannelVolume(channel, volume)lsmp.voice.setChannelVolume(channel: string | number, volume: number): voidThe volume of one channel, for this player only.
For example, a quieter radio than the voices around.
| Parameter | Type | Description |
|---|---|---|
channel | string|hashOut | A channel name or hash. |
volume | number | 0 to 4. |
Server API
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.foreigncapability. - 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
entityExistsand the model before acting.
Creating and deleting
lsmp.createEntity
ServerLua Β· JSlsmp.createEntity(type, model, position [, opts]) --> integer?lsmp.createEntity(type: string, model: number|string, position: Vec3Like, opts?: CreateEntityOptions): number | nullCreates 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.
| Parameter | Type | Description |
|---|---|---|
type | string | "vehicle", "ped" or "object". |
model | hash | Model name or hash (not 0). |
position | vec3 | Where to create it. |
opts opt | CreateEntityOptions | See the table below. |
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).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).| Option | Type | Default | Description |
|---|---|---|---|
heading | degrees | 0 | Facing (yaw). Exclusive with rotation. |
rotation | rotation | β | Full rotation {x, y, z} in degrees (pitch, roll, yaw). |
owner | playerId | β | The player who simulates it first. Its dimension is used when dimension is not given. |
dimension | dimension | 0 | The dimension to create it in. |
ownerPolicy | string | "auto" | Who may simulate it: see owner policies. |
lifePolicy | string | "whileRelevant" | When it is deleted: see life policies. |
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") endconst 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 Β· JSlsmp.deleteEntity(netId) --> booleanlsmp.deleteEntity(netId: number): booleanDeletes an entity.
Entities created by another resource or by a client need the entities.foreign capability. A player's ped cannot be deleted.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
boolean: false with not-found, permission, or invalid (a player's ped).lsmp.entityExists
ServerLua Β· JSlsmp.entityExists(netId) --> booleanlsmp.entityExists(netId: number): booleanWhether a netId designates a live entity.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
booleanReading
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 Β· JSlsmp.getEntityCoords(netId) --> Vector3?lsmp.getEntityCoords(netId: number): Vec3 | nullThe last synchronized position.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
Vector3?: nil/null if the entity is unknown.Vec3 | null: nil/null if the entity is unknown.lsmp.getEntityModel
ServerLua Β· JSlsmp.getEntityModel(netId) --> integer?lsmp.getEntityModel(netId: number): number | nullThe model hash, unsigned.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
integer?: nil/null if unknown.number | null: nil/null if unknown.lsmp.getEntityType
ServerLua Β· JSlsmp.getEntityType(netId) --> string?lsmp.getEntityType(netId: number): string | nullThe entity type.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
string?: "vehicle", "ped", "object" or "playerPed"; nil/null if unknown.string | null: "vehicle", "ped", "object" or "playerPed"; nil/null if unknown.lsmp.getEntityState
ServerLua Β· JSlsmp.getEntityState(netId) --> EntityState?lsmp.getEntityState(netId: number): EntityState | nullA consistent snapshot of what the server knows about an entity.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
EntityState?: See the table; nil/null if unknown.EntityState | null: See the table; nil/null if unknown.| Field | Type | Description |
|---|---|---|
coords | Vector3 | Position. |
model | hash | Model, unsigned. |
type | string | Entity type. |
owner | playerId? | Player simulating it; absent when orphan. |
dimension | dimension | Its dimension. |
lastSyncMs | ms? | Age of the last update; absent if never synchronized. |
vehicle | netId? | For a ped: the vehicle it is in. |
seat | integer? | For a ped in a vehicle: its seat (0 = driver). |
local s = lsmp.getEntityState(netId)
if s and s.type == "ped" and s.vehicle then
lsmp.log("in vehicle " .. s.vehicle .. ", seat " .. s.seat)
endconst s = lsmp.getEntityState(netId);
if (s?.type === "ped" && s.vehicle !== null) lsmp.log(`in vehicle ${s.vehicle}, seat ${s.seat}`);lsmp.getEntities
ServerLua Β· JSlsmp.getEntities([opts]) --> {integer}lsmp.getEntities(opts?: QueryOptions): Uint32ArrayThe netIds of all networked entities, optionally filtered.
| Parameter | Type | Description |
|---|---|---|
opts opt | QueryOptions | { types, dimension }: a list of entity types (default all) and one dimension (default all). |
{integer}: The netIds.Uint32Array: The netIds.local vehicles = lsmp.getEntities({ types = { "vehicle" }, dimension = 0 })
lsmp.log(#vehicles .. " vehicles in the main world")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 Β· JSlsmp.getVehicleOccupants(vehicle) --> {SeatOccupant}?lsmp.getVehicleOccupants(vehicle: number): SeatOccupant[] | nullThe occupied seats of a vehicle.
| Parameter | Type | Description |
|---|---|---|
vehicle | netId | The vehicle. |
{SeatOccupant}?: A list of { seat, ped } (seat 0 = driver), or nil/null if it is not a known vehicle.SeatOccupant[] | null: A list of { seat, ped } (seat 0 = driver), or nil/null if it is not a known vehicle.for _, o in ipairs(lsmp.getVehicleOccupants(car) or {}) do
lsmp.log("seat " .. o.seat .. ": ped " .. o.ped)
endfor (const { seat, ped } of lsmp.getVehicleOccupants(car) ?? []) lsmp.log(`seat ${seat}: ped ${ped}`);lsmp.getPedInVehicleSeat
ServerLua Β· JSlsmp.getPedInVehicleSeat(vehicle, seat) --> integer?lsmp.getPedInVehicleSeat(vehicle: number, seat: number): number | nullThe ped in one seat of a vehicle.
| Parameter | Type | Description |
|---|---|---|
vehicle | netId | The vehicle. |
seat | integer | 0 = driver, 1 and up = passengers. |
integer?: The ped's netId, or nil/null if the seat is empty or the vehicle unknown.number | null: The ped's netId, or nil/null if the seat is empty or the vehicle unknown.lsmp.getVehiclePedIsIn
ServerLua Β· JSlsmp.getVehiclePedIsIn(ped) --> integer?lsmp.getVehiclePedIsIn(ped: number): number | nullThe vehicle a ped is in.
| Parameter | Type | Description |
|---|---|---|
ped | netId | The ped (a player's ped too: see lsmp.getPlayerPed). |
integer?: The vehicle's netId, or nil/null.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 Β· JSlsmp.createPickup(pickupHash, position [, opts]) --> integer?lsmp.createPickup(pickupHash: number|string, position: Vec3Like, opts?: PickupOptions): number | nullCreates a pickup owned by the calling resource.
| Parameter | Type | Description |
|---|---|---|
pickupHash | hash | Pickup type: a PICKUP_* name or its hash. |
position | vec3 | Where to place it. |
opts opt | PickupOptions | See the table below. |
integer?: The pickup's netId, or nil/null with limit or permission (client entities disabled in that dimension).number | null: The pickup's netId, or nil/null with limit or permission (client entities disabled in that dimension).| Option | Type | Default | Description |
|---|---|---|---|
amount | integer | 0 | Amount granted (money, ammo...). |
dimension | dimension | 0 | Dimension. |
lifetimeMs | ms | 0 | Removed after this time (at most 24 h); 0 never expires. Removal happens within one second after the deadline. |
model | hash | the type's model | Another model to show. |
collectors | list of playerId | anyone | Only these players (at most 64) may collect it. |
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)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 Β· JSlsmp.setPickupCollectors(netId, players) --> booleanlsmp.setPickupCollectors(netId: number, players: number[] | null): booleanRestricts who may collect a pickup.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The pickup. |
players | list | nil | Up to 64 playerIds; nil/null lets anyone collect it. |
boolean: false with not-found or permission (pickup of another resource without entities.foreign).Constant
lsmp.EntityType
SharedLua Β· JSlsmp.EntityTypelsmp.EntityTypeEntity type strings.
lsmp.EntityType.Vehicle = "vehicle" Β· lsmp.EntityType.Ped = "ped" Β· lsmp.EntityType.Object = "object" Β· lsmp.EntityType.PlayerPed = "playerPed"
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.
| Reason | Meaning |
|---|---|
"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 Β· JSlsmp.getEntityOwner(netId) --> integer?lsmp.getEntityOwner(netId: number): number | nullThe player simulating an entity.
On the server, tell an orphan entity from an unknown one with lsmp.entityExists.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
integer?: A playerId; nil/null if the entity is orphan or unknown.number | null: A playerId; nil/null if the entity is orphan or unknown.lsmp.setEntityOwner
ServerLua Β· JSlsmp.setEntityOwner(netId, playerId) --> booleanlsmp.setEntityOwner(netId: number, playerId: number | null): booleanGives 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.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
playerId | playerId? | The new owner, in the same dimension as the entity; nil/null makes it orphan. |
boolean: false with not-found (entity or player), invalid (other dimension, or the policy forbids it) or permission.Owner policies
| Policy | Who 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 Β· JSlsmp.setEntityOwnerPolicy(netId, policy) --> booleanlsmp.setEntityOwnerPolicy(netId: number, policy: string): booleanSets how ownership of an entity may change.
Switching to "server" or "frozen" removes the current owner at once.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
policy | string | "auto", "pinned", "server" or "frozen". |
boolean: false with not-found, or permission (entity of another resource without entities.foreign).local car = lsmp.createEntity("vehicle", "police", position, { owner = playerId })
lsmp.setEntityOwnerPolicy(car, "pinned") -- stays on this playerconst car = lsmp.createEntity("vehicle", "police", position, { owner: playerId });
lsmp.setEntityOwnerPolicy(car, "pinned"); // stays on this playerLife policies
| Policy | When 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 Β· JSlsmp.setEntityLifePolicy(netId, policy) --> booleanlsmp.setEntityLifePolicy(netId: number, policy: string): booleanSets when the engine may delete an entity.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
policy | string | "whileRelevant", "keep" or "withCreator". |
boolean: 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.
| Field | Type | Description |
|---|---|---|
type | string | "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). |
target | netId or string | For follow, flee, combat: a netId, "nearestPlayer" or "owner" (the owner's ped). The strings are resolved again by each owner. |
position | vec3 | Anchor or destination. |
radius | meters | Wander radius, follow distance, guard radius. |
group | hash | Relationship group. |
accuracy | integer | Shooting accuracy, 0..100. |
keepTask | boolean | Keep the task even when the game would replace it (recommended for any lasting AI). |
mission | boolean | Mark as a mission entity: not cleaned up with the ambient population. |
run | boolean | Run instead of walk. |
hatesPlayers | boolean | Hostile 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 Β· JSlsmp.setEntityIntent(netId, intent) --> booleanlsmp.setEntityIntent(netId: number, intent: EntityIntent): booleanSets the replicated AI intent of a ped.
A mistyped or out-of-range field raises.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
intent | EntityIntent | See the table above. |
boolean: false with not-found, or permission (entity of another resource without entities.foreign).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,
})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 Β· JSlsmp.clearEntityIntent(netId) --> booleanlsmp.clearEntityIntent(netId: number): booleanRemoves the intent of a ped.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
boolean: false with not-found, or permission (entity of another resource without entities.foreign).Constants
lsmp.OwnerChangeReason
ServerLua Β· JSlsmp.OwnerChangeReasonlsmp.OwnerChangeReasonThe 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 Β· JSlsmp.OwnerPolicylsmp.OwnerPolicyOwner policies.
lsmp.OwnerPolicy.Auto = "auto" Β· lsmp.OwnerPolicy.Pinned = "pinned" Β· lsmp.OwnerPolicy.Server = "server" Β· lsmp.OwnerPolicy.Frozen = "frozen"
lsmp.LifePolicy
ServerLua Β· JSlsmp.LifePolicylsmp.LifePolicyLife policies.
lsmp.LifePolicy.WhileRelevant = "whileRelevant" Β· lsmp.LifePolicy.Keep = "keep" Β· lsmp.LifePolicy.WithCreator = "withCreator"
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.managecapability (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 Β· JSlsmp.setPlayerDimension(playerId, dimension) --> booleanlsmp.setPlayerDimension(playerId: number, dimension: number): booleanMoves 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
dimension | dimension | The dimension, 0..65535. |
boolean: false with not-found or permission.local function enterArena(playerId, arena)
local car = lsmp.getVehiclePedIsIn(lsmp.getPlayerPed(playerId))
lsmp.setPlayerDimension(playerId, arena)
if car then lsmp.setEntityDimension(car, arena) end
endfunction enterArena(playerId, arena) {
const car = lsmp.getVehiclePedIsIn(lsmp.getPlayerPed(playerId));
lsmp.setPlayerDimension(playerId, arena);
if (car !== null) lsmp.setEntityDimension(car, arena);
}lsmp.setEntityDimension
ServerLua Β· JSlsmp.setEntityDimension(netId, dimension) --> booleanlsmp.setEntityDimension(netId: number, dimension: number): booleanMoves an entity to another dimension.
A player's ped cannot be moved alone: move the player.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
dimension | dimension | The dimension, 0..65535. |
boolean: false with not-found, invalid (a player's ped) or permission.lsmp.getEntityDimension
ServerLua Β· JSlsmp.getEntityDimension(netId) --> integer?lsmp.getEntityDimension(netId: number): number | nullThe dimension of an entity.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
integer?: nil/null if the entity is unknown.number | null: nil/null if the entity is unknown.lsmp.getPlayersInDimension
ServerLua Β· JSlsmp.getPlayersInDimension(dimension) --> {integer}lsmp.getPlayersInDimension(dimension: number): number[]The players currently in a dimension.
| Parameter | Type | Description |
|---|---|---|
dimension | dimension | The dimension, 0..65535. |
{integer}: A list of playerIds, possibly empty.number[]: A list of playerIds, possibly empty.Dimension settings
| Setting | Default | Effect |
|---|---|---|
| population | on in dimension 0 | Ambient pedestrians and traffic. Turning it off stops the games of the players in the dimension from creating them. |
| client entities | on (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 Β· JSlsmp.setDimensionPopulation(dimension, enabled) --> booleanlsmp.setDimensionPopulation(dimension: number, enabled: boolean): booleanTurns ambient population on or off in a dimension.
| Parameter | Type | Description |
|---|---|---|
dimension | dimension | The dimension, 0..65535. |
enabled | boolean | Required: true or false. |
boolean: false with permission.lsmp.setDimensionPopulation(12, false)
lsmp.setDimensionClientEntities(12, false)lsmp.setDimensionPopulation(12, false);
lsmp.setDimensionClientEntities(12, false);lsmp.isDimensionPopulationEnabled
SharedLua Β· JSlsmp.isDimensionPopulationEnabled(dimension) --> boolean?lsmp.isDimensionPopulationEnabled(dimension: number): boolean | nullWhether ambient population runs in a dimension.
On a client, only the local player's dimension is known: other dimensions return nil/null.
| Parameter | Type | Description |
|---|---|---|
dimension | dimension | The dimension, 0..65535. |
boolean?boolean | nulllsmp.setDimensionClientEntities
ServerLua Β· JSlsmp.setDimensionClientEntities(dimension, enabled) --> booleanlsmp.setDimensionClientEntities(dimension: number, enabled: boolean): booleanLets 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.
| Parameter | Type | Description |
|---|---|---|
dimension | dimension | The dimension, 0..65535. |
enabled | boolean | Required: true or false. |
boolean: false with permission.lsmp.isDimensionClientEntitiesEnabled
ServerLua Β· JSlsmp.isDimensionClientEntitiesEnabled(dimension) --> booleanlsmp.isDimensionClientEntitiesEnabled(dimension: number): booleanWhether clients may create entities in a dimension.
| Parameter | Type | Description |
|---|---|---|
dimension | dimension | The dimension, 0..65535. |
boolean: true by default.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:
| Field | Type | Description |
|---|---|---|
name | string | The name they connect with. |
lsmpId | int? | Their account, nil/null for a guest. |
guest | boolean | true for a guest. |
verified | boolean | true when the LS:MP network confirmed the account; otherwise it is only what the client says. |
ip | string? | The address of the connection. Needs the players.identity capability. |
hwid | string? | 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) | function | Refuse, with the sentence the player reads (256 bytes at most). |
- Any refusal wins. A handler that returns without calling
p.denylets 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.
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)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.');
});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.
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 Β· JSlsmp.kickPlayer(playerId [, reason]) --> booleanlsmp.kickPlayer(playerId: number, reason?: string): booleanDisconnect a player.
playerLeave fires with the reason "kick" and your text as detail.
Needs the players.kick capability.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
reason opt | string | Shown to the player, 256 bytes at most. |
boolean: true if the player was connected.| Failure code | When |
|---|---|
not-found | Unknown player. |
permission | The resource does not hold players.kick. |
lsmp.banPlayer
ServerLua Β· JSlsmp.banPlayer(playerId [, opts]) --> {string}?lsmp.banPlayer(playerId: number, opts?: BanOptions): string[] | nullBan 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
opts opt | BanOptions | See BanOptions. |
{string}?: The identifier types actually banned, or nil/null if the player is unknown or the capability is missing.string[] | null: The identifier types actually banned, or nil/null if the player is unknown or the capability is missing.| Failure code | When |
|---|---|
not-found | Unknown player. |
permission | The resource does not hold players.ban. |
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)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 Β· JSlsmp.removeBan(type, value) --> booleanlsmp.removeBan(type: string, value: string | number): booleanLift a ban.
Needs the players.ban capability.
| Parameter | Type | Description |
|---|---|---|
type | string | "lsmp", "hwid", "ip" or "name". |
value | string|int | The banned value. For "lsmp", the account number is accepted. |
boolean: true if a ban was lifted.| Failure code | When |
|---|---|
not-found | No such ban. |
permission | The 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 Β· JSlsmp.addToWhitelist(type, value [, note]) --> booleanlsmp.addToWhitelist(type: string, value: string | number, note?: string): booleanAdd an entry to the whitelist.
Needs the players.whitelist capability.
| Parameter | Type | Description |
|---|---|---|
type | string | "lsmp", "ip" or "name". |
value | string|int | The value. For "lsmp", the account number is accepted. |
note opt | string | Shown in the admin panel. |
boolean: true if the entry was added.| Failure code | When |
|---|---|
exists | The entry is already there. |
permission | The resource does not hold players.whitelist. |
lsmp.removeFromWhitelist
ServerLua Β· JSlsmp.removeFromWhitelist(type, value) --> booleanlsmp.removeFromWhitelist(type: string, value: string | number): booleanRemove an entry from the whitelist.
Needs the players.whitelist capability.
| Parameter | Type | Description |
|---|---|---|
type | string | "lsmp", "ip" or "name". |
value | string|int | The value. |
boolean: true if the entry was removed.| Failure code | When |
|---|---|
not-found | No such entry. |
permission | The resource does not hold players.whitelist. |
lsmp.setWhitelistEnabled
ServerLua Β· JSlsmp.setWhitelistEnabled(enabled)lsmp.setWhitelistEnabled(enabled: boolean): voidSwitch the whitelist on or off.
Players already connected stay.
Needs the players.whitelist capability.
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | true to switch it on, false to switch it off. |
| Failure code | When |
|---|---|
permission | The resource does not hold players.whitelist. |
lsmp.isWhitelistEnabled
ServerLua Β· JSlsmp.isWhitelistEnabled() --> booleanlsmp.isWhitelistEnabled(): booleanWhether the whitelist is on.
boolean: true while it is on.Developer status
lsmp.setPlayerDev
ServerLua Β· JSlsmp.setPlayerDev(playerId, dev) --> booleanlsmp.setPlayerDev(playerId: number, dev: boolean): booleanAllow 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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
dev | boolean | true to allow, false to forbid. |
boolean: true if the player is connected.| Failure code | When |
|---|---|
not-found | Unknown player. |
permission | The resource does not hold players.dev. |
BanOptions
| Field | Type | Default | Description |
|---|---|---|---|
modes | strings | {"lsmp", "hwid"} | Identifier types to ban: "lsmp", "hwid", "ip". |
reason | string | β | Shown to the player and in the admin panel. |
durationMs | ms | permanent | How long the ban lasts. |
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
ioand the file is never overwritten, so nothing is lost.
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))
endfunction 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));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 Β· JSlsmp.storage.get(key) --> any?lsmp.storage.get(key: string): Value | nullReads a stored value.
| Parameter | Type | Description |
|---|---|---|
key | string | Key: 1 to 256 bytes, any content. |
any?: The value, or nil/null if the key is absent; nil, "io" (JavaScript: null and getLastError() = "io") if the store is unreadable.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 Β· JSlsmp.storage.set(key, value) --> booleanlsmp.storage.set(key: string, value: Value): booleanStores a value, or deletes the key when the value is nil/null.
A value over 64 KiB encoded raises.
| Parameter | Type | Description |
|---|---|---|
key | string | Key: 1 to 256 bytes, any content. |
value | value | The value; nil/null deletes the key. |
boolean: false with limit (the store would exceed 16 MiB) or io (unreadable store).local ok, err = lsmp.storage.set("house:12", { owner = 4211, price = 250000, locked = true })
if not ok then lsmp.error("cannot save house: " .. err) endif (!lsmp.storage.set("house:12", { owner: 4211, price: 250000, locked: true })) {
lsmp.error(`cannot save house: ${lsmp.getLastError()}`);
}lsmp.storage.delete
ServerLua Β· JSlsmp.storage.delete(key) --> booleanlsmp.storage.delete(key: string): booleanDeletes a key.
| Parameter | Type | Description |
|---|---|---|
key | string | Key: 1 to 256 bytes, any content. |
boolean: false if the key was absent.lsmp.storage.keys
ServerLua Β· JSlsmp.storage.keys([prefix]) --> {string}lsmp.storage.keys(prefix: string = ""): string[]The keys that start with a prefix, sorted.
| Parameter | Type | Description |
|---|---|---|
prefix opt | string | Prefix; empty lists every key. Default: "" |
{string}: The keys.string[]: The keys.lsmp.storage.flush
ServerLua Β· JSlsmp.storage.flush([cb]) --> boolean, errlsmp.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.
boolean, err: true once the store is on disk; fails with io if the write failed.Promise<boolean>: true once the store is on disk; fails with io if the write failed.lsmp.storage.set("config:motd", "Welcome!")
lsmp.storage.flush(function(ok, err)
if not ok then lsmp.error("flush failed: " .. err) end
end)lsmp.storage.set("config:motd", "Welcome!");
lsmp.storage.flush().catch((e) => lsmp.error(`flush failed: ${e.code}`));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.
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
NULLislsmp.nullin Lua andnullin JavaScript, in results and in parameters. Integers beyond 2^53 areBigIntin 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 Β· JSlsmp.mysql.createPool(opts) --> MysqlPool?lsmp.mysql.createPool(opts: MysqlPoolOptions): MysqlPool | nullCreates a connection pool.
| Parameter | Type | Description |
|---|---|---|
opts | MysqlPoolOptions | Connection settings (table below). |
MysqlPool?: The pool, or nil/null with permission (sandboxed resource) or limit (8 pools per resource).MysqlPool | null: The pool, or nil/null with permission (sandboxed resource) or limit (8 pools per resource).| Option | Type | Default | Description |
|---|---|---|---|
host | string | "127.0.0.1" | Server address. |
port | integer | 3306 | Server port. |
user | string | required | User name. |
password | string | "" | Password. |
database | string | β | Default database. |
charset | string | "utf8mb4" | "utf8mb4", "utf8", "latin1" or "binary". |
connectionLimit | integer | 8 | Connections at most, 1..64. |
connectTimeoutMs | ms | 10000 | Deadline to open a connection. |
queryTimeoutMs | ms | 0 | A query running longer fails with timeout and its connection is closed. 0 = no limit. |
local db = lsmp.mysql.createPool({
host = "127.0.0.1", user = "game", password = "secret", database = "lsmp",
connectionLimit = 4, queryTimeoutMs = 5000,
})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 Β· JSpool:query(sql [, params] [, cb]) --> MysqlResult, errpool.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 }.
| Parameter | Type | Description |
|---|---|---|
sql | string | The statement, with ? placeholders. |
params opt | list | Values for the placeholders, in order: numbers, strings, booleans, lsmp.null/null. |
MysqlResult, err: The rows, or the write summary.Promise<MysqlResult>: The rows, or the write summary.-- 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 })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 Β· JSpool:transaction(fn [, cb]) --> any, errpool.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.
| Parameter | Type | Description |
|---|---|---|
fn | fn | fn(tx); in Lua it may suspend on tx:query. |
any, err: What fn returned.Promise<Value>: What fn returned.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)) endasync 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 Β· JSpool:close([cb]) --> boolean, errpool.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.
boolean, err: true when closed.Promise<boolean>: true when closed.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 withpermission. - Use
/in paths on every system.
| Code | When |
|---|---|
not-found | The file or folder does not exist. |
exists | mkdir on an existing path, writeFile with exclusive on an existing file. |
permission | Refused by the sandbox or by the system. |
invalid | Malformed path, a folder where a file is expected, a folder that is not empty, append with exclusive. |
limit | File larger than 512 MiB to read, or not enough memory. |
io | Any other disk error. |
Failures come with details { message } (third value in Lua, message of the Error in JavaScript).
Data folder
lsmp.getDataPath
ServerLua Β· JSlsmp.getDataPath() --> stringlsmp.getDataPath(): stringThe 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.
string: The path, without a trailing /.string: The path, without a trailing /.local file = lsmp.getDataPath() .. "/scores.json"const file = `${lsmp.getDataPath()}/scores.json`;Files
lsmp.fs.readFile
ServerLua Β· JSlsmp.fs.readFile(path [, opts] [, cb]) --> string|string, errlsmp.fs.readFile(path: string, opts?: ReadFileOptions): Promise<string | Uint8Array>Reads a whole file (512 MiB at most). Asynchronous.
| Parameter | Type | Description |
|---|---|---|
path | string | Absolute, or relative to the server folder. |
opts opt | ReadFileOptions | { binary = true } returns bytes (Uint8Array in JavaScript); text (UTF-8) by default. |
string, err: The content.Promise<string | Uint8Array>: The content.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)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 Β· JSlsmp.fs.writeFile(path, data [, opts] [, cb]) --> boolean, errlsmp.fs.writeFile(path: string, data: string|Uint8Array|ArrayBuffer, opts?: WriteFileOptions): Promise<boolean>Writes a file, replacing it or appending to it. Asynchronous.
| Parameter | Type | Description |
|---|---|---|
path | string | Absolute, or relative to the server folder. |
data | data | A string, or bytes (lsmp.bytes/string in Lua; Uint8Array or ArrayBuffer in JavaScript). |
opts opt | WriteFileOptions | { append = false, exclusive = false }: append adds at the end; exclusive fails with exists if the file exists. Not both. |
boolean, err: true when written.Promise<boolean>: true when written.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)lsmp.fs.writeFile(`${lsmp.getDataPath()}/chat.log`, `${line}\n`, { append: true })
.catch((e) => lsmp.warn(`log write failed: ${e.code}`));lsmp.fs.rename
ServerLua Β· JSlsmp.fs.rename(from, to [, cb]) --> boolean, errlsmp.fs.rename(from: string, to: string): Promise<boolean>Renames or moves a file or folder. Asynchronous.
| Parameter | Type | Description |
|---|---|---|
from | string | Current path. |
to | string | New path. |
boolean, errPromise<boolean>lsmp.fs.remove
ServerLua Β· JSlsmp.fs.remove(path [, opts] [, cb]) --> boolean, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
path | string | Absolute, or relative to the server folder. |
opts opt | RemoveOptions | { recursive = false }. |
boolean, errPromise<boolean>Folders
lsmp.fs.mkdir
ServerLua Β· JSlsmp.fs.mkdir(path [, opts] [, cb]) --> boolean, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
path | string | Absolute, or relative to the server folder. |
opts opt | MkdirOptions | { recursive = false }. |
boolean, errPromise<boolean>lsmp.fs.list
ServerLua Β· JSlsmp.fs.list(path [, cb]) --> {DirEntry}, errlsmp.fs.list(path: string): Promise<DirEntry[]>The entries of a folder, sorted by name. Asynchronous.
| Parameter | Type | Description |
|---|---|---|
path | string | Absolute, or relative to the server folder. |
{DirEntry}, err: A list of { name, isDir, size, mtimeMs } (size 0 for folders).Promise<DirEntry[]>: A list of { name, isDir, size, mtimeMs } (size 0 for folders).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)(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 Β· JSlsmp.fs.stat(path [, cb]) --> FileStat?, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
path | string | Absolute, or relative to the server folder. |
FileStat?, err: { isDir, isFile, size, mtimeMs }, or nil/null if nothing is there.Promise<FileStat | null>: { isDir, isFile, size, mtimeMs }, or nil/null if nothing is there.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 get503. At most 256 requests are handled at once for one route (more get503) and 64 from one client address (more get429; 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
maxBodyBytesis answered413without calling the handler. A handler that does not answer withintimeoutMsleaves the client with504. A handler that raises gets the client a500, and the error is logged.
Serving
lsmp.http.serve
ServerLua Β· JSlsmp.http.serve(fn [, opts]) --> functionlsmp.http.serve(fn: Function, opts?: HttpServeOptions): () => booleanServes /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.
| Parameter | Type | Description |
|---|---|---|
fn | fn | fn(req) -> response. |
opts opt | HttpServeOptions | { maxBodyBytes = 1048576, timeoutMs = 10000 }: largest accepted body (at most 16 MiB) and answer deadline (at most 300 000 ms). |
function: The function that removes the route.() => boolean: The function that removes the route.| Request field | Type | Description |
|---|---|---|
method | string | Upper case: "GET", "POST"... |
path | string | The path after /res/<name>, starting with /. |
query | table | Query parameters, decoded: { page = "2" }. |
headers | table | Header names in lower case; repeated headers joined with ", ". |
body | string or bytes | The body; bytes (Uint8Array in JavaScript) when it is not valid UTF-8. |
address | string | The client's IP address. |
| Response field | Type | Default | Description |
|---|---|---|---|
status | integer | 200 | 100..599. |
headers | table | β | Header values are strings. Content-Length, Transfer-Encoding and Connection are set by the server and refused; a value with a line break raises. |
body | string or bytes | "" | The body. |
json | value | β | Sent as JSON with Content-Type: application/json. Not with body. |
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)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
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)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.
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.
| Option | Who may run the command |
|---|---|
(no permission) | The console, and players holding command.<name>. |
permission = "admin.kick" | The console, and players holding that permission. |
permission = false | The console and every player. |
restricted = true | The console only, never a player. |
Registering
lsmp.registerCommand
ServerLua Β· JSlsmp.registerCommand(name [, opts], fn) --> offlsmp.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 /.
| Parameter | Type | Description |
|---|---|---|
name | string | The command name. |
opts opt | CommandOptions | See CommandOptions. |
fn | fn | The handler. |
function: A function that unregisters this handler and returns true if it was registered.() => boolean: A function that unregisters this handler and returns true if it was registered.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.
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)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 Β· JSlsmp.unregisterCommand(name, fn) --> booleanlsmp.unregisterCommand(name: string, fn: Function): booleanRemove 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.
| Parameter | Type | Description |
|---|---|---|
name | string | The command name. |
fn | fn | The handler that was registered. |
boolean: true if the handler was registered.Running a command for a player
lsmp.executeCommand
ServerLua Β· JSlsmp.executeCommand(source, line) --> "ok" | "unknown" | "denied" | "invalid"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.
| Parameter | Type | Description |
|---|---|---|
source | playerId? | The player, or nil/null for console rights. |
line | string | The line, command name first, with or without a leading /. |
string: "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 code | When |
|---|---|
permission | The resource does not hold the capability. |
-- 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)// 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
| Field | Type | Default | Description |
|---|---|---|---|
help | string | β | One line shown by help in the console and in completions. |
params | list | β | Parameters shown while typing: { name, help, type, optional } each. Display only: the handler still receives strings. |
permission | string | boolean | "command.<name>" | The permission a player needs; false for every player. |
restricted | boolean | false | true: the console only, never a player. |
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
- Its dependencies start first. A dependency that is missing, disabled in
resources.jsonor failed makes the resourcefailed, with the reason in the log. - Its server scripts run in manifest order, JavaScript files before Lua files. In JavaScript, a module-level
awaitis waited for before the next file and before the resource counts as started, up toResourceStartTimeoutMs(server.cfg, 30 s by default). A Lua file runs until it ends or first waits (awhile true do lsmp.wait(...) endloop is fine). - 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. - Otherwise the resource is
startedandresourceStart(name)fires in every resource, itself included.
Stopping a resource
- It happens when the server shuts down (below). The resources that depend on it stop first.
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 toResourceStopGraceMs(2 s by default): this is the moment to save. Everything the resource owns still works during the handlers.- 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.
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)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
| Moment | What happens |
|---|---|
| Start | Every 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. |
| Shutdown | quit, 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. |
| Crash | Nothing of the above runs. Save important data as it changes, not only at shutdown. |
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)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.
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
lsmpfunctions 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).
| Capability | Covers | Operator resource | Marketplace mod |
|---|---|---|---|
perms.manage | Writes of lsmp.perms (groups, members, rules) | granted | granted |
commands.execute | lsmp.executeCommand(playerId, line): run a command for a player (their permissions still apply) | granted | granted |
commands.console | lsmp.executeCommand(nil, line): run a command with console rights | granted | granted |
players.kick | lsmp.kickPlayer | granted | granted |
players.ban | lsmp.banPlayer, lsmp.removeBan | granted | granted |
players.whitelist | Whitelist functions | granted | granted |
players.dev | lsmp.setPlayerDev | granted | granted |
players.identity | IP address and hardware id (getPlayerIdentifier(s), playerPreConnection) | granted | granted |
dimensions.manage | setPlayerDimension, setEntityDimension, setDimensionPopulation, setDimensionLockdown | granted | granted |
voice.manage | Writes of lsmp.voice (channels, members, muting) | granted | granted |
benefits.consume | lsmp.benefits.consume, consumeRevocation | granted | granted |
benefits.read | lsmp.benefits.fetch, events benefitGrant and benefitRevoke | granted | refused |
world.weather | lsmp.weather.set, resumeCycle, setSeed | granted | refused |
entities.foreign | Acting on entities, pickups and synchronized scenes created by another resource or by a client | granted | refused |
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.
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.
| Area | Sandboxed resource |
|---|---|
| Files | Its data folder (read and write) and its own package (lsmp.readResourceFile). Other folders only when listed in SandboxFsRead / SandboxFsWrite. Elsewhere: permission. |
| Outgoing network | As allowed by SandboxNetConnect (default: everything). Refused: permission. |
| Listening sockets | Only what SandboxNetListen allows (default: nothing). Use lsmp.http.serve instead. |
| Databases | lsmp.mysql.createPool fails with permission. |
| Environment variables | Only those listed in SandboxEnv (default NODE_ENV, TZ, LANG, LC_ALL). |
| Processes and native code | Refused: no child processes, no native modules, no access to the server process. |
| Lua standard library | Functions that reach outside (io, os.execute, load, debug...) raise an error that names the lsmp alternative. |
| Blocking code | Lua or JavaScript code that runs longer than SandboxWatchdogSec (default 10 s) without suspending is interrupted. |
Unsandboxing a resource gives it the machine, not extra capabilities, and granting a capability does not open the sandbox.
lsmp.isSandboxed
ServerLua Β· JSlsmp.isSandboxed() --> booleanlsmp.isSandboxed(): booleanWhether the calling resource runs in the sandbox.
booleanif lsmp.isSandboxed() then
lsmp.warn("MySQL disabled: set \"sandbox\": false for this resource in resources.json")
endif (lsmp.isSandboxed()) {
lsmp.warn('MySQL disabled: set "sandbox": false for this resource in resources.json');
}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.foreigncapability. Players' peds can always take part. - Scenes of a resource stop when it stops. A scene also stops when a participant disappears.
- Clients receive
syncSceneStartandsyncSceneStopfor each participant.
Scene definition
| Field | Type | Default | Description |
|---|---|---|---|
position | vec3 | required | Origin of the scene. |
rotation | rotation | {0, 0, 0} | Rotation of the origin, in degrees. |
rotationOrder | integer | 2 | Euler order of rotation, 0..5 (the game's usual order is 2). |
phase | number | 0 | Starting point, 0..1 of the animation. |
rate | number | 1 | Playback speed. |
holdLastFrame | boolean | false | Stay on the last frame at the end. |
looped | boolean | false | Loop. |
durationMs | ms | 0 | Stop the scene after this time; 0 = no limit. |
participants | list | required | 1 to 8 participants (below). |
| Participant field | Type | Default | Description |
|---|---|---|---|
netId | netId | required | The entity. |
dict | string | required | Animation dictionary (1 to 63 bytes). |
clip | string | required | Animation name (1 to 63 bytes). |
blendIn | number | 8 | Blend-in speed. |
blendOut | number | -8 | Blend-out speed. |
flags | integer | 0 | Game scene flags. |
ikFlags | integer | 0 | Game IK flags. |
offset | table | β | { x, y, z, heading } offset of this participant from the origin. |
Functions
lsmp.startSyncScene
ServerLua Β· JSlsmp.startSyncScene(def) --> integer?lsmp.startSyncScene(def: SyncSceneDef): number | nullStarts a synchronized scene played by every client.
A malformed definition (missing field, wrong type, more than 8 participants) raises.
| Parameter | Type | Description |
|---|---|---|
def | SyncSceneDef | The scene definition (tables above). |
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.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.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()) endconst 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 Β· JSlsmp.stopSyncScene(sceneId) --> booleanlsmp.stopSyncScene(sceneId: number): booleanStops a scene.
| Parameter | Type | Description |
|---|---|---|
sceneId | integer | The scene, as returned by startSyncScene. |
boolean: false with not-found or permission (scene of another resource).lsmp.setSyncScenePhase
ServerLua Β· JSlsmp.setSyncScenePhase(sceneId, phase [, rate]) --> booleanlsmp.setSyncScenePhase(sceneId: number, phase: number, rate?: number): booleanMoves a running scene to another point, and optionally changes its speed.
| Parameter | Type | Description |
|---|---|---|
sceneId | integer | The scene, as returned by startSyncScene. |
phase | number | 0..1. |
rate opt | number | New speed (>= 0); unchanged when absent. |
boolean: false with not-found or permission.lsmp.isSyncSceneActive
ServerLua Β· JSlsmp.isSyncSceneActive(sceneId) --> booleanlsmp.isSyncSceneActive(sceneId: number): booleanWhether a scene is running.
| Parameter | Type | Description |
|---|---|---|
sceneId | integer | The scene, as returned by startSyncScene. |
booleanlsmp.getEntitySyncScene
SharedLua Β· JSlsmp.getEntitySyncScene(netId) --> SyncSceneInfo?lsmp.getEntitySyncScene(netId: number): SyncSceneInfo | nullThe synchronized scene an entity is playing.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
SyncSceneInfo?: { sceneId, dict, clip }, or nil/null if it plays none.SyncSceneInfo | null: { sceneId, dict, clip }, or nil/null if it plays none.Client API
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.
- Resources start
Every client resource of the server runs its top-level code.
- Auto spawn
Once they all ran, the auto-spawn handler is called, once: the resource that set it with
setAutoSpawnHandlerpicks a place and callslsmp.spawn. A gamemode that spawns players itself turns this off withsetAutoSpawn(false). - Spawn
lsmp.spawnloads the world around the point, places the ped, closes the loading screen, and firesplayerSpawnon this client and on the server.
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 Β· JSlsmp.getLocalPlayer() --> integer?lsmp.getLocalPlayer(): number | nullThe 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.
integer?: The playerId, or nil/null outside a session.number | null: The playerId, or nil/null outside a session.lsmp.getGameScreen
ClientLua Β· JSlsmp.getGameScreen() --> ScreenSize?lsmp.getGameScreen(): ScreenSize | nullThe size of the game image, in pixels.
To convert pixel positions into the normalized 0..1 coordinates used by worldToScreen and the drawing natives.
ScreenSize?: { width, height }, or nil/null before the game window exists.ScreenSize | null: { width, height }, or nil/null before the game window exists.Spawning
lsmp.spawn
ClientLua Β· JSlsmp.spawn(position [, opts]) --> booleanlsmp.spawn(position: Vec3Like, opts?: SpawnOptions): booleanMake 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.
| Parameter | Type | Description |
|---|---|---|
position | vec3 | Where the feet go. |
opts opt | SpawnOptions | { heading, model }: heading in degrees (default 0), ped model as a hash or name (default: the current model). |
boolean: true if the spawn was started.| Failure code | When |
|---|---|
disconnected | Not in a session. |
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)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 Β· JSlsmp.setAutoSpawnHandler(fn)lsmp.setAutoSpawnHandler(fn: Function | null): voidSet 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.
| Parameter | Type | Description |
|---|---|---|
fn | fn? | The handler, or nil/null to remove this resource's. |
lsmp.setAutoSpawn
ClientLua Β· JSlsmp.setAutoSpawn(enabled)lsmp.setAutoSpawn(enabled: boolean): voidTurn 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.
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | false to keep the player hidden until a script spawns them. |
lsmp.closeLoadingScreen
ClientLua Β· JSlsmp.closeLoadingScreen()lsmp.closeLoadingScreen(): voidLift 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 Β· JSlsmp.resurrect(position [, opts]) --> booleanlsmp.resurrect(position: Vec3Like, opts?: ResurrectOptions): booleanBring 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.
| Parameter | Type | Description |
|---|---|---|
position | vec3 | Where the feet go. |
opts opt | ResurrectOptions | { heading } in degrees (default 0). |
boolean: true if the player was resurrected.| Failure code | When |
|---|---|
disconnected | Not in a session. |
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)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 Β· JSlsmp.disconnect([reason]) --> booleanlsmp.disconnect(reason?: string): booleanLeave the server.
The server sees playerLeave with the reason "quit" and your text as detail.
| Parameter | Type | Description |
|---|---|---|
reason opt | string | Why, 127 bytes at most. |
boolean: true if the client was in a session.| Failure code | When |
|---|---|
disconnected | Not in a session. |
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:
| Name | What it is | Used by |
|---|---|---|
| netId | The same number on the server and every client, for the entity's whole life. | lsmp functions, events, network messages, meta. |
| Handle | The 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 Β· JSlsmp.getEntityFromNetId(netId) --> integer?lsmp.getEntityFromNetId(netId: number): number | nullThe 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.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
integer?: The handle, or nil/null while the entity is not built on this client.number | null: The handle, or nil/null while the entity is not built on this client.| Failure code | When |
|---|---|
not-found | The entity is not built on this client. |
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
endasync 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 Β· JSlsmp.getNetIdFromEntity(entity) --> integer?lsmp.getNetIdFromEntity(entity: number): number | nullThe netId of a game handle.
| Parameter | Type | Description |
|---|---|---|
entity | handle | A game handle. |
integer?: The netId, or nil/null for an entity LS:MP does not network (a local prop, ambient traffic of this client only).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 code | When |
|---|---|
not-found | The 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 Β· JSlsmp.requestEntityOwnership(netId) --> booleanlsmp.requestEntityOwnership(netId: number): booleanAsk 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.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
boolean: true if the request was sent.| Failure code | When |
|---|---|
not-found | Unknown entity. |
disconnected | Not in a session. |
Events
| Event | Arguments | When |
|---|---|---|
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.
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 Β· JSlsmp.raycast(from, to [, opts]) --> RaycastResultlsmp.raycast(from: Vec3Like, to: Vec3Like, opts?: RaycastOptions): RaycastResultWhat 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.
| Parameter | Type | Description |
|---|---|---|
from | vec3 | Start of the line. |
to | vec3 | End of the line. |
opts opt | RaycastOptions | See RaycastOptions. |
RaycastResult: A RaycastResult.-- 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// 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 Β· JSlsmp.getGroundZ(position [, opts]) --> number?lsmp.getGroundZ(position: Vec3Like, opts?: GroundOptions): number | nullThe 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.
| Parameter | Type | Description |
|---|---|---|
position | vec3 | The point to look down from. |
opts opt | GroundOptions | { water }: true counts the water surface as ground (default false). |
number?: The height, or nil/null when no ground was found.number | null: The height, or nil/null when no ground was found.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)) endconst 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 Β· JSlsmp.worldToScreen(position) --> ScreenPointlsmp.worldToScreen(position: Vec3Like): ScreenPointWhere 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.
| Parameter | Type | Description |
|---|---|---|
position | vec3 | The world position. |
ScreenPoint: { x, y, onScreen }; onScreen is false behind the camera or outside the screen.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)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 Β· JSlsmp.getGamePool([opts]) --> {integer}lsmp.getGamePool(opts?: QueryOptions): Uint32ArrayThe 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.
| Parameter | Type | Description |
|---|---|---|
opts opt | QueryOptions | { types }: entity types to include, among "vehicle", "ped", "object" and "playerPed" (lsmp.EntityType); by default every type except player peds. |
{integer}: The handles (JS: Uint32Array).Uint32Array: The handles (JS: Uint32Array).local vehicles = lsmp.getGamePool({ types = { "vehicle" } })
lsmp.log(#vehicles .. " vehicles on this client")const vehicles = lsmp.getGamePool({ types: [lsmp.EntityType.Vehicle] });
lsmp.log(`${vehicles.length} vehicles on this client`);Shapes
RaycastOptions
| Field | Type | Default | Description |
|---|---|---|---|
flags | int | -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. |
ignore | handle | β | An entity the line goes through, usually the player's ped or vehicle. |
RaycastResult
| Field | Type | Default | Description |
|---|---|---|---|
hit | boolean | β | true if the line hit something. |
position | vec3? | β | Where. |
normal | vec3? | β | The surface direction at that point. |
entity | handle? | β | The entity hit; absent for the map. |
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.
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 Β· JSlsmp.hud.setMoney(wallet, bank) --> booleanlsmp.hud.setMoney(wallet: number, bank: number): booleanShow these amounts in the HUD.
| Parameter | Type | Description |
|---|---|---|
wallet | int | Cash, 0 to 2147483647. |
bank | int | Bank, 0 to 2147483647. |
boolean: true if the amounts are shown.| Failure code | When |
|---|---|
unavailable | The HUD cannot be changed at this moment (no session). |
lsmp.onServer("economy:balance", function(wallet, bank)
lsmp.hud.setMoney(wallet, bank)
end)lsmp.onServer('economy:balance', (wallet, bank) => {
lsmp.hud.setMoney(wallet, bank);
});lsmp.hud.resetMoney
ClientLua Β· JSlsmp.hud.resetMoney() --> booleanlsmp.hud.resetMoney(): booleanGive the money display back to the game.
boolean: true if this resource had set the money.lsmp.hud.getMoney
ClientLua Β· JSlsmp.hud.getMoney() --> HudMoney?lsmp.hud.getMoney(): HudMoney | nullThe amounts the HUD shows.
HudMoney?: { wallet, bank }, or nil/null when no script sets them.HudMoney | null: { wallet, bank }, or nil/null when no script sets them.Replay recording
lsmp.hud.hideReplayRecordingThisFrame
ClientLua Β· JSlsmp.hud.hideReplayRecordingThisFrame()lsmp.hud.hideReplayRecordingThisFrame(): voidHide 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).
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)lsmp.on('entityStreamIn', (netId, entity) => {
if (!isEntityAPed(entity) || !isPedAPlayer(entity)) return;
const blip = addBlipForEntity(entity);
setBlipSprite(blip, 1);
setBlipColour(blip, 0);
});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 Β· JSlsmp.outline.showEntity(entity [, opts]) --> booleanlsmp.outline.showEntity(entity: number, opts?: OutlineOptions): booleanOutline an entity, or change the style of this resource's outline on it.
| Parameter | Type | Description |
|---|---|---|
entity | handle | A game handle. |
opts opt | OutlineOptions | See OutlineOptions. |
boolean: true if the outline is drawn.| Failure code | When |
|---|---|
not-found | The handle is not usable, or the 32 outlines are taken. |
permission | Another resource outlines this entity. |
local vehicle = getVehiclePedIsIn(playerPedId(), false)
if vehicle ~= 0 then
lsmp.outline.showEntity(vehicle, { color = "#40beff", width = 3 })
endconst vehicle = getVehiclePedIsIn(playerPedId(), false);
if (vehicle) lsmp.outline.showEntity(vehicle, { color: '#40beff', width: 3 });lsmp.outline.hideEntity
ClientLua Β· JSlsmp.outline.hideEntity(entity) --> booleanlsmp.outline.hideEntity(entity: number): booleanRemove this resource's outline from an entity.
| Parameter | Type | Description |
|---|---|---|
entity | handle | A game handle. |
boolean: true if this resource outlined it.lsmp.outline.hasEntity
ClientLua Β· JSlsmp.outline.hasEntity(entity) --> booleanlsmp.outline.hasEntity(entity: number): booleanWhether this resource outlines an entity.
| Parameter | Type | Description |
|---|---|---|
entity | handle | A game handle. |
boolean: true while the outline is drawn.lsmp.outline.showGeometry
ClientLua Β· JSlsmp.outline.showGeometry(entity, geomKey [, opts]) --> booleanlsmp.outline.showGeometry(entity: number | null, geomKey: number, opts?: OutlineOptions): booleanOutline 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.
| Parameter | Type | Description |
|---|---|---|
entity | handle? | The entity the piece belongs to, or nil/null for the map. |
geomKey | uint | The geometry key. |
opts opt | OutlineOptions | See OutlineOptions; position helps to find map geometry again. |
boolean: true if the outline is drawn.| Failure code | When |
|---|---|
not-found | No such geometry, or the 32 outlines are taken. |
permission | Another resource outlines this geometry. |
lsmp.outline.hideGeometry
ClientLua Β· JSlsmp.outline.hideGeometry(entity, geomKey) --> booleanlsmp.outline.hideGeometry(entity: number | null, geomKey: number): booleanRemove this resource's outline from a piece of geometry.
| Parameter | Type | Description |
|---|---|---|
entity | handle? | The entity, or nil/null for the map. |
geomKey | uint | The geometry key. |
boolean: true if this resource outlined it.lsmp.outline.hasGeometry
ClientLua Β· JSlsmp.outline.hasGeometry(entity, geomKey) --> booleanlsmp.outline.hasGeometry(entity: number | null, geomKey: number): booleanWhether this resource outlines a piece of geometry.
| Parameter | Type | Description |
|---|---|---|
entity | handle? | The entity, or nil/null for the map. |
geomKey | uint | The geometry key. |
boolean: true while the outline is drawn.lsmp.outline.clear
ClientLua Β· JSlsmp.outline.clear() --> integerlsmp.outline.clear(): numberRemove every outline of this resource.
integer: How many were removed.number: How many were removed.lsmp.outline.count
ClientLua Β· JSlsmp.outline.count() --> integerlsmp.outline.count(): numberHow many outlines this resource draws.
integer: The number of outlines.number: The number of outlines.OutlineOptions
| Field | Type | Default | Description |
|---|---|---|---|
color | color | "#ffffff" | Any color form. An alpha below 255 makes it translucent. |
width | number | 2 | Thickness in pixels, up to 64. |
mode | string | "outline" | "outline", "fill" (the whole silhouette) or "dashed". |
softness | number | 0 | Blur of the edge, 0 to 1. |
dashPeriod | number | β | Length of a dash and its gap, in pixels ("dashed"). |
dashSpeed | number | β | How fast the dashes move, in pixels per second ("dashed"). |
position | vec3 | β | 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 Β· JSlsmp.selection.setEnabled(enabled) --> booleanlsmp.selection.setEnabled(enabled: boolean): booleanHold the picker on, or release this resource's hold.
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | true to hold it, false to release. |
boolean: true if this resource's hold changed.| Failure code | When |
|---|---|
unavailable | The picker is not available on this client. |
lsmp.selection.isEnabled
ClientLua Β· JSlsmp.selection.isEnabled() --> booleanlsmp.selection.isEnabled(): booleanWhether the picker runs (for any resource).
boolean: true while it runs.lsmp.selection.setPoint
ClientLua Β· JSlsmp.selection.setPoint(point)lsmp.selection.setPoint(point: Vec2Like | null): voidPick 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.
| Parameter | Type | Description |
|---|---|---|
point | vec2? | { x, y }, normalized 0..1, or nil/null to follow the cursor again. |
lsmp.selection.setPointPixel
ClientLua Β· JSlsmp.selection.setPointPixel(x, y)lsmp.selection.setPointPixel(x: number, y: number): voidPick at a fixed point of the screen, in pixels.
| Parameter | Type | Description |
|---|---|---|
x | number | From the left edge. |
y | number | From the top edge. |
lsmp.selection.get
ClientLua Β· JSlsmp.selection.get() --> Selection?lsmp.selection.get(): Selection | nullWhat is under the pick point.
See Selection. Already up to date inside a selectionChange handler.
Selection?: The selection, or nil/null while the picker is off.Selection | null: The selection, or nil/null while the picker is off.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)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 Β· JSlsmp.selection.setOutline(enabled [, opts]) --> booleanlsmp.selection.setOutline(enabled: boolean, opts?: SelectionOutlineOptions): booleanKeep 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.
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | true to show, false to stop. |
opts opt | SelectionOutlineOptions | { entity, geometry }, each an OutlineOptions. |
boolean: true if the setting was applied.| Failure code | When |
|---|---|
unavailable | The picker is not available on this client. |
lsmp.selection.setToolOpen
ClientLua Β· JSlsmp.selection.setToolOpen(open) --> booleanlsmp.selection.setToolOpen(open: boolean): booleanOpen 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.
| Parameter | Type | Description |
|---|---|---|
open | boolean | true to open, false to close. |
boolean: true if the request was applied.| Failure code | When |
|---|---|
unavailable | The tool is not available on this client. |
lsmp.selection.isToolOpen
ClientLua Β· JSlsmp.selection.isToolOpen() --> booleanlsmp.selection.isToolOpen(): booleanWhether the inspection tool is open.
boolean: true while it is open.selectionChange (entity, geomKey, valid) fires when what is under the pick point changes, not every frame.
Selection
| Field | Type | Default | Description |
|---|---|---|---|
serial | int | β | Increases with each new reading. |
valid | boolean | β | false when nothing is under the point (sky, nothing drawn). |
entity | handle? | β | The entity picked; absent for buildings and terrain. |
model | hash? | β | Its model. Read it here: some picked entities have no model information for natives. |
type | string? | β | "vehicle", "ped" or "object". |
baked | boolean | β | true for map geometry (buildings, terrain). |
distance | meters? | β | From the camera. |
position | vec3? | β | The world position under the point. |
point | vec2 | β | The pick point, normalized. |
geometry | table? | β | The piece of geometry: key (for showGeometry), and its triangle and vertex counts. |
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 Β· JSlsmp.registerCommand(name [, opts], fn) --> offlsmp.registerCommand(name: string, opts: CommandOptions | undefined, fn: Function): () => booleanAdd 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.
| Parameter | Type | Description |
|---|---|---|
name | string | The command name. |
opts opt | CommandOptions | { help, params }: see CommandOptions (permission and restricted are server only). |
fn | fn | The handler. |
function: A function that unregisters this handler and returns true if it was registered.() => boolean: A function that unregisters this handler and returns true if it was registered.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)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.
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)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
asyncfunction.
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 browser | 3D browser | |
|---|---|---|
| Created with | lsmp.createBrowser | lsmp.createBrowser3D |
| Shown | Over the game, in a rectangle of the screen | Nowhere by itself: its texture replaces a game texture (lsmp.replaceTexture) |
| Mouse and keyboard | When it has the focus (both, or one of the two) | None |
| Addresses | https://, rsc://<resource>/β¦; http://localhost outside a server | https://, rsc://<its own resource>/β¦ |
| At most | 16 per resource, 128 on the client | 4 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().
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)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 };
}
});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 Β· JSlsmp.createBrowser(url [, opts]) --> Browser?lsmp.createBrowser(url: string, opts?: BrowserOptions): Browser | nullOpen 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.
| Parameter | Type | Description |
|---|---|---|
url | string | https://β¦, 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 opt | BrowserOptions | Options, below. |
Browser?: The handle, or nil on failure.Browser | null: The handle, or null on failure.| BrowserOptions | Type | Default | Description |
|---|---|---|---|
bounds | Rect | full screen | { x, y, width, height } as fractions of the screen, 0..1. The rectangle must fit on the screen. |
boundsPixel | Rect | The same in pixels. Do not give both bounds and boundsPixel. | |
visible | boolean | true | Shown at once. |
focus | boolean | false | Takes the mouse and keyboard at once. See Focus. |
cursor | boolean | true | With focus: false takes the keyboard only, with no cursor (a chat field). Same as the cursor option of browser.setFocus. |
keepInput | boolean | false | With focus: true takes the mouse only, the player keeps playing. Same as the keepInput option of browser.setFocus. |
zIndex | integer | 0 | Stacking among this server's 2D pages, -1000..1000; higher is on top. |
browser.destroy
ClientLua Β· JSbrowser:destroy()browser.destroy(): voidClose 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 Β· JSbrowser:isValid() --> booleanbrowser.isValid(): booleanWhether the browser is still open.
boolean: false once destroyed, by you or when the resource stopped.browser.id
ClientLua Β· JSbrowser.id --> integerbrowser.id: numberRead-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 Β· JSbrowser:setUrl(url) --> booleanbrowser.setUrl(url: string): booleanLoad 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.
| Parameter | Type | Description |
|---|---|---|
url | string | The new address. A refused address raises a RangeError. |
boolean: false if the browser was destroyed.browser.setBounds
ClientLua Β· JSbrowser:setBounds(rect) --> booleanbrowser.setBounds(rect: Rect): booleanMove and resize the page, as fractions of the screen.
| Parameter | Type | Description |
|---|---|---|
rect | Rect | { x, y, width, height }, 0..1; width and height above 0, and the rectangle inside the screen. Otherwise RangeError. |
boolean: false if the browser was destroyed.browser.setBoundsPixel
ClientLua Β· JSbrowser:setBoundsPixel(rect) --> booleanbrowser.setBoundsPixel(rect: Rect): booleanMove 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.
| Parameter | Type | Description |
|---|---|---|
rect | Rect | { x, y, width, height } in pixels, non-negative, width and height above 0, at most 16384 to the far edge. |
boolean: false if the browser was destroyed.browser.setVisible
ClientLua Β· JSbrowser:setVisible(visible) --> booleanbrowser.setVisible(visible: boolean): booleanShow 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.
| Parameter | Type | Description |
|---|---|---|
visible | boolean | true to show. |
boolean: false if the browser was destroyed.browser.isVisible
ClientLua Β· JSbrowser:isVisible() --> booleanbrowser.isVisible(): booleanWhether the page is shown.
boolean: false when hidden or destroyed.browser.setFocus
ClientLua Β· JSbrowser:setFocus(focused [, opts]) --> booleanbrowser.setFocus(focused: boolean, opts?: FocusOptions): booleanGive 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.
| Parameter | Type | Description |
|---|---|---|
focused | boolean | true to take the input, false to give it back to the game. |
opts opt | FocusOptions | Options, below. |
boolean: false if the browser was destroyed.| FocusOptions | Type | Default | Description |
|---|---|---|---|
cursor | boolean | true | true: the mouse and the keyboard, with the cursor. false: the keyboard only, with no cursor and no clicks. No effect when focused is false. |
keepInput | boolean | false | true: 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. |
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)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 Β· JSbrowser:hasFocus() --> booleanbrowser.hasFocus(): booleanWhether the page holds the focus (the mouse and keyboard, or the keyboard alone).
boolean: false after setFocus(false), after the player's Ctrl+Alt+Backspace, or once destroyed.browser.setZIndex
ClientLua Β· JSbrowser:setZIndex(z) --> booleanbrowser.setZIndex(z: number): booleanChange the stacking order among this server's 2D pages.
LS:MP's own interface (menu, console, payment window) always stays above every server page.
| Parameter | Type | Description |
|---|---|---|
z | integer | -1000..1000; higher is on top. |
boolean: 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 Β· JSbrowser:emit(event, ...) --> booleanbrowser.emit(event: string, ...args: Value[]): booleanSend 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.
| Parameter | Type | Description |
|---|---|---|
event | string | Event name, 1 to 128 characters. |
... opt | Value | Up to 32 values. |
boolean: false if the browser was destroyed or the queue is full (code limit).browser.on
ClientLua Β· JSbrowser:on(event, fn) --> functionbrowser.on(event: string, fn: Function): () => booleanHandle 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.
| Parameter | Type | Description |
|---|---|---|
event | string | Event name, or "load", "loadError", "focusLost", "crash". |
fn | function | fn(...args); its return value answers a page call. |
function: Call it to remove the handler; it returns true if it was registered.() => boolean: Call it to remove the handler; it returns true if it was registered.browser.off
ClientLua Β· JSbrowser:off(event, fn) --> booleanbrowser.off(event: string, fn: Function): booleanRemove a handler registered with on.
| Parameter | Type | Description |
|---|---|---|
event | string | The event name. |
fn | function | The same function that was registered. |
boolean: true if it was registered.browser.call
ClientLua Β· JSbrowser:call(event, ... [, cb]) --> any, errbrowser.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):
| Parameter | Type | Description |
|---|---|---|
event | string | CallOptions | The handler's name, or { name, timeoutMs }: timeoutMs from 1 to 300000, default 10000. |
... opt | Value | Up to 32 values. |
any, err: The page's answer, or nil and a code.Promise<Value>: Resolves with the page's answer; rejects with an error whose code is one of the codes below.| Code | Meaning |
|---|---|
timeout | No answer in time. |
no-handler | The page has no lsmp.on handler for this name. |
error | The page's handler threw, or its answer could not be sent. Details in the page's console (DevTools). |
cancelled | The browser was destroyed, or the page navigated away, before answering. |
limit | 1024 calls are already waiting on this browser. |
unavailable | The game's web engine is not running. |
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)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.
| Event | Arguments | When |
|---|---|---|
load | url | The page's document is ready (its DOMContentLoaded). Queued emits are delivered right after. Fires again after each navigation. |
loadError | url, code | The page could not load. code: "refused-url" (address not allowed), "network", "http-<status>" (such as "http-404"), "aborted". |
focusLost | 2D only. The player took the input back (Ctrl+Alt+Backspace), or another page took the focus. hasFocus() is now false. | |
crash | reason | The 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 Β· JSlsmp.createBrowser3D(url [, opts]) --> Browser3D?lsmp.createBrowser3D(url: string, opts?: Browser3DOptions): Browser3D | nullOpen 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.
| Parameter | Type | Description |
|---|---|---|
url | string | https://β¦, or rsc://<this resource>/β¦: a 3D page cannot show another resource's pages. |
opts opt | Browser3DOptions | width and height of the page and its texture in pixels, 1..4096, default 1024; fps, frames rendered per second, 1..60, default 30. |
Browser3D?: The handle, or nil on failure.Browser3D | null: The handle, or null on failure.-- 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)// 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 Β· JSbrowser3d:destroy()browser3d.destroy(): voidClose 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 Β· JSbrowser3d:isValid() --> booleanbrowser3d.isValid(): booleanWhether the 3D browser is still open.
boolean: false once destroyed.browser3d.id
ClientLua Β· JSbrowser3d.id --> integerbrowser3d.id: numberRead-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 Β· JSbrowser3d:setUrl(url) --> booleanbrowser3d.setUrl(url: string): booleanLoad another page, with the same address rules as createBrowser3D.
| Parameter | Type | Description |
|---|---|---|
url | string | The new address. A refused address raises a RangeError. |
boolean: false if the browser was destroyed.browser3d.setSize
ClientLua Β· JSbrowser3d:setSize(width, height) --> booleanbrowser3d.setSize(width: number, height: number): booleanResize the page and its texture.
The texture handle stays the same; bindings made with replaceTexture follow.
| Parameter | Type | Description |
|---|---|---|
width | integer | 1..4096 pixels. |
height | integer | 1..4096 pixels. |
boolean: false if the browser was destroyed.browser3d.getTexture
ClientLua Β· JSbrowser3d:getTexture() --> integerbrowser3d.getTexture(): numberThe 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.
integer: Texture handle.browser3d.emit
ClientLua Β· JSbrowser3d:emit(event, ...) --> booleanbrowser3d.emit(event: string, ...args: Value[]): booleanSend an event to the page, as browser.emit.
| Parameter | Type | Description |
|---|---|---|
event | string | Event name. |
... opt | Value | Up to 32 values. |
boolean: false if the browser was destroyed or the queue is full.browser3d.on
ClientLua Β· JSbrowser3d:on(event, fn) --> functionbrowser3d.on(event: string, fn: Function): () => booleanHandle 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).
| Parameter | Type | Description |
|---|---|---|
event | string | Event name or lifecycle event. |
fn | function | fn(...args); its return value answers a page call. |
function: Call it to remove the handler.() => boolean: Call it to remove the handler.browser3d.off
ClientLua Β· JSbrowser3d:off(event, fn) --> booleanbrowser3d.off(event: string, fn: Function): booleanRemove a handler, as browser.off.
| Parameter | Type | Description |
|---|---|---|
event | string | The event name. |
fn | function | The same function that was registered. |
boolean: true if it was registered.browser3d.call
ClientLua Β· JSbrowser3d:call(event, ... [, cb]) --> any, errbrowser3d.call(event: string | CallOptions, ...args: Value[]): Promise<Value>Call the page's handler and get its answer, as browser.call, with the same codes.
| Parameter | Type | Description |
|---|---|---|
event | string | CallOptions | The handler's name, or { name, timeoutMs }. |
... opt | Value | Up to 32 values. |
any, err: The answer, or nil and a code.Promise<Value>: Resolves with the answer; rejects with a coded error.Values and limits
| Script value | In the page |
|---|---|
nil / null | null (a missing argument too) |
| boolean, string | the same |
| number | number. Integers beyond 2^53, NaN and infinities raise a TypeError. |
| table with keys / object | object |
| sequence / array | array |
| 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:, andload,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
emitis dropped and acallfails withlimit. A page event no script handler listens to is dropped (acallfails withno-handler).
URL rules
rsc://<resource>/β¦serves the files of a resource'swebuifolders. A 3D browser may only open its own resource's pages.https://opens any public web page. The page still gets thelsmpobject, linked to your script: only open sites you trust.http://is refused, excepthttp://localhost,http://127.0.0.1andhttp://[::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
cursorset tofalsetakes 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
keepInputset totruekeeps 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
isDisabledControlPressedor 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
focusLostand 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,sessionStorageand 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.getUserMediashows 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
BroadcastChannelwork as on the web. fetchand ES modules work for the files of the page's own resource (rsc://), and forhttps://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 storersc://files: uselocalStorageor IndexedDB. Anhttps://2D page is an embedded frame: its cookies needSameSite=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,confirmandpromptdo 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.
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.
- Create
Create the scene with
lsmp.createScene, at the size of the image you want. - Add entities
Add peds, vehicles or objects with
scene.addEntity, each with its own position and rotation. - 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. - Shoot or render live
Call
scene.shotfor an image, orscene.enableRenderto render continuously into a texture. - Destroy
Destroy the scene when you are done. The scenes of a resource are destroyed when it stops.
-- 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// 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();
}
}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 Β· JSlsmp.createScene([opts]) --> Scene?lsmp.createScene(opts?: SceneOptions): Scene | nullCreate 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.
| Parameter | Type | Description |
|---|---|---|
opts opt | SceneOptions | See scene options. |
Scene?: The scene, or nil and a code.Scene | null: The scene, or null with the code in lsmp.getLastError().scene.configure
ClientLua Β· JSscene:configure(opts) --> booleanscene.configure(opts: SceneOptions): booleanChange 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.
| Parameter | Type | Description |
|---|---|---|
opts | SceneOptions | The options to change. |
boolean: true when applied; false otherwise, with the code in lsmp.getLastError(): limit, unavailable, error.Scene options
| Option | Type | Default | Meaning |
|---|---|---|---|
width, height | int | 512 | Size of the images in pixels, 16 to 4096. |
supersample | int | 1 | 1 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. |
background | color | boolean | false | false: 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 Β· JSscene:addEntity(entity [, opts]) --> integer?scene.addEntity(entity: number, opts?: SceneTransform): number | nullDraw 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.
| Parameter | Type | Description |
|---|---|---|
entity | handle | A ped, vehicle or object handle. |
opts opt | SceneTransform | { position, rotation } in scene space, both default { 0, 0, 0 }. |
integer?: An id for this entity in this scene (not the entity handle).-- 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 } })// 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 Β· JSscene:setEntityTransform(id, opts) --> booleanscene.setEntityTransform(id: number, opts: SceneTransform): booleanMove 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.
| Parameter | Type | Description |
|---|---|---|
id | int | The id from addEntity. |
opts | SceneTransform | { position, rotation }. |
boolean: true when applied; false otherwise, with the code in lsmp.getLastError(): not-found.scene.removeEntity
ClientLua Β· JSscene:removeEntity(id) --> booleanscene.removeEntity(id: number): booleanTake an entity out of the scene. The entity itself is left as it is.
| Parameter | Type | Description |
|---|---|---|
id | int | The id from addEntity. |
boolean: true if it was in the scene.scene.clearEntities
ClientLua Β· JSscene:clearEntities() --> integerscene.clearEntities(): numberTake every entity out of the scene.
integer: How many were removed.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 Β· JSscene:setCamera(opts) --> booleanscene.setCamera(opts: SceneCamera): booleanPlace 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.
| Parameter | Type | Description |
|---|---|---|
opts | SceneCamera | See the table below. |
boolean: true when applied; false otherwise, with the code in lsmp.getLastError(): invalid.-- 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 })// 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 });| Option | Type | Default | Meaning |
|---|---|---|---|
position | vec3 | { 0, 3, -0.1 } | Where the camera stands. |
lookAt | vec3 | { 0, 0, -0.1 } | The point it looks at. |
rotation | rotation | Angles in degrees, instead of lookAt. | |
fov | degrees | 40 | Vertical field of view, 1 to 170. |
near, far | meters | 0.05, 500 | Clipping distances. near above 0, far above near. |
ortho | boolean | false | Orthographic projection: no perspective, for icons and blueprints. |
orthoHeight | meters | 2 | With 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 Β· JSscene:setLightPreset(preset) --> booleanscene.setLightPreset(preset: string): booleanReplace 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.
| Parameter | Type | Description |
|---|---|---|
preset | string | "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". |
boolean: true when applied; false otherwise, with the code in lsmp.getLastError().scene.setAmbient
ClientLua Β· JSscene:setAmbient(opts) --> booleanscene.setAmbient(opts: SceneAmbient): booleanSet 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.
| Parameter | Type | Description |
|---|---|---|
opts | SceneAmbient | color (the same from every direction, default white), topColor (the light from above, default white), intensity (0 to 64, default 1). |
boolean: true when applied; false otherwise, with the code in lsmp.getLastError().scene.setKeyLight
ClientLua Β· JSscene:setKeyLight(opts) --> booleanscene.setKeyLight(opts: SceneLight | null): booleanTurn 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.
| Parameter | Type | Description |
|---|---|---|
opts | table? | 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). |
boolean: true when applied; false otherwise, with the code in lsmp.getLastError().scene:setKeyLight({ direction = { 0.5, -0.5, -0.7 }, color = "#fff4e0", intensity = 8 })scene.setKeyLight({ direction: { x: 0.5, y: -0.5, z: -0.7 }, color: '#fff4e0', intensity: 8 });scene.setExposure
ClientLua Β· JSscene:setExposure(ev) --> booleanscene.setExposure(ev: number): booleanBrighten or darken the whole image.
Every light, ambient included, is multiplied by 2^ev: 1 doubles the light, -1 halves it. Default 0.
| Parameter | Type | Description |
|---|---|---|
ev | number | -16 to 16. |
boolean: true when applied; false otherwise, with the code in lsmp.getLastError().scene.addLight
ClientLua Β· JSscene:addLight([opts]) --> integer?scene.addLight(opts?: SceneLight): number | nullAdd 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.
| Parameter | Type | Description |
|---|---|---|
opts opt | SceneLight | See the table below. |
integer?: The id of the light.-- 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 })// 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 });| Option | Type | Default | Meaning |
|---|---|---|---|
type | string | "point" | "point", "spot" or "capsule" (a light along a segment, like a neon tube). |
position | vec3 | { 0, 2.5, 1.5 } | In front of the subject, above it. |
direction | vec3 | towards the origin | Spot: where it points. Capsule: the axis of the tube. |
color | color | white | |
intensity | number | 4 | 0 to 1024. |
range | meters | 10 | Reach, 0.01 to 1000: nothing is lit beyond it. |
falloff | number | 8 | How the light fades towards range, 0.01 to 64: high values keep it strong, then fade it quickly near the edge. |
innerAngle, outerAngle | degrees | 20, 35 | Spot: half-angles of the cone, 0 to 89.9. Full light inside innerAngle, none beyond outerAngle. |
length | meters | 1 | Capsule: length of the tube, 0 to 1000. |
scene.updateLight
ClientLua Β· JSscene:updateLight(id, opts) --> booleanscene.updateLight(id: number, opts: SceneLight): booleanChange a light added with addLight. Only the fields you give change.
| Parameter | Type | Description |
|---|---|---|
id | int | The id from addLight. |
opts | SceneLight | The fields to change. |
boolean: true when applied; false otherwise, with the code in lsmp.getLastError(): not-found.scene.removeLight
ClientLua Β· JSscene:removeLight(id) --> booleanscene.removeLight(id: number): booleanRemove a light added with addLight.
| Parameter | Type | Description |
|---|---|---|
id | int | The id from addLight. |
boolean: true if the light existed.scene.clearLights
ClientLua Β· JSscene:clearLights() --> integerscene.clearLights(): numberRemove every light, those of the preset included. The ambient and key lights stay.
integer: How many lights added with addLight were removed.Shots
scene.shot
ClientLua Β· JSscene:shot([opts] [, cb]) --> ShotResult, errscene.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.
| Parameter | Type | Description |
|---|---|---|
opts opt | ShotOptions | width 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). |
ShotResult, err: The result below, or nil and a code.Promise<ShotResult>: Resolves with the result below; rejects with a code.| Field | Type | Meaning |
|---|---|---|
width, height | int | Size of the image. |
format | string | The format of data. |
data | bytes | The encoded image: a string in Lua, a Uint8Array in JavaScript. |
dataUrl | string? | The data URL when asked for; nil / null otherwise. |
entities | int | Entities drawn in the image. |
missing | int | Entities of the scene that no longer exist, skipped. |
frames | int | Frames the shot waited before it was rendered. |
ms | ms | Time from the request to the image. |
-- 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// 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:
setOverlaydraws it in a rectangle, above the game's HUD and below LS:MP pages. - As a game texture:
getTexturereturns a texture forlsmp.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.
-- 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)// 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 Β· JSscene:enableRender(enabled [, opts]) --> booleanscene.enableRender(enabled: boolean, opts?: RenderOptions): booleanStart 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.
| Parameter | Type | Description |
|---|---|---|
enabled | boolean | true to render, false to stop. |
opts opt | RenderOptions | fps: frames per second, 1 to 60, default 30. |
boolean: true when applied; false otherwise, with the code in lsmp.getLastError(): limit (8 scenes already render live), unavailable, error.scene.invalidate
ClientLua Β· JSscene:invalidate() --> booleanscene.invalidate(): booleanAsk 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.
boolean: false if the scene does not render live.scene.getTexture
ClientLua Β· JSscene:getTexture() --> integer?scene.getTexture(): number | nullThe 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.
integer?: A texture handle, or nil / null before enableRender.scene.setOverlay
ClientLua Β· JSscene:setOverlay(opts) --> booleanscene.setOverlay(opts: SceneOverlay | boolean): booleanShow 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.
| Parameter | Type | Description |
|---|---|---|
opts | SceneOverlay | boolean | visible (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). |
boolean: true when applied; false otherwise, with the code in lsmp.getLastError(): limit, unavailable, error.scene.getRenderInfo
ClientLua Β· JSscene:getRenderInfo() --> SceneRenderInfo?scene.getRenderInfo(): SceneRenderInfo | nullHow the live rendering is doing.
SceneRenderInfo?: 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).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 Β· JSscene:destroy()scene.destroy(): voidDestroy 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 Β· JSscene:isValid() --> booleanscene.isValid(): booleanfalse once the scene was destroyed, by the script or because its resource stopped.
booleanOn 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
| Limit | Value |
|---|---|
| Scenes | 8 per resource, 16 on the client |
| Pixels, all scenes together | About 8 million, counted at the rendered size (width Γ supersample by height Γ supersample) |
| Entities per scene | 32 |
| Lights per scene | 32, the key light included; 8 of them light transparent surfaces |
| Shots in flight | 4 per scene |
| Scenes rendering live | 8 on the client; beyond the per-frame pixel budget, live scenes take turns (skipped) |
Its scenes are destroyed, its texture replacements are restored, and the Promises or callbacks of pending shots never complete.
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.
-- 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",
})// 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 Β· JSlsmp.createTexture(source) --> integer?lsmp.createTexture(source: TextureSource): number | nullMake 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.
| Parameter | Type | Description |
|---|---|---|
source | TextureSource | Where the image comes from: { file }, { data } or { pixels, width, height, format }. See the table below. |
integer?: The texture handle, or nil and a code.number | null: The texture handle, or null with the code in lsmp.getLastError().-- 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 })// 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 source | Type | Meaning |
|---|---|---|
file | string | Path of an image file of this resource, relative to its root, with / separators and no ... |
data | bytes | The content of a PNG, JPEG, WebP or DDS file: a string in Lua, a Uint8Array or an ArrayBuffer in JavaScript. |
pixels | bytes | Raw pixels, 4 bytes each, rows from top to bottom, without padding: exactly width * height * 4 bytes. |
width, height | integer | Size of pixels, 1 to 4096 each. Required with pixels, refused otherwise. |
format | string | Byte 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.
| Format | What is read |
|---|---|
| PNG | Every color type and bit depth, with transparency. |
| JPEG | Baseline and progressive, 8 bits per channel. |
| WebP | Lossy and lossless, with transparency. Animated WebP files are refused. |
| DDS | Uncompressed 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. |
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 Β· JSlsmp.getTextureInfo(texture) --> TextureInfo?lsmp.getTextureInfo(texture: number): TextureInfo | nullSize 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".
| Parameter | Type | Description |
|---|---|---|
texture | int | A texture handle of this resource. |
TextureInfo?: { width, height, state }, or nil and not-found when the handle is unknown or belongs to another resource.TextureInfo | null: { width, height, state }, or null with not-found when the handle is unknown or belongs to another resource.-- 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)// 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 Β· JSlsmp.releaseTexture(texture) --> booleanlsmp.releaseTexture(texture: number): booleanFree 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.
| Parameter | Type | Description |
|---|---|---|
texture | int | A handle returned by createTexture. |
boolean: true when the texture was freed; false and a code otherwise.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 Β· JSlsmp.replaceTexture(texture, target) --> integer?lsmp.replaceTexture(texture: number, target: TextureTarget): number | nullShow 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.
| Parameter | Type | Description |
|---|---|---|
texture | int | A texture handle of this resource. |
target | TextureTarget | { 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. |
integer?: The id of the replacement, or nil and a code.number | null: The id of the replacement, or null with the code in lsmp.getLastError().-- 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// 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 Β· JSlsmp.restoreTexture(bindId) --> booleanlsmp.restoreTexture(bindId: number): booleanGive the game its original texture back.
| Parameter | Type | Description |
|---|---|---|
bindId | int | The id returned by replaceTexture. |
boolean: 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.
-- 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// 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);
}
});
}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
| Limit | Value |
|---|---|
| Size of an image | 4096 pixels on a side |
Size of an image file (file, data) | 96 MiB |
Textures made by createTexture | 256 per resource |
| Pixels of those textures | 256 MiB per resource, counted as width * height * 4 bytes |
Its textures are freed and its replacements are restored: the game shows its own textures again.
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 Β· JSlsmp.captureCamera(camera [, opts] [, cb]) --> CaptureResult, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
camera | handle | A scripted camera, from createCam, createCamWithParams and the camera natives. |
opts opt | CaptureOptions | See the options. |
CaptureResult, err: The result, or nil and a code.Promise<CaptureResult>: Resolves with the result; rejects with a code.-- 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// 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
| Option | Type | Default | Meaning |
|---|---|---|---|
width, height | int | 512 | Output size in pixels, 16 to 4096. |
format | string | "webp" | "png", "jpeg" or "webp". WebP keeps the transparency of PNG at a fraction of its size. |
quality | int | 90 | JPEG and WebP quality, 0 to 100. WebP at 100 is lossless. |
settleFrames | int | 2 | Frames rendered before the shot, 0 to 30, so that streaming and exposure settle after the camera moved. |
fov | degrees | the camera's | Vertical field of view of the image, above 0 and below 180. |
dataUrl | boolean | false | Also return a data:image/...;base64,... URL, ready for an <img> in a page. |
chromaKey | boolean | color | table | off | true 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
| Field | Type | Meaning |
|---|---|---|
width, height | int | Size of the image. |
format | string | The format of data. |
data | bytes | The encoded image: a string in Lua, a Uint8Array in JavaScript. |
dataUrl | string? | The data URL when dataUrl was asked for; nil / null otherwise. |
sourceWidth, sourceHeight | int | Size of the region of the frame that was read. |
upscaled | boolean | true when the output is larger than that region: ask for a smaller size, or play at a higher resolution, for a sharper image. |
frames | int | Frames the capture took. |
ms | ms | Time the capture took. |
Its pending captures are dropped: their Promise or callback never completes. The player sees nothing of it.
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 Β· JSlsmp.mountResource(name [, cb]) --> boolean, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
name | name | The resource name. |
boolean, err: true once the resource is started; false and a code otherwise.Promise<boolean>: Resolves with true once the resource is started; rejects with a code otherwise.local ok, err = lsmp.mountResource("island_b")
if ok then
lsmp.emitServer("island:ready")
else
lsmp.warn("island_b did not start: " .. err)
endasync 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 Β· JSlsmp.unmountResource(name [, cb]) --> boolean, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
name | name | The resource name. |
boolean, err: true once the resource is stopped; false and a code otherwise.Promise<boolean>: Resolves with true once the resource is stopped; rejects with a code otherwise.-- Swap two maps, in order.
local ok = lsmp.unmountResource("island_a")
if ok then lsmp.mountResource("island_b") end// 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 Β· JSlsmp.resources.loadStreamSet(resource, set [, cb]) --> boolean, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
resource | name | A mounted resource. |
set | string | The name of one of its stream sets. Exact, case-sensitive. |
boolean, err: true once the set is loaded; false and a code otherwise.Promise<boolean>: Resolves with true once the set is loaded; rejects with a code otherwise.local ok, err = lsmp.resources.loadStreamSet("las-venturas", "addons")
if not ok then lsmp.warn("addons: " .. err) endlsmp.resources.loadStreamSet('las-venturas', 'addons')
.catch((err) => lsmp.warn(`addons: ${err.code}`));lsmp.resources.unloadStreamSet
ClientLua Β· JSlsmp.resources.unloadStreamSet(resource, set [, cb]) --> boolean, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
resource | name | A mounted resource. |
set | string | The name of the set. |
boolean, err: true once the set is unloaded; false and a code otherwise.Promise<boolean>: Resolves with true once the set is unloaded; rejects with a code otherwise.lsmp.resources.getStreamSetState
ClientLua Β· JSlsmp.resources.getStreamSetState(resource, set) --> string?lsmp.resources.getStreamSetState(resource: string, set: string): string | nullThe state of a stream set, read at once.
| Parameter | Type | Description |
|---|---|---|
resource | name | A resource. |
set | string | The name of the set. |
string?: "unloaded", "loading", "loaded" or "unloading"; nil / null when the resource is not mounted or has no set of that name.if lsmp.resources.getStreamSetState("las-venturas", "addons") == "unloaded" then
lsmp.resources.loadStreamSet("las-venturas", "addons")
endif (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 Β· JSlsmp.resources.unregisterAssets(names [, cb]) --> AssetJobResult, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
names Lua only | {string} | 1 to 1,048,576 asset names, each a non-empty string. |
names JavaScript only | string[] | 1 to 1,048,576 asset names, each a non-empty string. |
AssetJobResult, err: { done, failed }: names processed and names refused. A refused name is not a failure of the call.Promise<AssetJobResult>: Resolves with { done, failed }: names processed and names refused. A refused name does not reject the Promise.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))
endasync 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 Β· JSlsmp.resources.registerAssets(names [, cb]) --> AssetJobResult, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
names Lua only | {string} | 1 to 1,048,576 asset names. |
names JavaScript only | string[] | 1 to 1,048,576 asset names. |
AssetJobResult, err: { done, failed }: names processed and names refused. A refused name is not a failure of the call.Promise<AssetJobResult>: Resolves with { done, failed }: names processed and names refused. A refused name does not reject the Promise.lsmp.resources.getAssetState
ClientLua Β· JSlsmp.resources.getAssetState(name) --> string?lsmp.resources.getAssetState(name: string): string | nullThe state of one asset, read at once.
| Parameter | Type | Description |
|---|---|---|
name | string | Asset name, with its extension. |
string?: "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 Β· JSlsmp.resources.invalidateArchives(names [, cb]) --> AssetJobResult, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
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 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". |
AssetJobResult, err: { done, failed }: names processed and names refused. A refused name is not a failure of the call.Promise<AssetJobResult>: Resolves with { done, failed }: names processed and names refused. A refused name does not reject the Promise.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") endlsmp.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 Β· JSlsmp.resources.restoreArchives(names [, cb]) --> AssetJobResult, errlsmp.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.
| Parameter | Type | Description |
|---|---|---|
names Lua only | {string} | Archive names. |
names JavaScript only | string[] | Archive names. |
AssetJobResult, err: { done, failed }: names processed and names refused. A refused name is not a failure of the call.Promise<AssetJobResult>: Resolves with { done, failed }: names processed and names refused. A refused name does not reject the Promise.lsmp.resources.getArchiveState
ClientLua Β· JSlsmp.resources.getArchiveState(name) --> string?lsmp.resources.getArchiveState(name: string): string | nullThe state of one game archive, read at once.
| Parameter | Type | Description |
|---|---|---|
name | string | Archive name as the game registers it. |
string?: "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 Β· JSlsmp.resources.suspendScriptIpls([cb]) --> AssetJobResult, errlsmp.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.
AssetJobResult, err: { done, failed }: names processed and names refused. A refused name is not a failure of the call.Promise<AssetJobResult>: Resolves with { done, failed }: names processed and names refused. A refused name does not reject the Promise.local res, err = lsmp.resources.suspendScriptIpls()
if not res then lsmp.warn("IPLs: " .. err) endlsmp.resources.suspendScriptIpls().catch((err) => lsmp.warn(`IPLs: ${err.code}`));lsmp.resources.resumeScriptIpls
ClientLua Β· JSlsmp.resources.resumeScriptIpls([cb]) --> AssetJobResult, errlsmp.resources.resumeScriptIpls(): Promise<AssetJobResult>Give the story scripts their map pieces back.
Undoes suspendScriptIpls. Failure code: error.
AssetJobResult, err: { done, failed }: names processed and names refused. A refused name is not a failure of the call.Promise<AssetJobResult>: Resolves with { done, failed }: names processed and names refused. A refused name does not reject the Promise.lsmp.resources.suspendStoryScript
ClientLua Β· JSlsmp.resources.suspendStoryScript(name) --> stringlsmp.resources.suspendStoryScript(name: string): stringStop 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".
| Parameter | Type | Description |
|---|---|---|
name | string | The name of the game script, for example "blip_controller". |
string: "stopped", "loading", "running" (the state the script is in now), or "refused".if lsmp.resources.suspendStoryScript("blip_controller") == "refused" then
lsmp.warn("blip_controller cannot be stopped")
endif (lsmp.resources.suspendStoryScript('blip_controller') === 'refused') {
lsmp.warn('blip_controller cannot be stopped');
}lsmp.resources.resumeStoryScript
ClientLua Β· JSlsmp.resources.resumeStoryScript(name) --> stringlsmp.resources.resumeStoryScript(name: string): stringAllow a story script to run again.
Undoes suspendStoryScript for this resource. The game starts the script again when it needs it.
| Parameter | Type | Description |
|---|---|---|
name | string | The name of the game script. |
string: Same values as suspendStoryScript.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.
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
falsewith the codepermission. - 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/nullputs the default back.
lsmp.discord.setDetails
ClientLua Β· JSlsmp.discord.setDetails(text) --> booleanlsmp.discord.setDetails(text: string | null): booleanSet the first line of the card.
| Parameter | Type | Description |
|---|---|---|
text | string? | The text, or nil/null for the default. |
boolean: true if applied.| Failure code | When |
|---|---|
permission | The player turned the presence off. |
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)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 Β· JSlsmp.discord.setState(text) --> booleanlsmp.discord.setState(text: string | null): booleanSet the second line of the card.
| Parameter | Type | Description |
|---|---|---|
text | string? | The text, or nil/null for the default. |
boolean: true if applied.| Failure code | When |
|---|---|
permission | The player turned the presence off. |
lsmp.discord.setAsset
ClientLua Β· JSlsmp.discord.setAsset(slot, key [, hoverText]) --> booleanlsmp.discord.setAsset(slot: string, key: string | null, hoverText?: string): booleanSet 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.
| Parameter | Type | Description |
|---|---|---|
slot | string | "large" or "small". |
key | string? | The asset key or image address, or nil/null for none. |
hoverText opt | string | Text shown when the image is hovered, 128 bytes at most. |
boolean: true if applied.| Failure code | When |
|---|---|
permission | The player turned the presence off, or the server has no custom presence. |
lsmp.discord.setButton
ClientLua Β· JSlsmp.discord.setButton(index, label [, url]) --> booleanlsmp.discord.setButton(index: number, label: string | null, url?: string): booleanSet one of the two buttons of the card.
Needs a custom presence. A button opens its address in the browser of whoever clicks it.
| Parameter | Type | Description |
|---|---|---|
index | int | 0 or 1. |
label | string? | The button text, or nil/null to remove the button. |
url opt | string | An https:// address; required with a label. |
boolean: true if applied.| Failure code | When |
|---|---|
permission | The player turned the presence off, or the server has no custom presence. |
lsmp.discord.setAppId
ClientLua Β· JSlsmp.discord.setAppId(appId) --> booleanlsmp.discord.setAppId(appId: string): booleanShow 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.
| Parameter | Type | Description |
|---|---|---|
appId | string | The application id from the Discord developer portal: 17 to 20 digits, as a string. |
boolean: true if applied.| Failure code | When |
|---|---|
permission | The player turned the presence off, or the server has no custom presence. |
lsmp.discord.clear
ClientLua Β· JSlsmp.discord.clear()lsmp.discord.clear(): voidRemove everything this resource set.
The card goes back to what other resources set, or to the default.
Page API
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.
<!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>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)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
| Document | lsmp |
|---|---|
| The page loaded in a 2D or 3D browser of a resource | Yes, 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 page | No. |
| The page opened in an ordinary web browser, outside the game | No: 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
pageJSlsmp.emit(event: string, ...args: any[]): voidSend 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.
| Parameter | Type | Description |
|---|---|---|
event | string | Event name, 1 to 128 characters, no control characters. load, loadError, focusLost, crash and names starting with lsmp: are reserved. |
...args opt | any | Up to 32 JSON-compatible values; Uint8Array, ArrayBuffer and DataView travel as bytes. |
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
pageJSlsmp.on(event: string, fn: (...args) => any): () => booleanHandle 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.
| Parameter | Type | Description |
|---|---|---|
event | string | Event name, same rules as lsmp.emit. |
fn | function | fn(...args); its return value (or Promise) answers a script call. |
() => boolean: Call it to remove the handler.// 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
pageJSlsmp.off(event: string, fn: Function): booleanRemove a handler registered with lsmp.on.
Not available in Lua.
| Parameter | Type | Description |
|---|---|---|
event | string | The event name. |
fn | function | The same function that was registered. |
boolean: true if it was registered.lsmp.call
pageJSlsmp.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.
| Parameter | Type | Description |
|---|---|---|
event | string | { name, timeoutMs } | The handler's name, or an object with name and timeoutMs (1 to 300000, default 10000). |
...args opt | any | Up to 32 values. |
Promise<any>: Resolves with the script's answer (null when it returned nothing).err.code | Meaning |
|---|---|
timeout | No answer in time. |
no-handler | The script has no browser:on handler for this name. |
error | The script's handler raised, or its answer could not be sent. The details are in the client console (F8), never in the page. |
cancelled | The browser was destroyed or the page navigated away. |
limit | 1024 calls are already waiting. |
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
pageJSlsmp.version: stringThe LS:MP version, such as "0.6.254".
Not available in Lua.
lsmp.gameVersion
pageJSlsmp.gameVersion: stringThe game version, such as "1.0.1158.16".
Not available in Lua.
lsmp.gameBuild
pageJSlsmp.gameBuild: numberThe game build number, such as 1158.
Not available in Lua.
lsmp.language
pageJSlsmp.language: stringThe 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
pageJSlsmp.resource: stringThe name of the resource that owns this browser, such as "shop".
Not available in Lua.
Good to know
- Order: the script's
loadhandler runs once the page's document is ready (DOMContentLoaded). Register yourlsmp.onhandlers 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 getsloadagain. - 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.
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.
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
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.
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_COORDSissetEntityCoords,_GET_LAST_ENTITY_HIT_BY_ENTITYisgetLastEntityHitByEntity. - 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.hashfor 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 aTypeErrorthat 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).
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)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);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:
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 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-param | You 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-param | You 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 } |
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)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);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.
| Family | Natives | Accepted |
|---|---|---|
| HUD colors | replaceHudColour, replaceHudColourWithRgba | color 0 to 234 |
| HUD components | showHudComponentThisFrame, hideHudComponentThisFrame, setHudComponentPosition and related | 0 to 160, scripted components 0 to 29 |
| Vehicle windows | rollDownWindow, smashVehicleWindow, isVehicleWindowIntact and related | 0 to 7 |
| Vehicle doors | isVehicleDoorFullyOpen, getIsDoorValid, getVehicleIndividualDoorLockStatus | 0 to 6 |
| Tyres | setVehicleTyreFixed, getTyreHealth, setTyreHealth and related | 0 to 7 |
| Vehicle classes | getVehicleClassMaxBraking, getVehicleClassMaxTraction and related | 0 to 22 |
| Ped components | getPedDrawableVariation, getPedTextureVariation, getPedPaletteVariation | 0 to 11 |
| Combat attributes | setPedCombatAttributes | 0 to 90 |
| TV | setTvChannel, setTvChannelPlaylist, setTvChannelPlaylistAtHour | channel -1 (off, for setTvChannel) or 0 to 4, hour 0 to 23 |
| Text blocks | requestAdditionalText, hasAdditionalTextLoaded and related | slot 0 to 21, 0 to 22 to query |
| Markers | drawMarker, drawMarkerEx | type 0 to 44, finite position, size and rotation |
| Clock | setClockTime, advanceClockTimeTo, networkOverrideClockTime, setClockDate | hours 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.
| Calls | Result or scope |
|---|---|
getClosestRoad | Success, south and north endpoints, south and north lane counts, and median width. |
getGroupSize | Leader present as 0 or 1, then the number of followers. |
getMpOutfitDataFromMetadata | Pass { male, index } with a zero-based index. Returns success and a record with componentDrawables, componentTextures, propDrawables, propTextures and tattooOverlays. |
getPedHeadBlendData | Success and a record with six shape and skin IDs, three blend weights and Boolean isParent. |
getPedNearbyPeds, getPedNearbyVehicles, getAllVehicles | Count and a dense array of up to 256 game handles. Lua starts at index 1, and JavaScript at index 0. |
getPosFromFiredEvent | Success and the source position of the selected event type. |
getWeaponHudStats, getWeaponComponentHudStats | Success and a record with damage, speed, capacity, accuracy and range. |
addRope, attachEntitiesToRope | Load 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, playEntityScriptedAnim | Scripted animation on a resource-owned local ped, vehicle or object. Load each clip dictionary first. |
taskMoveNetworkByNameWithInitParams, taskMoveNetworkAdvancedByNameWithInitParams | Movement graphs on a resource-owned local ped. Clone override must be false. Flags may use only bits 0x04 and 0x08. |
createMissionTrain | Returns the local locomotive handle or 0. Preload the models for the selected variation. Pass false for both network flags. |
local pos = getEntityCoords(playerPedId(), true)
local found, south, north, lanesSouth, lanesNorth, median = getClosestRoad(pos, 0, 1, true)
if found then
print(lanesSouth, lanesNorth, median)
endconst 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.
| Family | What it covers | Instead |
|---|---|---|
| Rockstar accounts and commerce | MONEY, NETSHOPPING, SOCIALCLUB, APP, SAVEMIGRATION | Keep your economy and profiles on your server, with storage. |
| Rockstar online sessions and content | LOBBY, LANDINGPAGE, NETWORK_SESSION_*, NETWORK_TRANSITION_*, UGC, remote textures and Rockstar network authority changes | LS:MP runs the session: use events and remote calls. |
| Game script threads | START_NEW_SCRIPT, TERMINATE_THREAD, the BRAIN namespace | Your code runs as a resource. To quiet a story script, see suspendStoryScript. |
| Saves and game flow | Save data, STAT_SAVE, RESTART_GAME | Store data with storage. |
| Rockstar Editor | RECORDING, REPLAY | Not available to resources. |
| Raw memory and structures | DATAFILE, raw pointers and game structures without a typed adapter | For entity lists, lsmp.getGamePool. For JSON, your language's own JSON functions. |
| Shared menus and input | The game's frontend and pause menu, on-screen keyboard and input layout | Use the LS:MP page and input APIs for your resource UI. |
| Managed world state | Shared weather changes and unchecked clock increments | Use the documented LS:MP world APIs and checked clock setters. |
| Replaced by the language | Bit helpers and string conversions | Your language's own operators and functions. |
local ok, err = pcall(startNewScript, "cellphone_flashhand", 1424)
lsmp.log(tostring(ok) .. " " .. tostring(err)) --> false ... not available to scriptstry {
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,getInteriorRoomNameand 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 withlsmp.wait.
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.
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
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/_vpointer sentinels and noCitizen.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:
getGroundZFor3dCoordtakes a trailingp5, for instance.
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.
| Type | Lua | JavaScript | Meaning |
|---|---|---|---|
playerId | integer | number | A connected player, 0..65534. Valid for one session and reused after the player leaves. See Players. |
netId | integer | number | A networked entity, 1..65535, the same number on the server and on every client. Reused after the entity is deleted. |
handle | integer | number | Client only: the game's own handle of an entity, valid on this client only. Turn a netId into a handle with lsmp.getEntityFromNetId. |
dimension | integer | number | A 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. |
heading | number | number | Degrees, yaw only. |
hash | integer or string | number or string | A 32-bit game hash. A string is hashed with lsmp.hash. |
ms | integer | number | A duration in milliseconds. |
epochMs | integer | number | A point in time: milliseconds since the Unix epoch (lsmp.nowMs()). |
meters | number | number | A distance. |
color | see Colors | see Colors | A color, read in four forms. |
value | see Transportable values | see Transportable values | Any value that can travel between resources, engines and machines. |
event | string | string | An event or RPC name: 1 to 128 bytes of UTF-8, no NUL, case-sensitive. See Reserved names. |
name | string | string | A resource name (its folder name). |
ids | sequence of integers | Uint32Array | A list of netIds that can be large (getEntities, getEntitiesInRadius). |
fn | function | function | A 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.
| Situation | Lua | JavaScript |
|---|---|---|
| Programming error: wrong type, missing required argument, a function expected and not given | raises 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 name | raises 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 resource | action: false, "code"; read: nil, "code" | action: false; read: null; the code with lsmp.getLastError() |
| Run-time failure of an asynchronous call | cb(nil, "code", details?), or nil, "code", details? in a coroutine | the 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 saysbrowser:emit:in Lua andbrowser.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),
undefinedis 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 JavaScriptError) only exists where a function says so (MySQL, HTTP, files).
local ok, err = lsmp.setEntityOwner(netId, playerId)
if not ok then
lsmp.warn("cannot give the entity: " .. err) -- "not-found", "permission"...
endif (!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
nilin Lua andnullin JavaScript, everywhere: return values, fields of returned tables, event arguments (killerId,oldOwner...). A business value (0for 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
nullwhen the shape documents it. - "Unknown" and "empty" are told apart by an existence function:
lsmp.entityExists,lsmp.playerExists. - In JavaScript,
undefinedandnullpassed as an argument both mean "absent" (the documented default applies), except wherenilhas an explicit meaning, such as "nil deletes" for meta and storage.
Booleans
- Functions and events return real booleans.
- Arguments and option fields take
trueorfalse;nilor absent selects the documented default. A number, a string or a table in place of a boolean is a programming error:0is notfalse. - 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:
| Form | Example | Meaning |
|---|---|---|
number 0xRRGGBB | 0xFF0000 | Opaque. 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
Vector3in 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 aheading(degrees).
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 })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 withlsmp.hash(ASCII letters are lower-cased first). Anything else is an error.
Units
| Quantity | Unit | Naming |
|---|---|---|
| duration | milliseconds, integer | suffix Ms: timeoutMs, transitionMs, durationMs, lifetimeMs |
| point in time | milliseconds since the Unix epoch | suffix Ms: untilMs, atMs, mtimeMs, purchasedAtMs |
| distance | meters | explicit name, no suffix: radius, range, maxRadius |
| angle | degrees | heading, rotation, fov |
| screen position | normalized 0..1 | except 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.
| Lua | JavaScript | Travels as |
|---|---|---|
nil (argument), lsmp.null | undefined, null | nothing (absent) |
| boolean | boolean | boolean |
| integer | integer number within Β±(2^53-1), bigint within 64 bits | integer |
float (even 3.0) | any other number (NaN, Infinity included) | float |
| string (valid UTF-8) | string | string |
non-UTF-8 string, or lsmp.bytes(s) | Uint8Array, Buffer, ArrayBuffer, DataView | bytes |
Vector3 | object whose only own keys are numeric x, y, z | vector |
sequence with keys exactly 1..n; an empty table | Array (holes become null) | list |
| table whose keys are all strings | plain 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.
- 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)andlsmp.fs.readFile(path, opts, cb)both work). It is called later, never during the call, exactly once, withcb(result, nil)on success andcb(nil, "code", details)on failure (falseinstead ofnilwhen 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.onClientandlsmp.onCall,playerPreConnectionhandlers, and everylsmp.createThreadfunction. A suspended handler blocks neither the next event nor the other handlers. When the resource stops, its pending waits end withcancelled. lsmp.onTickhandlers, and functions called by Lua itself (atable.sortcomparator, a metamethod), cannot suspend.
-- 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)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:onandlsmp.http.servereturn an unsubscribe functionoff(), which returnstrueif it removed something. Each also has a symmetricoff*function (off,offServer,offClient,offCall,offTick,unregisterCommand,browser:off).- The same
(name, fn)pair registered twice is registered once; the second call returns the sameoff. - A handler that raises is isolated and logged as
[resource] lsmp: handler of '<name>' raised: ...; the other handlers still run. It stays registered (onlyonTickhandlers 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,
thisisundefinedin every handler.
local off = lsmp.on("playerJoin", function(playerId, name)
lsmp.log(name .. " joined")
end)
-- later
off()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 withobj:m()in Lua andobj.m()in JavaScript. Theiridfield, when they have one, is read-only. - A method of a destroyed handle does nothing and returns
falseornil;isValid()returnsfalse. 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.foreigncapability. When the resource stops, its entities and pickups are deleted (exceptlifePolicy = "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, butemit,emitServer,emitClient,emitAllClients,emitDimensionClients,onServer,onClient,onCallandbrowser:emitwith these names raiseError(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,quiton 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 aUint32Arrayin JavaScript (getEntities,getEntitiesInRadius). - Lists of pairs are lists of objects:
{ seat, ped },{ playerId, role }. - Seats:
0is the driver,1and 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:
| Subject | Lua | JavaScript |
|---|---|---|
| method call | obj:m() | obj.m() |
| asynchronous call | final callback or coroutine, result, err | Promise |
| reason of a synchronous failure | second return value "code" | lsmp.getLastError() |
| vector returned | Vector3 | {x, y, z} |
| bytes | string (send binary explicitly with lsmp.bytes(s)) | Uint8Array |
| explicit null in a list, JSON or SQL | lsmp.null | null |
| JSON | lsmp.json.encode/decode/array | JSON |
| thread | lsmp.createThread(fn, ...) | async function |
print = lsmp.log | console.* routed to lsmp.log/warn/error/debug | |
| timers | integer ids | client: integer ids; server: Node Timeout objects |
| integers beyond 2^53 | 64-bit Lua integers | BigInt |
| indices in error paths | from 1 (args[1] = first argument) | from 0 (args[0]) |
lsmp.null
SharedLualsmp.nullLua 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.
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".
lsmp.on("playerJoin", function(playerId, name)
lsmp.log(name .. " joined as player " .. playerId)
end)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
lsmpcall that caused it.lsmp.setPlayerDimensionreturns first, thenplayerDimensionChangearrives. - 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/nullfor absent values, unsigned hashes, vectors (Vector3in 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,
asyncfunction) without delaying the other handlers.
All engine events
| Event | Sides | Arguments | When |
|---|---|---|---|
resourceStart | server, client | name | After a resource's entry scripts (and module-level awaits) completed. |
resourceStop | server, client | name | Before a resource is torn down: its own handlers run first, then other resources'. |
serverStart | server | β | Once, after every resource of the boot set has started and the game port listens. |
serverStop | server | β | On graceful shutdown (console quit, admin panel restart/stop, update, SIGTERM/CTRL+C): after playerLeave(..., "shutdown") for every player, before resources stop. |
playerPreConnection | server | p | When an admitted client asks to join, before any slot is given. |
playerJoin | server, client | playerId, name | Server: the player has a slot and is in the session (after admission). |
playerLeave | server, client | playerId, name, reason, detail, client | The player left the session. |
playerSpawn | server, client | playerId, position, heading, model, first | Client: the local player spawned (lsmp.spawn, auto spawn, respawn). |
playerDeath | server, client | playerId, killerId, weaponHash, position, flags, killerEntity | Server: the victim's client reported its death (deduplicated, rate-limited, killer resolved by the server). |
playerDimensionChange | server, client | playerId, oldDimension, newDimension | A player changed dimension. |
entityDimensionChange | server | netId, oldDimension, newDimension | An entity changed dimension. |
entityOwnerChange | server | netId, oldOwner, newOwner, reason | Simulation of an entity moved. |
entityAdopt | client | netId | The local client starts simulating an entity. |
entityRelease | client | netId | The local client stops simulating an entity. |
entityStreamIn | client | netId, entity | A networked entity got a game instance here. |
entityStreamOut | client | netId | A networked entity lost its game instance here (its handle is already invalid). |
voiceStart | server, client | playerId | A player starts transmitting. |
voiceStop | server, client | playerId | A player stops transmitting. |
pickupCollect | server | playerId, netId, pickupHash, amount, serverCreated | The server granted a pickup to a player. |
playerPermsChange | server, client | playerId | Server: a player's effective permissions changed. |
weatherChange | server, client | type, previous, transitionMs | The target synchronized weather type changed (client: also when a local override starts/ends). |
benefitGrant | server | lsmpId, benefit | A connected account has a benefit to apply (once per session until consumed). |
benefitRevoke | server | lsmpId, benefit | A benefit was revoked and must be taken back. |
metaChange | server, client | scope, target, key, value, source, client | A script-visible meta value changed (server: any writer; client: replicated change received, own writes included). |
selectionChange | client | entity, geomKey, valid | The picked entity/geometry changed. |
syncSceneStart | client | sceneId, netId | An entity of the session starts a synchronized scene. |
syncSceneStop | client | sceneId, netId | It stops. |
serverMessage | client | text | The server console ran say. |
browser:load | client | url | The page (main frame) finished loading. |
browser:loadError | client | url, code | Navigation failed or the URL was refused. |
browser:focusLost | client | β | The player took focus back (escape hatch) or another page took it. |
browser:crash | client | reason | The page renderer crashed. |
Resources and server
resourceStart
SharedLua Β· JSlsmp.on("resourceStart", function(name) end)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.
| Parameter | Type | Description |
|---|---|---|
name | name | The resource that started. |
lsmp.on("resourceStart", function(name)
if name == lsmp.getResourceName() then
lsmp.log("ready")
end
end)lsmp.on("resourceStart", (name) => {
if (name === lsmp.getResourceName()) lsmp.log("ready");
});resourceStop
SharedLua Β· JSlsmp.on("resourceStop", function(name) end)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.
| Parameter | Type | Description |
|---|---|---|
name | name | The resource that stops. |
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)lsmp.on("resourceStop", async (name) => {
if (name !== lsmp.getResourceName()) return;
lsmp.storage.set("lastStop", lsmp.nowMs());
await lsmp.storage.flush();
});serverStart
ServerLua Β· JSlsmp.on("serverStart", function() end)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 Β· JSlsmp.on("serverStop", function() end)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 Β· JSlsmp.on("playerPreConnection", function(p) end)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.
| Parameter | Type | Description |
|---|---|---|
p | PreConnection | The connecting player (fields below). JavaScript: a frozen object. |
| Field | Type | Description |
|---|---|---|
lsmpId | integer? | LS:MP account; nil/null for a guest. |
name | string | The name the player connects with. |
verified | boolean | true when the server verified the account with LS:MP. |
guest | boolean | true for a player without an account. |
ip | string? | IP address. nil/null unless the resource holds the players.identity capability. |
hwid | string? | Hardware identifier. Same rule as ip. |
deny(reason) | function | Refuses the connection. In Lua, call it as p.deny(reason) (no colon). |
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)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 Β· JSlsmp.on("playerJoin", function(playerId, name) end)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).
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The new player. |
name | string | Their name. |
playerLeave
SharedLua Β· JSlsmp.on("playerLeave", function(playerId, name, reason, detail, client) end)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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player who left. |
name | string | Their name. |
reason | string | "quit", "kick", "ban", "timeout", "shutdown" or "error" (lsmp.LeaveReason). |
detail | string? | Server: the text given to the kick, the ban or the client's disconnect, if any. Always nil/null on the client. |
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)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 Β· JSlsmp.on("playerSpawn", function(playerId, position, heading, model, first) end)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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
position | Vector3 | Spawn position. |
heading | heading | Spawn heading, in degrees. |
model | hash | Ped model (unsigned). |
first | boolean | true for the first spawn of the session. |
playerDeath
SharedLua Β· JSlsmp.on("playerDeath", function(playerId, killerId, weaponHash, position, flags, killerEntity) end)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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The victim. |
killerId | playerId? | The killing player; nil/null when not killed by a player. |
weaponHash | hash | Weapon (unsigned); 0 if unknown. |
position | Vector3 | Where the victim died. |
flags | integer | Bits of lsmp.DeathFlag (Headshot = 1). |
killerEntity | netId? | The entity that killed (ped, vehicle); nil/null for the environment. |
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)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 Β· JSlsmp.on("playerDimensionChange", function(playerId, oldDimension, newDimension) end)lsmp.on("playerDimensionChange", (playerId, oldDimension, newDimension) => {})A player changed dimension.
Client: local player only. See Dimensions.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
oldDimension | dimension | Before. |
newDimension | dimension | After. |
playerPermsChange
SharedLua Β· JSlsmp.on("playerPermsChange", function(playerId) end)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.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
Entities
entityDimensionChange
ServerLua Β· JSlsmp.on("entityDimensionChange", function(netId, oldDimension, newDimension) end)lsmp.on("entityDimensionChange", (netId, oldDimension, newDimension) => {})An entity changed dimension.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
oldDimension | dimension | Before. |
newDimension | dimension | After. |
entityOwnerChange
ServerLua Β· JSlsmp.on("entityOwnerChange", function(netId, oldOwner, newOwner, reason) end)lsmp.on("entityOwnerChange", (netId, oldOwner, newOwner, reason) => {})The player simulating an entity changed.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
oldOwner | playerId? | Previous owner; nil/null if it was orphan. |
newOwner | playerId? | New owner; nil/null if it becomes orphan. |
reason | string | One of lsmp.OwnerChangeReason: "adopt", "migrate", "leaseExpired", "disconnect", "demand", "script", "release". |
entityAdopt
ClientLua Β· JSlsmp.on("entityAdopt", function(netId) end)lsmp.on("entityAdopt", (netId) => {})The local client starts simulating an entity.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
entityRelease
ClientLua Β· JSlsmp.on("entityRelease", function(netId) end)lsmp.on("entityRelease", (netId) => {})The local client stops simulating an entity.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
entityStreamIn
ClientLua Β· JSlsmp.on("entityStreamIn", function(netId, entity) end)lsmp.on("entityStreamIn", (netId, entity) => {})A networked entity got a game instance on this client.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
entity | handle | Its game handle, valid during the dispatch (it can disappear later). |
entityStreamOut
ClientLua Β· JSlsmp.on("entityStreamOut", function(netId) end)lsmp.on("entityStreamOut", (netId) => {})A networked entity lost its game instance on this client.
Its handle is already invalid when the event arrives.
| Parameter | Type | Description |
|---|---|---|
netId | netId | The entity. |
pickupCollect
ServerLua Β· JSlsmp.on("pickupCollect", function(playerId, netId, pickupHash, amount, serverCreated) end)lsmp.on("pickupCollect", (playerId, netId, pickupHash, amount, serverCreated) => {})The server granted a pickup to a player.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The collector. |
netId | netId | The pickup. |
pickupHash | hash | Pickup type (unsigned). |
amount | integer | Amount granted. |
serverCreated | boolean | true 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 Β· JSlsmp.on("syncSceneStart", function(sceneId, netId) end)lsmp.on("syncSceneStart", (sceneId, netId) => {})An entity of the session starts a synchronized scene.
See Synchronized scenes.
| Parameter | Type | Description |
|---|---|---|
sceneId | integer | The scene. |
netId | netId | The participating entity. |
syncSceneStop
ClientLua Β· JSlsmp.on("syncSceneStop", function(sceneId, netId) end)lsmp.on("syncSceneStop", (sceneId, netId) => {})An entity stops playing a synchronized scene.
| Parameter | Type | Description |
|---|---|---|
sceneId | integer | The scene. |
netId | netId | The participating entity. |
selectionChange
ClientLua Β· JSlsmp.on("selectionChange", function(entity, geomKey, valid) end)lsmp.on("selectionChange", (entity, geomKey, valid) => {})The picked entity or geometry changed.
See Outlines and picking.
| Parameter | Type | Description |
|---|---|---|
entity | handle? | The picked entity; nil/null if none. |
geomKey | integer? | The picked geometry, if any. |
valid | boolean | Whether the selection is valid. |
Meta
metaChange
SharedLua Β· JSlsmp.on("metaChange", function(scope, target, key, value, source) end)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.
| Parameter | Type | Description |
|---|---|---|
scope | string | "global", "player" or "entity". |
target | integer? | The playerId or netId; nil/null for a global value. |
key | string | The key. |
value | value? | The new value; nil/null when it was deleted. |
source | playerId? | 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 field | Type | Matches |
|---|---|---|
scope | string | "global", "player" or "entity". |
key | string | One key. |
target | integer | One playerId or netId. |
lsmp.on("metaChange", function(scope, target, key, value, source)
lsmp.log("player " .. target .. " has " .. tostring(value) .. " money")
end, { scope = "player", key = "money" })lsmp.on("metaChange", (scope, target, key, value, source) => {
lsmp.log(`player ${target} has ${value} money`);
}, { scope: "player", key: "money" });Voice, weather, benefits
voiceStart
SharedLua Β· JSlsmp.on("voiceStart", function(playerId) end)lsmp.on("voiceStart", (playerId) => {})A player starts transmitting voice.
See Voice.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The talking player. |
voiceStop
SharedLua Β· JSlsmp.on("voiceStop", function(playerId) end)lsmp.on("voiceStop", (playerId) => {})A player stops transmitting voice.
| Parameter | Type | Description |
|---|---|---|
playerId | playerId | The player. |
weatherChange
SharedLua Β· JSlsmp.on("weatherChange", function(type, previous, transitionMs) end)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.
| Parameter | Type | Description |
|---|---|---|
type | string | The new weather type. |
previous | string? | The previous type; nil/null if unchanged. |
transitionMs | ms | Duration of the transition. |
benefitGrant
ServerLua Β· JSlsmp.on("benefitGrant", function(lsmpId, benefit) end)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.
| Parameter | Type | Description |
|---|---|---|
lsmpId | integer | The account. |
benefit | Benefit | { id, key, quantity, purchasedAtMs, status }. |
benefitRevoke
ServerLua Β· JSlsmp.on("benefitRevoke", function(lsmpId, benefit) end)lsmp.on("benefitRevoke", (lsmpId, benefit) => {})A benefit was revoked and must be taken back.
Delivered only to resources holding benefits.read.
| Parameter | Type | Description |
|---|---|---|
lsmpId | integer | The account. |
benefit | Benefit | { id, key, quantity, purchasedAtMs, status }. |
serverMessage
ClientLua Β· JSlsmp.on("serverMessage", function(text) end)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.
| Parameter | Type | Description |
|---|---|---|
text | string | The 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 Β· JSbrowser:on("load", function(url) end)browser.on("load", (url) => {})The page (main frame) finished loading.
Events emitted to the page before this point are delivered right after it.
| Parameter | Type | Description |
|---|---|---|
url | string | The loaded address. |
browser:loadError
ClientLua Β· JSbrowser:on("loadError", function(url, code) end)browser.on("loadError", (url, code) => {})Navigation failed or the address was refused.
| Parameter | Type | Description |
|---|---|---|
url | string | The address. |
code | string | "refused-url", "network", "http-<status>" or "aborted". |
browser:focusLost
ClientLua Β· JSbrowser:on("focusLost", function() end)browser.on("focusLost", () => {})The player took the focus back, or another page took it (2D browsers).
browser:crash
ClientLua Β· JSbrowser:on("crash", function(reason) end)browser.on("crash", (reason) => {})The page renderer crashed.
The browser stays valid: setUrl loads it again.
| Parameter | Type | Description |
|---|---|---|
reason | string | What happened. |
Constants
lsmp.LeaveReason
SharedLua Β· JSlsmp.LeaveReasonlsmp.LeaveReasonThe 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 Β· JSlsmp.DeathFlaglsmp.DeathFlagBits of the flags argument of playerDeath.
lsmp.DeathFlag.Headshot = 1
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
| Call | Lua | JavaScript |
|---|---|---|
| synchronous action | local ok, code = lsmp.fn(...) | if (!lsmp.fn(...)) code = lsmp.getLastError() |
| synchronous read | local v, code = lsmp.fn(...) | if (lsmp.fn(...) === null) code = lsmp.getLastError() |
| asynchronous, callback | lsmp.fn(..., function(result, code, details) end) | β |
| asynchronous, coroutine | local result, code, details = lsmp.fn(...) | try { await lsmp.fn(...) } catch (e) { e.code } |
-- 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// 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
| Code | lsmp.ErrorCode | Meaning | Typical causes |
|---|---|---|---|
not-found | NotFound | The target does not exist. | Unknown player, entity, resource, scene, file or product; callClient to a player who is not connected. |
timeout | Timeout | No 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-handler | NoHandler | Nobody 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. |
error | Error | The 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. |
permission | Permission | Not 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. |
limit | Limit | A 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. |
disconnected | Disconnected | Not in a session, or the player left. | Client call while not connected; the player left before answering a callClient. |
invalid | Invalid | Refused 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. |
unavailable | Unavailable | The service is off or not ready. | LS:MP network services disabled on the server, renderer not ready, store disabled. |
cancelled | Cancelled | Stopped before the end. | The calling resource stops while it waits; the owner of the operation was destroyed; a MySQL pool closed. |
io | Io | Disk or network transport failure. | Unreadable file or store, connection lost, write failed. |
exists | Exists | It already exists. | fs.mkdir on an existing folder, fs.writeFile with exclusive. |
denied | Denied | The 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
Errorin 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 teste.code, not the message. lsmp.getLastError()returns the code of the last synchronous call of the resource that failed, ornil/nullwhen the last such call succeeded.
Constant
lsmp.ErrorCode
SharedLua Β· JSlsmp.ErrorCodelsmp.ErrorCodeEvery 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"
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
| What | Limit | Beyond |
|---|---|---|
| Event and RPC name | 1 to 128 bytes of UTF-8, no NUL; lsmp: prefix reserved | raises |
| Meta key | 1 to 128 bytes of UTF-8, no NUL; lsmp: prefix reserved | raises |
| Storage key | 1 to 256 bytes | raises |
| Command name | 1 to 64 characters among A-Z a-z 0-9 _ . : - (a leading / is ignored), case-insensitive | raises |
Lua module name (require) | 1 to 128 characters among A-Z a-z 0-9 _ - . | raises |
Synchronized scene dict and clip | 1 to 63 bytes | the scene is refused |
playerPreConnection deny reason | 256 bytes | cut to fit |
Events and remote calls
| What | Limit | Beyond |
|---|---|---|
Arguments of emit, emitServer, emitClient*, call, callServer, callClient, browser:emit/call, page lsmp.emit/call | 32 | raises |
| Nesting of lists and maps in a value | 32 levels | raises |
| One map key | 4096 bytes | raises |
emit and local call (same side), arguments and result | 16 MiB encoded | raises |
Server β client (emitClient, emitAllClients, emitDimensionClients, callClient request, answer to a callServer) | 16 MiB encoded | emitClient* 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 encoded | raises |
| Lists, maps and byte arrays in one client β server message | 65 536 in total | the message is dropped, a line is logged |
| Script β page message | 120 000 UTF-16 code units of JSON | raises |
Nested synchronous emit calls | 32 | raises lsmp.emit: recursion limit (32) reached |
Handlers per resource (on, once, onServer, onClient) | 4096 | raises |
| RPC handlers | one per name per side, for all resources and both engines | a second onCall raises |
Pending outgoing calls per resource (call, callServer, callClient) | 4096 | limit |
| Calls from one player being handled at the same time | 1024 | the client's call fails with limit |
Calls being answered at the same time by one resource on the client (callClient requests and local call) | 4096 | the call fails with limit; a server call not answered within 300 s is dropped |
Call names (onCall) per resource on the client | 256 | raises |
RPC timeoutMs | 1 to 300 000 ms, default 10 000 ms | raises; 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 client | MaxClientSendQueueBytes (server.cfg, default 64 MiB) | the client is disconnected |
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
| What | Limit | Beyond |
|---|---|---|
| One meta value | 8192 bytes encoded | raises |
| Meta keys per player or entity, written by clients | MetaMaxKeys (server.cfg, default 256) | the client write is refused |
| Meta bytes per player or entity, written by clients | MetaMaxBlobBytes (server.cfg, default 64 KiB) | the client write is refused |
| Client meta write rate | MetaWriteBytesPerSec (server.cfg, default 64 KiB/s, four-second burst) | limit |
| One stored value | 64 KiB encoded | raises |
| Storage of one resource | 16 MiB; each entry counts 64 bytes on top of its key and value (about 260 000 entries at most) | limit |
| Storage write to disk | within about 750 ms of the change | use lsmp.storage.flush() to wait for it |
lsmp.fs.readFile | 512 MiB per file | limit |
lsmp.readResourceFile | 64 MiB per file | limit |
lsmp.randomBytes | 1 to 65 536 bytes | raises |
Databases and HTTP
| What | Limit | Beyond |
|---|---|---|
| MySQL pools per resource | 8 (JavaScript) | limit |
MySQL connectionLimit | 1 to 64 | raises |
MySQL queryTimeoutMs | default 0 (none) | the query fails with timeout and its connection is closed |
HTTP route per resource (lsmp.http.serve) | one | a second route replaces or is refused, see HTTP routes |
HTTP route request body (maxBodyBytes) | default 1 MiB, at most 16 MiB | the request is answered 413 without calling the handler |
HTTP route answer time (timeoutMs) | default 10 000 ms, at most 300 000 ms | the client gets 504 |
| HTTP requests being handled, whole server | 1024 | the client gets 503 |
| HTTP requests being handled by one resource's route | 256 | the client gets 503 |
| HTTP requests being handled from one client address | 64 (loopback not counted) | the client gets 429 |
| Outgoing HTTP requests in flight, sandboxed server resource | 256 | limit |
lsmp.fs operations waiting, sandboxed server resource | 128 operations or 64 MiB of data | limit |
Limits of the HTTP client (lsmp.http.get...) are on the HTTP client page.
Entities and scenes
| What | Limit | Beyond |
|---|---|---|
Pickup lifetimeMs | 0 (never) to 86 400 000 ms (24 h); removed at most 1 s after expiry | raises |
| Pickup collectors | 64 players | raises |
| Synchronized scene participants | 1 to 8 | the scene is refused |
| Distance between the participants of a scene | 50 m | invalid |
| Synchronized scenes running at once | 1024 | limit |
Client resources
| What | Limit | Beyond |
|---|---|---|
| 2D browsers | 16 per resource, 128 on the client | nil/null with limit |
| 3D browsers | 4 per resource, 64 on the client | nil/null with limit |
Handlers on one browser (browser:on) | 1024 | raises |
| Messages from one page in one frame | 256 messages and 524 288 characters of JSON | an emit is dropped, a call fails with limit; logged once a minute |
lsmp.http on the client | 8 requests in flight and 20 per second per resource; 32 in flight and 128 MiB of response bodies for the whole client | limit |
Names given to lsmp.resources.invalidateArchives / restoreArchives | 1 to 4096 per call, each 1 to 512 bytes; 8192 archives invalidated at once on the client | raises (count, length); error beyond 8192 |
Time and memory
| What | Limit | Beyond |
|---|---|---|
| Lua and JavaScript on the server: one run (handler, timer, file body) without suspending | SandboxWatchdogSec (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 ms | the run is interrupted, the error is logged with the resource name |
| Script time of one resource per frame (client) | 100 ms in total | the 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 536 | raises too many timers in this resource (65536) |
Waiting coroutines per resource (Lua) / pending lsmp.wait per resource (JS) | 65 536 | raises |
| 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 handlers | ResourceStopGraceMs (server.cfg, default 2000 ms); 1000 ms on the client | the resource is torn down anyway |
serverStop handlers | ShutdownGraceMs (server.cfg, default 5000 ms) | resources are stopped anyway |
| Module-level awaits of a starting resource | ResourceStartTimeoutMs (server.cfg, default 30 000 ms) | the resource is marked failed |
playerPreConnection verdict | PreConnectionTimeoutMs (server.cfg, default 10 000 ms) | the player is refused |
setInterval period | at least 1 ms | a smaller period is raised to 1 ms |
onTick errors (client) | 8 in a row | the tick handler is disabled |
Tutorials
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
- The client checks that the name is a vehicle model (only the game knows) and computes a spot in front of the player.
- It asks the server with
lsmp.callServer. Network entities are created by the server: every player nearby sees the same car. - 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.
- 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{
"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 }.
-- 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)// 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.
-- 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)// 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
- Load the resource
Restart the server (
quitin its console, then start it again): resources are loaded when the server starts. - Give the permission
In the admin panel, Permissions tab, allow
car.spawnto a group you are in (or todefaultfor every player). A script can do it too:lsmp.perms.allow("group:default", "car.spawn"). - Try it
In game, open the F8 console and type
/car adder. Without the permission, the server answers "You may not spawn vehicles."
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.
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.
- Create the folder and the manifest
web/is served to your pages atrsc://atm/.Lua only:
resources/ ββ atm/ ββ manifest.json ββ server/ β ββ main.lua ββ client/ β ββ main.lua ββ web/ ββ index.html ββ style.css ββ app.jsJavaScript only:
resources/ ββ atm/ ββ manifest.json ββ server/ β ββ main.js ββ client/ β ββ main.js ββ web/ ββ index.html ββ style.css ββ app.jsLua 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" } - 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.lualocal 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.jsconst 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 }; }); - 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.csshtml, 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.jsconst $ = (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'); }); - The client script connects them
It opens the page hidden, shows it on the
/atmcommand, 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.lualocal 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+Backspacejsclient/main.jsconst 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 - Start it and try
Restart the server so it loads
atm, then join. In game, open the client console (F8) and typeatm. 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 - 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.
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: 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.js1. 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.
-- 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)// 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 };
});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.
-- 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)// 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
- Load the resource
Restart the server: resources are loaded when it starts.
- Shop
In game, F8 console:
/shop, then/buy pistol. - 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.
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.
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
- Spawn the peds
lifePolicy = "keep"keeps the guards alive when nobody is around. They are deleted with the resource when it stops.luaLualocal 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)jsJavaScriptconst 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()}`); } }); - Give them an intent
A
"guard"intent keeps each ped withinradiusofpositionand makes it attack what comes close.keepTaskstops ambient events from replacing the task;missionkeeps the game from cleaning the ped up.luaLuafor _, ped in ipairs(guards) do lsmp.setEntityIntent(ped, { type = "guard", position = POST, radius = 12.0, accuracy = 40, keepTask = true, mission = true, hatesPlayers = true, }) endjsJavaScriptfor (const ped of guards) { lsmp.setEntityIntent(ped, { type: "guard", position: POST, radius: 12, accuracy: 40, keepTask: true, mission: true, hatesPlayers: true, }); } - Change orders later
Set a new intent at any time; the current owner applies it, and so will the next ones.
luaLualsmp.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)jsJavaScriptlsmp.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.
- Server: mark the pedluaLua
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 }) endjsJavaScriptconst 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 }); } - Client: apply it when adopting
entityAdoptfires on the client that starts simulating the entity, each time ownership moves to it.luaLualsmp.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)jsJavaScriptlsmp.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 = playerIdand 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.foreigncapability to be given intents.
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 theresources/folder of your server, then restart the server: every folder ofresources/starts with it. - To turn one off without deleting it, use
resources.jsonor 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 thisare typed in the game's F8 console; the others in the server console. With thechatresource, a line that starts with/in the chat runs a server command with the player's permissions.
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
| Resource | What it does | Shows |
|---|---|---|
spawn-mgr | Places 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. |
chat | Text 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-mgr | Respawn 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-mgr | Proximity 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-tools | Moderation commands for the server console and, with permissions, the chat: online, ids, kickplayer, ban, unban, whitelist, announce. | Admission and moderation, commands with permissions. |
scoreboard | Kills and deaths of every player; hold Z to see them. | Global meta as shared state, metaChange on the client. |
player-blips | A map blip on every player streamed near you. /blips toggles them. | getEntitiesInRadius, the entityStreamOut event, blip natives. |
Samples
| Resource | Try it | Shows |
|---|---|---|
hello-world | Join, 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-sample | Edit 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-respawn | Run 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-sample | Look at your Discord profile while playing. /presence off. | The Discord presence functions (Discord presence). |
event-logger | evlog 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-sample | Look 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-benefit | First 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-sample | tip 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-sample | Stand 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-sample | Go 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-sample | weather, 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.
| Resource | Try it | Lua 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.
| Resource | Try it | What 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. |
