GearBlocks

GearBlocks

Not enough ratings
Lua Scripting Guide
By danger726
A reference guide to Lua scripting in GearBlocks for making script mods and scenarios.
   
Award
Favorite
Favorited
Unfavorite
Introduction
This guide covers some general principles that apply to all GearBlocks Lua scripts, whether they be for scenarios or script mods.

For information specifically on making script mods, refer to:
https://steamhost.cn/steamcommunity_com/sharedfiles/filedetails/?id=3082621095
For information specifically on making scenarios, refer to:
https://steamhost.cn/steamcommunity_com/sharedfiles/filedetails/?id=3083650307
The Update Function
If a Lua script defines an Update() function, the game will call it every frame.

This should be used for any regular updates a script needs to do, such as polling input:
function Update() -- See if the j key was pressed. if Input.GetKeyDown( 'j' ) then print( 'Key triggered' ) end end
The FixedUpdate Function
If a Lua script defines a FixedUpdate() function, the game will call it once per simulation time step.

This should be used when applying physics forces, for example:
function FixedUpdate() -- Apply a force to every part in the scene. for part in Parts do part.ApplyForce( Vector3.Up * 10, part.Position ) end end
The Cleanup Function
If a Lua script defines a Cleanup() function, the game will call it when the script is unloaded.

This should be used for tidying up, such as reverting changes to global variables, removing global event handlers, destroying UI windows, and so on.

As an example:
-- Create a UI window. local win = Windows.CreateWindow() function Cleanup() -- Destroy the UI window. Windows.DestroyWindow( win ) end
The Save and Load Functions
For a scenario to support saving and loading of progress, its Lua script must define Save() and Load() functions. The game will call these functions when saving or loading a scene.

NOTE: Typically it only makes sense to define these functions in a scenario script, not a script mod.

The Save() function should return a string containing the serialized data that the scenario script wants to save. The built-in Json module can be used to serialize a table of data as a string:
local someValue = 42 function Save() local saveTable = {} saveTable['someValue'] = someValue return json.serialize( saveTable ) end

The Load() function takes a string containing the previously serialized data. The built-in Json module can be used to deserialize the string and get back the table of data:
function Load( jsonString ) local saveTable = json.parse( jsonString ) someValue = saveTable['someValue'] end

NOTE: Refer to the included "Kit Build" scenario for an example of implementing save / load functions. It can be found here: C:\Program Files (x86)\Steam\steamapps\common\GearBlocks\GearBlocks_Data\StreamingAssets\Scenes\Kit Build (or equivalent if you installed GearBlocks to a different location).
Global Events
The game has many global events that are exposed for use in Lua scripts.

A handler can be added to an event in order to respond to it:
local function onGameReady() -- The scene has finished loading, so init our scenario here... end -- Add our handler to the "GameReady" global event. GameReady.Handler.add( onGameReady ) function Cleanup() -- Make sure to remove our "GameReady" event handler. GameReady.Handler.remove( onGameReady ) end

NOTE: Event handlers should be removed when no longer needed, hence the use of the Cleanup() function in this example.

Events can also be raised from Lua scripts:
-- Raise the "MessagePopupShow" global event. MessagePopupShow.Raise( 'Message from lua script' )

NOTE: Caution is advised when raising events as some can put the game in a non-functioning state!

For a full list of the available events, open up the debug console (press the "backquote" key, or your keyboard's equivalent). Then type "listevt" and hit enter, this will list all the events:


You can type "help" followed by an event name to get more info on it.
Global Variables
The game has many global variables that are exposed for use in Lua scripts.

A variable can be read from:
function Update() -- Get the player from the "LocalPlayer" global variable. local player = LocalPlayer.Value -- Print out the player's speed. if player then local playerSpeed = player.Velocity.Magnitude print( string.format( 'Player speed: %0.2f m/s', playerSpeed ) ) end end

Or assigned to:
-- Set the "NoBuilderTool" global variable to true to disable the builder tool. NoBuilderTool.Value = true

NOTE: Caution is advised when assigning to variables as some can put the game in a non-functioning state!

For a full list of the available variables, open up the debug console (press the "backquote" key, or your keyboard's equivalent). Then type "listvar" and hit enter, this will list all the variables:


You can type "help" followed by a variable name to get more info on it.
Global Objects
The game exposes many global objects to Lua scripting, these provide all sorts of functionality. Such as: spawning in parts or constructions, manipulating constructions, creating custom UIs, creating vectors, quaternions, and much more.

We've seen examples of this already in this guide: polling input using Input, and creating a UI window using Windows.

Here are some more examples:

function Update() -- Use "InputActions" to see if the key bound to the "select" action was pressed. if InputActions.IsTriggered( actionID_Select ) then print( 'Action triggered' ) end end

-- Use "Vector3" to create a new vector and normalize it. local vec = Vector3.__new( 1, 2, 3 ) vec = Vector3.Normalize( vec )

-- Use "PopConstructions" to spawn in a part. PopConstructions.SpawnPart( 'Propeller 3Blade' )

A comprehensive reference of all available objects is beyond the scope of this guide, and more features and functionality will be added to the API over time anyway. For full documentation, refer to the GearBlocks Lua Script API[www.gearblocksgame.com].
Scene IDs
Players, constructions, and parts have a unique scene ID that can be used to identify them.

Each of these have an ID property that can be read, and can be retrieved from the scene using the Players, Constructions, and Parts global objects respectively.

For example:
-- Get a specific part. local partID = 0 local part = Parts.GetInstance( partID ) print( part.DisplayName ) -- Loop through all the parts. for part in Parts.Instances do print( string.format( 'Part scene ID: %d, name: %s', part.ID, part.DisplayName ) ) end
More Information
A tutorial on the Lua language itself is beyond the scope of the guide, there are many resources online for this.

It is worth mentioning though that GearBlocks uses MoonSharp for its Lua integration, which has some slight differences and additions compared to "standard" Lua. More information can be found at Differences vs Lua[www.moonsharp.org] and Additions vs Lua[www.moonsharp.org].

To learn more about Lua scripting for GearBlocks, the included script mods and scenarios are a good reference, you'll find them here (or equivalent paths for your installation):
  • Script mods: C:\Program Files (x86)\Steam\steamapps\common\GearBlocks\GearBlocks_Data\StreamingAssets\ScriptMods
  • Scenarios: C:\Program Files (x86)\Steam\steamapps\common\GearBlocks\GearBlocks_Data\StreamingAssets\Scenes
Finally, here is the full documentation for the GearBlocks Lua scripting API[www.gearblocksgame.com]. This will evolve over time as I expose more features and functionality in the API, so bookmark it for future reference!
3 Comments
Aljon 18 Jul, 2024 @ 7:12am 
Are we getting a way to add linear and rotational forces to construction/parts?
danger726  [author] 6 Jul, 2024 @ 5:54pm 
Good idea, will do, should be quick to add.
SniperGnome 6 Jul, 2024 @ 5:23pm 
on the Boundary can you add away to get the Boundarys
MapSize = Boundary.GetDims

MapSize = ( -100, -100, 200, 200 )
so we can see the size of the map and just make the Boundary bigger with out falling off the map.