Hydro documentation

Everything in the Hydro language, with examples. The examples run as shown, except the ones that need a sound file or another .hydro file in the same folder.

Start here

Hydro is a small language for scripts, terminal programs and simple screens. Every program starts with Main() => { ... }. Save the file as name.hydro and run it with python -m hydro name.hydro.

Main() => {
    hy.write("Hello, world");
}

Errors show the file, line and column, the source line, and a caret pointing at the problem.

Program structure

  • Statements end with ;. This includes let, change, hy.write(...), return, pull, function calls, and closers such as .closeLoop();.
  • Block statements such as Main() => {{ }} and on(...) => {{ }} need no ; after the final }.
  • Comments: // text runs to the end of the line. /// text /// spans several lines.
  • Main may appear only once.
  • Run order: top-level create new<func> and create new<class> blocks are defined first, then the Main body runs, then any other top-level statements run in order. on blocks start watching at once but do not fire until Main finishes.
  • A top-level function can be called on a line above its create block.
  • Names start with a letter and continue with letters or digits. Names cannot start with _ or a number. Words are case-sensitive.

The using rule

using hy(.end()); lets if blocks end with just } (an optional ; is allowed) instead of }.end();. Only hy is supported.

using hy(.end());
let score as num => 12;
if(=> score >> 10) then => {
    hy.write("high");
};

Variables and types

let name as str => "Bagel";   // typed with a value
let count as num;             // typed, starts as nil
let guess;                    // untyped, takes the type of its first value
change count to be => 5;
let global total as num => 0; // visible after the enclosing block
TypeExamplesNotes
str"text", 'text'Text. Escapes below.
num42, -5Whole numbers.
dec0.5, 2.0Decimals. Digits are needed on both sides of the dot.
toftrue, falseYes or no values.
nilnilNo value. Allowed in any typed variable.
  • num and dec never mix. 2 * 0.5 is an error. Convert first with parseTo.
  • A let with a mismatched value is an error, such as let x as dec => 3;.
  • Using an undeclared name gives an error. Redeclaring a name that already exists in scope is also an error.
  • Variables made inside a block are removed when the block ends.
  • name.exists() returns true when a variable has a value. It never errors.
  • hy.del(name); removes a variable.

Checking and converting types

  • x.isNum(), x.isStr(), x.isToF(), x.isFloat() (dec only), x.isClass(). Pass false to negate, as in x.isNum(false).
  • x.parseTo(type) converts a value. Any value converts to str. Digits convert to num, decimals to dec, "true"/"false" to tof, num to dec, and a whole dec to num.
  • x.parseTo(type, err => deny) does nothing on failure. Without it, a failed conversion is an error.
  • x.autoParse(type) converts the same way as parseTo, but in a dict literal it only converts when the value is grabbed. See Dicts.
  • x.type() prints the type name with a capital letter: Str, Num, Dec, Tof, or Nil. A tuple lists its distinct types in order, such as Str, Num. A dict prints its one stored value type.

Operators

From lowest to highest precedence:

LevelOperatorsNotes
1OR, NORLogical. Left to right.
2ANDLogical. Stops early.
3??Fallback when the left side is nil or false.
4== != < > << >>, value as TYPE IN dict, text %P 50?<target>Comparisons. One per expression.
5++Joins text.
6+ -Add and subtract.
7* div modMultiply, whole-number divide, remainder.
8!, NOT, unary -Prefix.
9^Power. Right to left.
10[ ], .method()Index and method calls.
  • << means less than or equal, and >> means greater than or equal. Write <= only in declarations, such as NAMES.LIST <= [...].
  • div rounds to the nearest whole number, halves away from zero: 7 div 2 is 4 and -7 div 2 is -4. / is not allowed. Use div.
  • mod takes the sign of the divisor: -7 mod 3 is 2 and 7 mod -3 is -2.
  • 2^3^2 is 512 and -5^2 is -25.
  • ++ joins only str values.
  • == and != need both sides to be the same type. nil compares with anything.

Logic

