Guide: Logic Basics

**Logic** is a mechanic introduced in Version 6.0 of Mindustry, which allows you to override the default behaviour of blocks and units through a customised programming language. Logic is run through Processors in conjunction with accessory blocks such as the Memory Cell, Switch and Logic Display. It is recommended to have some form of prior programming experience in order to be familiar with data types.

The way writing Logic code works is that when editing a Processor, players can enter in commands through adding blocks which do different things. The processor then loops through the commands given one by one starting from the top and returning there after the final command, once the player exits the editing interface.

## Types of Data

* **Integer:** Referred to shorthand as ints, this type of data is a whole number.
* **Float:** Floats are data types which contains decimals.
* **String:** Strings are data types which contain letters, numbers and symbols. They are denoted with quotation marks around them like "router".
* **Bool:** A True/False value.
* **null:** A value returned when a command fails to return due to no item matching parameters, such as when the *Unit Radar* command fails to pick up. Cannot undergo any direct operations.
* **@unit:** A value returned with the *Unit Bind* function. *Unit Control, Unit Radar and Unit Locate* functions use this data type to determine which unit to execute on.
* **block:** A type of data containing the information of a set block.
* **@ipt:** Returns the instructions per tick of the processor.
* **@time:** Unix timestamp since January 1st 1970.

## Blocks

### **Processors**

Main article: Micro Processor, Logic Processor, Hyper Processor

Logic Processors are the brains of logic, the blocks that run the commands. There are three varieties:

* The Micro Processor is cheap and can be used for small-scale operations such as controlling low numbers of units or managing blocks (i.e Turning a Thorium Reactor off when without Cryofluid) due to its low speed of 120 commands/sec.
* The Logic Processor is more expensive. It is often used to make advanced calculations or to run commands with large numbers of units. It runs at 480 commands/sec.
* The Hyper Processor is the most expensive and runs 1500 commands/sec. It is best used when dealing with constantly updating graphics.

When designing a new system in Sandbox mode, it can be tempting to reach for the largest and fastest processor you can find. However, since Mindustry processors run in parallel, there are many tasks that can be done faster, with fewer resource costs and less coding complexity, by splitting tasks among many small processors (with memory cells to share state between them if needed), instead of one big processor that does everything. For example, you could do all your business logic in a Micro Processor and use a Logic or Hyper processor to draw the results to a graphical display (sort of like a how a real-world PC has both a CPU and a GPU). This comes with the added benefit that the "CPU" can still operate if the "GPU" and graphical interface are destroyed and can't be rebuilt right away.

### **Messages and Displays**

*Main articles: Message, Logic Display, Logic Display*

Messages and Logic Displays can show the stored text and visual data within a processor.

In text form, the command *Print* adds text to a hidden variable in each processor. The command *Print Flush* displays the text to a Message block and clears the hidden variable.

Logic Displays work in much the same way, with the *Draw* and *Draw Flush* command.

### Memory Cells

*Main articles: Memory Cell, Memory Bank*

### Switches

Main article: Switch

The Switch has two states, with the on state (indicated by the dot in the middle being purple) registering as *true* when sensing whether it is *enabled* with a Logic Processor. If it is off (indicated by the dot in the midddle being grey), it will register as *false*. Switches can be turned on or off by clicking on them, and can also be forced on or off with a logic processor using the Control command.

## List of Commands

### Flow Control

These commands control the flow of the program.

#### Wait

Pause execution for a specified number of seconds.

#### End

Signifies the end of the current execution run. Processor will return to the first operation and run again. Equivalent to "jump 0 always"

#### Jump

Jump to a different instruction if the specified condition is met. The in-game editor allows you to choose a line number, but using an external editor allows you to set labels and jump to those labels.

