# Useful script snippets

## Looping over instances&#x20;

```javascript
for (const inst of runtime.objects.Sprite.instances()) {
     console.log(inst.instVars.myVariable) //example of logging an instance variable
}
```

you can replace instances() with pickedInstances() if you want to loop over the picked instances in an event sheet script snippet

## Looping over instances ordered

```javascript
const instances = runtime.objects.sprite.getAllInstances();
const sortedInstances = instances.sort((a, b) => b.instVars.varName - a.instVars.varName);

for (const inst of sortedInstances)
{  
}
```

## For loop

```javascript
for (let i = 0; i < amountOfIterations; i++) {
}
```

## Getting event sheet variables

### Global variables

```javascript
runtime.globalVars.variableName
```

### Instance variables

```javascript
runtime.objects.Sprite.getFirstInstance().instVars.variableName
```

{% hint style="info" %}
here I am getting the first instance, you might want to use getFirstPickedInstance() or [loop over all instances](#looping-over-instances)
{% endhint %}

### Local variables&#x20;

*parameters in functions and custom actions are also local variables*

```javascript
localVars.variableName
```

## Calling an event sheet function

```javascript
runtime.callFunction("functionName", Parameter0, Parameter1, Parameter2...etc)
```

## Returning a value in an event sheet function via scripting

```javascript
runtime.setReturnValue() 
```

{% hint style="info" %}
you cannot return a boolean directly, you need to first convert it into 0 or 1.

bool ? 1 : 0
{% endhint %}

## Accessing by name i.e. via a string or value

in js you can access stuff via a string or variable using brackets, this is really handy and cannot be done in events. A few examples:

```javascript
runtime.globalVars["myVar"]

runtime.objects[localVars.functionParam].getFirstInstance()
```

## Getting instances by UID

in js you can get instances via their UID without requiring the object type, this can be great for generalized getters. (This is how Overboys UID to anything works)\
\
Example of returning an instances x position in an event sheet function, only by passing its UID as a parameter.&#x20;

```javascript
const inst = runtime.getInstanceByUid(localVars.uid);
runtime.setReturnValue(inst.x)
```