let a as tof => true;
let b as tof => false;
hy.write(a AND b);   // false
hy.write(a OR b);    // true
hy.write(a NOR b);   // false: NOR is true only when both sides are false
hy.write(!b);        // true
hy.write(!a AND b);  // false
  • AND and OR stop early, like Python: the right side runs only when the left side does not decide the answer.
  • NOR is true only when both sides are false.
  • ! and NOT both negate a tof value. They bind tighter than comparisons, so !true == false is true.
  • The operands of AND, OR and NOR must be tof.

Null fallback

let n as num => if(=> false) then => {5} ?? 0;
hy.write(n);   // 0

Dividing decimals

div works on two num values or two dec values. It rounds the result to the nearest whole number, with halves going away from zero. A dec result stays a dec: 10.0 div 3.0 is 3.0, and -7.5 div 2.0 is -4.0. mod still works only on num. To multiply by 1 / x, use x ^ -1.0.

Conditions

let x as num => 5;
if(=> x == 2) then => {
    hy.write("two");
}.end();
if NOT then if(=> x == 3) then => {
    hy.write("three");
}.end();
if NOT then => {
    hy.write("other");
}.end();
  • The condition must be tof.
  • NOT must be capitalized. if NOT then continues the chain directly after an if block.
  • An empty block is allowed.
  • if(=> cond) then => {{ value }} can be used as a value. The result is nil when the condition is false.

Else-if with NOT?

if(=> n > 10) then => {
    return => "big";
}.end();
NOT?(=> n > 5) then => {
    return => "medium";
}.end();
NOT then => {
    return => "small";
}.end();

NOT?(=> condition) then => Ellipsis is an else-if. NOT then is the else. The older if NOT then if(...) form still works.

Loops

let i as num => 0;
create new<loop>{
    while(=> i << 2) => {
        change i to be => i + 1;
    }
}.closeLoop();

create new<loop>{
    for(=> n IN rangeOf(10), 2) => {
        hy.write(n);       // 2 4 6 8 10
    }
}.closeLoop();

create new<array>{
    names.LIST <= ["a", "b"];
}.closeArray();

create new<loop>{
    for(=> item IN names) => {
        hy.write(item);    // each item of a list
    }
}.closeLoop();
  • Every loop uses create new<loop>{{ ... }}.closeLoop();.
  • rangeOf(count, step) runs step, 2 times step, and so on, up to count. Both values are num, and step must be above 0.
  • The loop variable is local to the loop unless it already exists.
  • for(=> item IN list) runs once per list item.
  • END; leaves the nearest loop.

Functions

create new<func>{
    area(num::W, num::H) with num {
        return => W * H;
    };
    hello() {
        hy.write("hi");
    };
}.closeFunc();

hy.write(area(2, 3));   // 6
hello();
  • Parameters are written type::name.
  • with type sets the return type. A function without with cannot return a value.
  • Arguments are checked for count and type.
  • A function can read top-level variables but not the caller's variables.
  • Recursion works.
  • returnVal holds the last returned value.
  • A function can be used inside text: *"Double is {{double(21)}}".

Default values, named values, and rules

A parameter can have a default with ??. A value the caller leaves out uses the default. Parameters with defaults must come after the ones without.

create new<func>{
    ticket(str::name ?? "Guest", str::seat ?? Front, num::count ?? 1) with str {
        hy.write(*"{name} booked {count} ticket(s) for the {seat.choise} seat");
        return => name;
    }.createRule{
        keep => str::name to => 3 len OR >;
        keep => num::count to => 1 OR > AND 4 OR <;
        option => str::seat with values: => {Front: "front", Back: "back"} denying: str;
    };
}.closeFunc();

ticket();                          // Guest booked 1 ticket(s) for the Front seat
ticket(name="Ann", count=2);       // Ann booked 2 ticket(s) for the Front seat
ticket("Ben", "back", 1);          // Ben booked 1 ticket(s) for the Back seat
ticket("Cy", "nope");              // error: 'ticket' needs seat to be one of "front", "back"
  • name=value passes a value by name, in any order, and can skip values that have defaults.
  • .createRule{ ... }; goes after the function's }. Rules run before the function body.
  • keep => type::name to => limit; keeps a value inside limits. OR > means at least, OR < means at most. len checks the length of text. Checks can be joined with AND or OR. AND binds tighter than OR.
  • A limit that fails stops the call with an error, such as 'ticket' rule failed: name must be at least 3 letters.
  • option => type::name with values: => {Key: "text"} denying: str; lets the caller pass only one of the listed texts.
  • name.choise gives the option key the caller picked, such as Front.
  • The form {Key: "text" => value} turns the text into a value. tof::ofAge with values: => {ofAge: "Yes" => true, ofAge: "No" => false} makes "Yes" mean true.
  • A default can name an option: ?? No::false means the option No with the value false. A bare option name, such as ?? Front, uses that option's text.

