Var
On this page

Var()

Function in Authoring

Declare a mutable local and return the node that reads and writes it.

import { Var } from 'typeshade'

The signature, the description and the examples come from the compiler's own source at commit 26de7be8.

Syntax

function Var<K extends string>(init: ReadonlyNode<K>): Node<K>;
function Var<T extends ShaderType>(type: T, init?: ReadonlyNode<KeyOf<T>>): Node<KeyOf<T>>;
function Var<T extends ShaderType>(
name: string,
type: T,
init?: ReadonlyNode<KeyOf<T>>,
): Node<KeyOf<T>>;
function Var<K extends string>(name: string, init: ReadonlyNode<K>): Node<K>;

Parameters

init ReadonlyNode<K>

the initial value.

name

the emitted identifier. Omit it and the builder generates one.

type

the declared type. Omit it when an initialiser carries the type.

Return value

Node<K>

a mutable node reading the binding, and the target of .assign.

Description

Var is the one declarator whose result carries .assign, so it is what a body reaches for when a value changes: an accumulator, a counter, a value a Switch chain fills in per case.

Four shapes are accepted: Var(init) infers the type from the initialiser, Var(type) and Var(type, init) state it, and Var(name, init) or Var(name, type, init) also pin the emitted identifier, which keeps the bytes stable across rebuilds.

A plain const usually needs no Var. Author the intermediate as a JavaScript const and the emit decides between an inlined expression, a shared let and a var; if the value is later assigned to, the auto-var pass materialises it as a real var with no marker from you. Reach for Var when you want the binding named, or when the declaration and the first assignment are far apart.

The read-only bindings are the other half of the rule. A Let result, an fn parameter and a module constant all return the read-only node type, which has no .assign, so mutating one is a tsc error at the authoring line.

Examples

Example

import { Var, Switch, f32 } from 'typeshade'
const radiusPx = Var('radius_px', rawRadius)
Switch(sizeMode)
.case(1, () => radiusPx.assign(rawRadius.div(viewport.z)))
.default(() => {})

In the guide

See also

Source

src/core/ir/builder.ts, line 1658, at commit 26de7be8

Edit this page Report a problem