scrap mechanic api: Lua Setup Guide and Best Practices - Guides

scrap mechanic api: Lua Setup Guide and Best Practices

Learn how the Scrap Mechanic API fits into Lua scripting, client-server logic, UI building, storage, and reliable mod development.

2026-07-27
scrap mechanic Wiki Team
Quick Guide
  • scrap mechanic api: Use the published Lua API reference as the source for exposed functions and availability.
  • Lua environment: Scrap Mechanic scripting uses LuaJIT with Lua 5.1 language behavior.
  • Core structure: Separate client visuals, server authority, networking, and persistent storage.
  • UI workflow: Build interfaces through the available GUI tools and update them from client-side logic.
  • Debugging focus: Test shape merging, raycasts, body collisions, and multiplayer synchronization independently.

scrap mechanic api: What It Covers

The scrap mechanic api is the published interface for scripting inside Scrap Mechanic. It exposes the functions, objects, signatures, and availability labels that mods can use. The reference is presented through the Scrap Mechanic Lua API documentation, an unofficial searchable interface based on the published material at scrapmechanic.com/api.

The documentation site does not claim to replace the original API files. Its value is organization: searchable entries make it easier to locate a function before testing it in a mod. This matters because the published API can contain incomplete entries or omissions, so practical testing remains part of the development process.

The scripting environment uses LuaJIT, with the language covered by the Lua 5.1 reference manual. The API reference focuses on Scrap Mechanic’s exposed functions rather than documenting every general Lua feature.

Video Highlights:

  • Building a custom paint gun through Lua scripting
  • Creating a GUI for spread, speed, size, and color settings
  • Working with raycasts, shapes, bodies, and creation data
  • Managing client-server settings and saved values
  • Testing shape merging and collision behavior in large creations
API areaTypical purposeDevelopment question
Lua languageVariables, tables, functions, loopsIs the logic valid Lua 5.1 syntax?
Game objectsShapes, bodies, tools, creationsWhich object owns the function?
Client logicUI, effects, local updatesDoes this need to run for each player?
Server logicAuthority and shared stateShould the server validate the result?
NetworkingRequests and synchronizationWhich values must reach other clients?
StoragePersistent mod settingsShould the value remain after reloading?
Reference Habit

Search the API entry first, then confirm its signature, availability, and owning object before writing the surrounding logic. This prevents many avoidable scripting errors.

The Main API Systems to Learn First

A useful way to approach the API is to group functions by responsibility instead of memorizing isolated names. A tool such as a paint gun may combine raycasts, shape data, colors, particles, GUI controls, network requests, and storage. Each system should still have a clear role.

Lua and exposed game functions

Lua handles the program structure, while Scrap Mechanic provides the game-facing functions. Tables are especially important because shape data, settings, point lists, and network payloads may be represented as grouped values.

Shapes, bodies, and creations

Shape-based operations require careful attention to ownership. A single visible object may be part of a larger body or creation, and modifying one piece can affect connected geometry. Large creations also make inefficient loops more noticeable.

Raycasts and effects

Interactive tools often use a raycast or similar hit result to find where an effect should occur. The result may then be used to identify a shape, calculate a position, or spawn a visual effect. Always test the difference between the impact point, the hit shape, and the object that owns it.

GUI and player interaction

A custom interface generally belongs on the client. The client can display controls and collect input, while the server can validate settings that affect shared gameplay or world state.

Lua Tables

Store grouped values such as settings, point data, shape records, and temporary lookup tables.

Shape Data

Track positions, colors, bounds, and identifiers carefully when a tool edits construction pieces.

GUI Builder

Use client-side interface logic to expose readable controls instead of hard-coding every value.

Networking

Send only the values that need synchronization, then validate shared changes on the server.

SystemBest handled byExample responsibility
GUI displayClientShow controls and update labels
Input readingClientDetect interaction with a tool
World mutationServerApprove shared shape or creation changes
Visual particlesClient or effect contextDisplay impact feedback
Saved configurationServer or owning storage contextPreserve selected settings
Debug outputDevelopment buildPrint values during isolated tests
Ownership Matters

Do not assume that code running on a client can safely control shared world state. Separate presentation from authoritative changes, especially in multiplayer mods.

Client-Server and GUI Setup Workflow

A reliable mod normally establishes its execution model before adding advanced behavior. The following workflow is suitable for an interactive tool with configurable settings.

1

Confirm the API Entry

Identify the object, callback, function signature, and availability label for every API call you plan to use. If an entry is incomplete, create a small test instead of embedding it immediately into a large feature.

2

Create the Basic Object

Set up the tool or block with the minimum lifecycle functions needed for creation, interaction, and cleanup. Keep the first version free of GUI and persistent settings.

3

Add the Client Interface

Build the GUI on the client and expose only practical controls. Values such as spread, speed, size, or mode should be displayed in a form that makes their current state obvious.

4

Send Settings Through the Server

When a player changes a shared setting, send a focused request to the server. The server should store the accepted value and distribute the resulting state when other clients need it.

5

Test World Effects Separately

Test raycasts, shape edits, particles, and large creations as separate cases. This makes it easier to identify whether a failure comes from networking, geometry, or the game’s own merging behavior.

A practical configuration table might contain values such as spread, speed, size, and a mode flag. Keep those values in one settings table rather than scattering constants throughout the script. This makes GUI updates, validation, and storage easier to manage.