```
set result 0
jump 3 equal result 0
set result "text"
print result

```
Example (Skips instruction #2, prints "0")

```
set result 0
jump label equal result 0
set result "text"
label:
print result

```
Example (Same example, but with labels. The game converts labels to line numbers, so be sure to save your file and only make edits outside of the game)

### Operations

#### Set

Set a variable to a specific value. This can be a literal value, or another variable.

```
set myVariable "some text"

```
Example (set "myVariable" to the text "some text")

```
set myVariable nucleus1

```
Example (set "myVariable" to the linked building "nucleus1")

#### Operation

Set a variable to a calculated value. This allows basic mathematical operations, as well as a few other mathematical functions. According to the Official Wiki, specific operations can be googled such as: "<operation name> Java math".

```
op add myVariable myVariable 1

```
Example (increase value of myVariable by 1)

```
op max myVariable count1 count2

```
Example (set "myVariable" to larger of the variables count1 and count2)

#### Lookup

Get a reference to a particular type of block, unit, item, or liquid based on it's index (an integer) in the lookup tables. This can be used in sensor and control commands

```
lookup item myItem 3
sensor myVariable nucleus1 myItem

```
Example (Store the type of item with index 3 into "myItem" - metaglass, then check the quantity of metaglass in the Core)

```
lookup unit myUnit 21
bind myUnit

```
Example (Store the type of unit with index 21 into "myUnit" - mono, then bind one)

#### Pack Color

Pack RGBA components into a single number for drawing or rule-settings. All values should be decimals between 0 and 1.

```
packcolor red 1 0 0 1
control color illuminator1 red 0 0 0

```
Example (Set an illuminator to emit red light)

### Block Control

#### Sensor

Gets a value or property of a building, and stores that information in a variable.

Properties that can be sensed include quantities of specific resources or liquids, as well as a long list of special properties.

```
sensor myVariable nucleus1 @copper

```
Example (how much copper in the core)

```
sensor myVariable wall1 @health

```
Example (health of a wall block)

#### Control

Set a property of a building to a particular value.

Set-able properties include:

* "enabled" - Whether the block is enabled
* "shoot" - Shoot at a position
* "shootp" - Shoot at a unit/building with velocity prediction
* "config" - Building configuration; possible values and behavior depend on the target block
* "color" - Illuminator color

```
control enabled conveyor1 false

```
Example (Disable one block of a conveyor, resources will not pass through that block)

```
control config unloader1 @copper

```
Example (Set an unloader to unload copper)

#### Radar

Detect a unit within a Turret's range.

You can specify up to 3 types that a unit must match to be detected. A unit must match ALL the selected types. Available target types:

* "any" - *Any unit*
* "enemy" - *Enemy unit*
* "ally" - *Ally unit*
* "player" - *Unit controlled by a player*
* "attacker" - *Unit with a weapon*
* "flying" - *Flying unit*
* "boss" - *Guardian unit*
* "ground" - *Ground unit*

If multiple units meet the criteria, you can control which one is chosen based on "sort" and "order".

Sort can be:

* "distance"
* "health"
* "shield"
* "armor"
* "maxHealth"

Order can be 1 or 0, used to specify whether you want the highest/closest (1) or lowest/farthest (0) of the selected Sort.

Data for the detected unit is stored in the return variable, which can be used in other commands.

```
radar flying enemy any health turret1 1 myVariable

```
Example (Find the enemy flying unit within the range of turret1 that has the highest health, and store it in "myVariable")

```
radar enemy any any armor turret1 1 myVariable
control shootp turret1 myVariable 1

```
Example (Find the enemy unit within the range of turret1 that has the highest armor, and shoot it)

#### Print Flush

Sends text that has been printed to a particular display block.

```
print "Test!"
printflush message1

```
Example (Display "Test!" on the first linked Message building)

#### Draw Flush

Sends drawing data to a particular display block.

```
draw poly 40 40 4 5 0 0
drawflush display1

```
Example (Draws a dot on the first linked display)

#### Get Link

Get a linked building/block by its index, regardless of type. The first linked block is 0, the second is 1, and so on.

```
getlink myVariable 0

```
Example (Stores data for the first linked block in "myVariable")

### Unit Control

#### Unit Bind

Bind a particular unit to this processor. The bound unit is automatically the target of unit control and unit radar commands. The bound unit can be referenced by "@unit" for use in other commands.

**Only one unit may be bound at a time.** Calling "unit bind" a second time will unbind the original unit in order to bind the new one.

```
ubind @mono

```
Example (Bind a Mono unit)

```
radar ally any any health turret1 0 myUnit
ubind myUnit

```
Example (Find the ally within the range of turret1 that has the lowest health, and bind it)

#### Unit Control

Issue commands to the bound unit. Each command has a set of additional parameters. Not all commands are valid for all units.

Available commands are:

* "idle" - Don't move, continue building/mining. The default state
* "stop" - Stop/cancel all actions (moving, mining, building, etc)
* "move" - Move to exact position
* "approach" - Approach a position with a radius
* "boost" - Start/stop boosting (for certain mechs)
* "target" - Shoot a position
* "targetp" - Shoot a target with velocity prediction
* "itemDrop" - Drop an item
* "itemTake" - Take an item from a building
* "payDrop" - Drop current payload
* "payTake" - Pick up payload at current position
* "payEnter" - Enter/land on the payload block the unit is on
* "mine" - Mine (extract resources) at a position
* "flag" - Numeric unit flag. Readable with Sensor, visible in unit hover info
* "build" - Build a structure
* "getBlock" - Fetch a building/floor and type at coordinates. Unit must be in range of position. Solid non-buildings will have the type @solid
* "within" - Check if unit is near a position
* "unbind" - Completely disable logic control. Resume standard AI

```
ucontrol itemTake @coal nucleus1 10

```
Example (Pick up 10 coal from the Core)

#### Unit Radar

Detect another unit within the bound unit's range.

You can specify up to 3 types that a unit must match to be detected. A unit must match ALL the selected types. Available target types:

* "any" - Any unit
* "enemy" - Enemy unit
* "ally" - Ally unit
* "player" - Unit controlled by a player
* "attacker" - Unit with a weapon
* "flying" - Flying unit
* "boss" - Guardian unit
* "ground" - Ground unit

If multiple units meet the criteria, you can control which one is chosen based on "sort" and "order".

Sort can be:

* "distance"
* "health"
* "shield"
* "armor"
* "maxHealth"

Order can be 1 or 0, used to specify whether you want the highest/closest (1) or lowest/farthest (0) of the selected Sort.

Data for the detected unit is stored in the return variable, which can be used in other commands.

```
uradar flying enemy any health 1 myVariable

```
Example (Find the enemy flying unit within the range of turret1 that has the highest health, and store it in "myVariable")

```
uradar enemy any any armor 1 myVariable
ucontrol targetp myVariable 1

```
Example (Find the enemy unit within the range of turret1 that has the highest armor, and shoot it)

#### Unit Locate

Uses units to find a block type anywhere on the map.

Block types that can be located:

* "ore" - Locate a tile that yields a specific type of resource when mined.
* "building" - Locate a building of a particular category. Also specify whether located building should be enemy or not. Categories:
	+ "core" - Any core
	+ "storage" - Storage building, e.g. Vault
	+ "generator" - Buildings that generate power
	+ "turret" - Any turret
	+ "factory" - Buildings that transform resources
	+ "repair" - Repair points
	+ "battery" - Any battery
	+ "reactor" - Impact/Thorium reactor
* "spawn" - Locate an enemy spawn point. May be a core or position
* "damaged" - Locate a damaged ally building

```
ulocate ore core true @copper copperX copperY copperFound nothing

```
Example (Find a tile for mining copper. The coordinates of the tile are stored in "copperX" and "copperY", and "copperFound" will be false if no tile was found)

```
set isEnemy true
ulocate building turret isEnemy turretX turretY turretFound turrentRef

```
Example (Find an enemy turret. Store coordinates in "turretX" and "turretY", boolead success in "turretFound", and the building's data in "turretRef")

### Input & Output

#### Read

The *Read* command updates a variable which is the value in a position stored in a Memory Cell.

#### Write

The *Write* command updates a value in a position in a Memory Cell. These can only read and write ints or floats.

#### Draw

The *Draw* command creates shape/color data to be sent to a Logic Display

* Clear -- Clears the draw queue and fills it with a rgb color.
* Stroke -- Sets a line width.
* Rect -- Fills in a rectangle. X and Y coordinates define it's top left position
* Poly -- Fills in a regular polygon. Sides define what shape it is. For example, with 6 lines, it creates a hexagon, AKA the best shape ever.
* Triangle -- Fills in a triangle. The coordinates define where the points are. Can be used to make more unique triangles.
* Color -- Sets color for objects, for example polies and triangles.
* Col -- Equivalent to Color, but packed
* Line -- Creates a line. Width can be set using Stroke.
* LineRect -- Creates a rectangle outline. Same properties as the rectangle.
* LinePoly -- Creates a polygon outline. Same properties as the polygon.
* Image -- Creates an image. Defined with @ (e.g. @router or @dagger). Mods can work too, but you need their name and THEN the designator. Invalid images load up an oh no.

#### Print

The *Print* command specifies text to be sent to a Message block.

## See Also

Logic Examples

1. ↑ https://mindustrygame.github.io/wiki/logic/1-glossary/#op