Classes

create new<class>{
    Player => {
        localSector:: {
            let Health as num;
            let Name as str;
        };
        globalSector:: {
            create new<func>{
                init(str::TName, num::BHealth) with num {
                    localSector.grab<Name> => TName;
                    localSector.grab<Health> => BHealth;
                    localSector.allowEdit(true);
                    return => 0;
                };
                takeDamage(num::amount) with num {
                    change Health to be => Health - amount;
                    return => Health;
                };
            }.closeFunc();
        };
    };
}.closeClass();

let p as class => Player.NEW("Bagel", 100);
hy.write(p.takeDamage(20));   // 80
  • Name.NEW(args) makes an object and runs its init.
  • Fields in localSector:: are private to the object.
  • Inside a method, localSector.grab<Field> => value; sets a field with a type check.
  • Several classes can share one block.
  • There is no inheritance syntax.

Lists, dicts and tuples

create new<array>{
    NAMES.LIST <= ["Bob", "Dylan"];
    stats.DICT <= { HP: 100, MP: 5 };
    t.TUPLE <= (10, "a");
    testDict.DICT <= { Name: "Bagel", Team: "Red" };
}.closeArray();

Lists

  • All items must have the same type. Indexes start at 0: NAMES[1] is Dylan.
  • NAMES.getMax() is the last index, NAMES.getMin() is 0, NAMES.getMid() is the middle index.
  • change NAMES[0] to be => "Ann"; changes one item. The new value must match the item type.

Dicts

  • Keys are names or 'quoted'. All values must share one type. Mixing types, such as Name: "Bagel", Age: 17, is an error.
  • Read with stats['HP']. A missing key is an error.
  • change stats['HP'] to be => 50; changes a value. A dict cannot gain a new key through change.
  • stats.keyLen() is the number of keys.
  • stats.keys() prints the names only: HP, MP.
  • stats.keys(all) prints names and values: HP: 100, MP: 5.
  • stats.findPath(value) prints where a value is, such as stats -> MP -> "5".
  • stats.findKey('MP' => remove); deletes a key. findKey('MP' => replace); restores a key's starting value.
  • value as str IN stats is true when the dict holds a value of that type equal to value.
  • stats.type() prints the dict's value type, such as Str.

Tuples

  • Each item keeps its own type. Read an item with its type: t[num::'0'], t[str::'Name'].
  • A tuple item can only change to its current type.

Automatic parsing in dicts

  • .autoParse(type) in a dict literal is lazy. The value stays as text inside the dict, and it converts only when you grab it: testDict['Age'], keys(all), or findPath.
  • Because the stored text is the dict's value type, "17".autoParse(num) and "18".autoParse(num) can share one dict.
  • If a grabbed value cannot convert, that is an error at the moment you grab it. autoParse(type, err => deny) skips it instead.
create new<array>{
    testDict.DICT <= {
        Name: "Bagel",
        Age: "17".autoParse(num),
        Score: "18".autoParse(num)
    };
}.closeArray();
hy.write(testDict['Age'] + 10);     // 27
hy.write(testDict['Age'].isNum());  // true
hy.write(testDict.type());          // Str (the stored type)

Strings

  • Escapes in normal strings: \n, \t, \", \\. Other escapes are errors.
  • Raw strings: "|text keeps backslashes as they are.
  • Single-quoted strings: 'text'.
  • Interpolation: *"Hi {{name}}, {{count + 1}}". The * must come right before the quote.
MethodDoesExample
s.len()Character count."abc".len() is 3
s.changeTo(lower, i) / upperChanges characters up to index i."HELLO".changeTo(lower, 2) is helLO
s.del("text") / s.del(i)Removes the first match, or the character at index i.
s.sep(i)Text up to index i when positive; from index i to the end when negative."HELLO".sep(-3) is ELLO, "HELLO".sep(2) is HEL
s.getMid()Index of the middle character."abcd".getMid() is 1