SettingFunction in a toolSuggested validation
SpreadControls directional variationClamp to an intended angle range
SpeedControls effect movementRequire a non-negative numeric value
SizeControls affected areaRequire a valid minimum size
ModeSelects behavior such as bucket or single targetAccept only known mode names
ColorDefines the applied or displayed colorValidate the expected color format
Stable Pattern

Let the GUI edit a local settings object, send a clean request, validate it on the server, and then return the accepted state to clients.

Shape Editing, Merging, and Performance

Shape editing is one of the most demanding areas for API experimentation. A script may find the correct target yet still produce unexpected results when the game splits, recreates, or merges construction shapes. Repainting an existing area can therefore behave differently from placing a new block.

When a tool works across neighboring shapes, compare more than position. A robust check may need to consider:

  • Whether a matching point or key exists
  • The direction of the next bound
  • The color associated with the shape data
  • Whether the object belongs to the expected body
  • Whether the object is a part, shape, or larger creation
  • Whether the operation is running on the correct side of the client-server boundary

Large creations are useful stress tests, but they can also hide the source of a bug. Begin with a small wall or compact vehicle. Then test a larger structure after the basic operation behaves consistently.

Test caseWhat to observeWhy it matters
One uncolored shapeHit detection and first editConfirms the basic path
Two adjacent colorsRepainting and color comparisonReveals merge-related behavior
Connected vehicleBody and creation ownershipTests object relationships
Large wallLoop cost and visual lagExposes performance pressure
Multiple toolsDuplicate edits and synchronizationTests race-like interactions

A common optimization is to avoid repeatedly scanning data that can be indexed. Temporary lookup tables can record processed points or shape identifiers, reducing duplicate work during a single operation. Clear the table at the correct lifecycle point so old entries do not affect later interactions.

Raycasts also deserve focused testing. A particle or effect may appear to pass through a surface when the real issue is its spawn position, velocity, collision timing, or a target that was placed too close. Moving the effect slightly away from the hit surface can help distinguish collision behavior from visual overlap.

Performance Check

Measure large-creation behavior only after the small test works. If a loop touches every shape repeatedly, reduce duplicate scans before adding more GUI features or effects.

OptimizationUse caseTrade-off
Lookup tableRepeated point or identifier checksRequires cleanup
Narrow raycast scopeSmall, precise toolsLess forgiving targeting
Smaller test creationEarly debuggingDoes not represent worst-case load
Server-side validationShared world actionsAdds request handling
Limited GUI updatesSliders and repeated inputRequires deliberate refresh timing

API Debugging Checklist and Documentation Practice

API development is easier when each error is reduced to a small reproducible test. Avoid changing raycasts, networking, storage, and GUI code in the same pass. First confirm that the object exists, then confirm the returned value, and only afterward connect it to the next system.

Use this checklist before treating a mod feature as ready:

API Testing Checklist:

  • Confirm every function name, signature, and availability label in the published API reference
  • Test client and server callbacks independently
  • Validate shape, body, creation, and color data before modifying objects
  • Clamp GUI values and reject unknown modes
  • Test saved settings after reload and multiplayer synchronization

Keep an API notes table

A small project reference can save time when the official published entries are brief. Record the function name, owning object, callback context, return value, and a minimal test result. Do not treat an assumption as a confirmed API feature.

Note fieldExample content
FunctionExact published function name
OwnerShape, body, creation, GUI, or tool object
ContextClient, server, callback, or shared
ReturnsValue type or documented result
TestedSmall reproduction result
RiskMissing entry, merge behavior, or multiplayer concern

Link the correct reference

For current API browsing, use the searchable Scrap Mechanic Lua API reference. The site identifies its source as the published Scrap Mechanic reference and lists a 2026-07-24 UTC build date. For a questionable entry, compare it with the original publisher’s API material rather than relying only on a community interpretation.

Debugging Method

Print one meaningful value at a time: the hit result, identifier, color, bounds, or network payload. Small logs are easier to interpret than a large stream of mixed state.

FAQ for Scrap Mechanic Lua Modding

Q: What is the Scrap Mechanic API?

It is the published scripting interface for functions and objects exposed to Lua in Scrap Mechanic. The searchable SM Docs site organizes that reference without claiming to replace the original API files.

Q: Which Lua version does Scrap Mechanic use?

Scrap Mechanic uses LuaJIT, and the API documentation states that LuaJIT is covered by the Lua 5.1 reference manual. Use Lua 5.1-compatible language behavior when designing scripts.

Q: Should GUI code run on the client or server?

GUI presentation and local interaction generally belong on the client. Settings that affect shared world state should be sent through an appropriate request path and validated by the server.

Q: Why can shape repainting behave unexpectedly?

Shape edits can interact with splitting and merging behavior. A script may recreate or merge pieces before a later color operation completes, so test positions, colors, bounds, ownership, and operation order separately.

A good API mod is not defined only by how impressive the final tool looks. It should also have predictable ownership, readable settings, controlled network traffic, and tests that explain its failure cases. Start with the published reference, build one system at a time, and use small creations before moving to large multiplayer scenarios.

Final Recommendation

Treat the API reference as your contract, but treat in-game testing as essential validation for geometry, callbacks, GUI behavior, and multiplayer state.