Rules

let myNum as num => 100;
create new<rule>{
    change myNum => minVal <= 0;
    change myNum => maxVal <= 100;
    set myNum;
}.closeRule();
change myNum to be => 100 * 10;   // stored as 100
  • minVal and maxVal apply to num and dec.
  • Rules apply on every change: numbers are kept inside the limits.
  • myNum.minVal reads a rule's value.

Errors and attempt

attempt:
    hy.write(1 div 0);
FAIL::(mathError, indexError) {
    hy.write("caught");
}
  • Error kinds for FAIL::(...): typeError, mathError, indexError, inputError.
  • FAIL::() {{ }} or a bare FAIL {{ }} catches every error.
  • mathError: divide by zero, bad powers, negative roots. indexError: index out of range, missing dict key, empty list or text. inputError: end of input from hy.writeIn.
  • err("message") stops the program with a message.

hy commands

CommandWhat it does
hy.write(value);Prints the value and a newline.
hy.write(value).stop();Prints without a newline.
hy.stop();Ends the program.
hy.writeIn("prompt")Asks the user and returns the text. Add .sameLine() to keep the answer on the prompt line, and .parseTo(num) to convert it.
hy.getRandval(min, max, true)Random whole number from min to max, including max.
hy.getRandval(min, max, false)Same, but max is not included. min must be below max.
hy.getTime(format="12") / "24"Current time.
hy.getDate(format=...)Current date in the format you choose.
hy.getHost(format="pc")Your user and computer name.
hy.getHost(format="fs")The folder the script is in.
hy.grabVar("file.hydro", "name")Reads a top-level variable from another file in the same folder.
hy.await(ms);Waits for the given milliseconds.
hy.del(name);Removes a variable.
hy.find(name exists)True when a variable exists.
hy.pushScreen(...)Opens a screen page. Needs pull SMNG();.

Files

  • hy.file(path) gives json, text or bin. Check with hy.file(path) NOT json.
  • hy.json(path) reads a JSON object as a tuple.
  • hy.openFile(path, false) => {{ ... }}; runs a block with the file open. hy.closeFile(); ends the block early.
  • Inside openFile, hy.bin.GetLen(), hy.bin.GetType(), hy.bin.getBytes(start, end) and hy.bin.Conv(bytes, type) read binary data. Types: u8, i8, u16, i16, u32, i32, f32, f64.

Modules

Your own modules

The example needs a file named rndGen.hydro in the same folder that declares let rndGen as module;.

pull rndGen;                 // finds rndGen.hydro in this folder
hy.write(rndGen.answer);     // read a top-level variable
hy.write(rndGen.genRandom(7, 7));  // call a function
  • pull "path/file.hydro"; pulls a file by path.
  • A pulled file must declare let name as module;.
  • A pulled file's Main does not run.
  • A broken .hydro file in the folder can break name pulls.

ADM (math)

pull ADM;
hy.write(ADM.Round(format => "up", true, 10.5));   // 11
hy.write(ADM.Floor(10.5, true));                   // 10
hy.write(ADM.Pow(2, 3));                            // 8
  • Round formats: "up" (halves up), "down" (halves down), "big-up" and "big-down" (nearest power of ten above or below).
  • The same work on any number variable, no pull needed: v.Round(format => "up", true), v.Floor(true), v.Ceiling(false), v.Pow(2).

Soundify (sound)

pull Soundify;
Soundify.playHZ(440, 500);     // tone: frequency, milliseconds
Soundify.playNote("A4", 500);  // note name, milliseconds
Soundify.playAudio("song.mp3");
on(Soundify.currentAudio(finished)) => {
    hy.write("Song finished!");
}
  • Notes: A to G, optional # or b, then an octave digit. A4 is 440 Hz.
  • playAudio plays mp3, wav or ogg. The program waits for the audio at the end.
  • Soundify.currentAudio(none | playing | finished) is true in that state.
  • Windows plays tones and files with built-in sound. Linux needs one of: paplay (pulseaudio-utils), aplay (alsa-utils), or ffplay (ffmpeg). The website plays sound in the browser.

pcUtil (computer information)

pull pcUtil;
hy.write(pcUtil.coreAmount());
hy.write(pcUtil.memTotal());
hy.write(pcUtil.cpuTemp(format="C"));
  • Functions include coreAmount(), activeThreads(), cpuFrequency(), cpuName(), cpuPerc(), cpuTemp(format=), gpuAmount(), gpuName(), gpuTemp(format=), vramTotal(), memTotal() (MB), memUsed(), memFree(), memPerc(), getSystem(), and more.
  • Temperature functions accept format="C", "F" or "K".

SMNG and trueScreen (experimental)

trueScreen (windows and elements, experimental)

Screen and window support is experimental. Members:

MemberWhat it does
init(...)starts the screen
newElement(type, ...)adds an element; type is "button" or "label"
getElement("id")finds an element by its id
getWindow(id, width, height, isFullscreen, isExlusive)reads a window
closeWindow(...)closes a window
hostthe host for the screen
giveActiongives an action to the screen
ActiveElementthe element with focus
ELEMENTSall elements on the screen
readytrue when the screen has loaded
stop()closes the screen

SMNG (pages, experimental)

MemberWhat it does
activeScreen(path)opens a page from a folder
GetElement(id="...")finds an element on the page
Editchanges the page
GetActivethe active element

pcUtil (all functions)

Each one is called as pcUtil.name() after pull pcUtil;. The temperature functions also take format="C", "F" or "K".

GroupFunctions
CPUcpuTemp, activeThreads, coreAmount, cpuFrequency, cpuMaxFrequency, cpuMinFrequency, cpuVModel, cpuArchitecture, cpuName, cpuPerc
SystemmachineType, getSystem
GPUgpuName, gpuModel, gpuArchitecture, gpuAmount, gpuTemp, gpuPerc, gpuMemPerc, gpuFrequency, gpuMaxFrequency, gpuPower, gpuMaxPower, gpuFanSpeed, gpuDriverVersion
Graphics memoryvramTotal, vramUsed, vramFree
MemorymemTotal, memUsed, memFree, memAvailable, memPerc

Command line and editor

  • python -m hydro file.hydro runs a file.
  • python -m hydro --check reads a program from stdin and prints its errors as a JSON list (used by the VS Code extension).
  • python -m hydro with no file opens the interactive prompt.
  • The website editor has tabs, file open and save, live error checking, find and replace, undo and redo, line moving, a Stop button for runs, and sound file support (mp3, wav, ogg).
  • Website shortcuts: Ctrl+F find, Ctrl+H replace, Ctrl+G go to line, Ctrl+Z and Ctrl+Y undo and redo, Alt+Up and Alt+Down move lines, Ctrl+Shift+D duplicate line, Ctrl+Shift+K delete line, Ctrl+Enter or F5 run, Ctrl+S save.
  • VS Code: install the Hydro extension for highlighting and live error checks. Set hydro.hydroFolder to the folder that contains the hydro package.

What is new

  • AND, OR, NOR logic operators, and ! negation.
  • x.parseTo(dec) now works on whole numbers and on text such as "15".
  • Number methods (Round, Floor, Ceiling, Pow) work on any number without pull ADM.
  • Dicts: keyLen(), keys(), keys(all), findPath(value), and .autoParse(type) in dict literals.
  • value as str IN dict membership check.
  • using hy(.end()); so if blocks end with };.
  • hy.stop(); to end a program.
  • text %P 50?<target> is true when text is at least that percent as long as target. The 50 can be any whole number: %P 10?<...>. Without a number it is 50. !text %P ... negates the whole check.
  • x.type() prints a value's type name: Str, Num, Dec, Tof, Nil.
  • Dict autoParse converts only when a value is grabbed.

Version 0.3.19

  • Default values: str::name ?? "Unknown".
  • Named values: greet(name="Ann", age=3).
  • .createRule{ keep ...; option ...; } on functions, with AND and OR joins, name.choise, and option defaults.
  • NOT?(=> cond) then => {...} else-if.
  • div works on dec values.
  • Editor and VS Code extension: all keywords and built-in words are in autocomplete, including rangeOf, changeTo, and the rule words.