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 includeslet,change,hy.write(...),return,pull, function calls, and closers such as.closeLoop();. - Block statements such as
Main() => {{ }}andon(...) => {{ }}need no;after the final}. - Comments:
// textruns to the end of the line./// text ///spans several lines. Mainmay appear only once.- Run order: top-level
create new<func>andcreate new<class>blocks are defined first, then theMainbody runs, then any other top-level statements run in order.onblocks start watching at once but do not fire untilMainfinishes. - A top-level function can be called on a line above its
createblock. - 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
| Type | Examples | Notes |
|---|---|---|
str | "text", 'text' | Text. Escapes below. |
num | 42, -5 | Whole numbers. |
dec | 0.5, 2.0 | Decimals. Digits are needed on both sides of the dot. |
tof | true, false | Yes or no values. |
nil | nil | No value. Allowed in any typed variable. |
numanddecnever mix.2 * 0.5is an error. Convert first withparseTo.- A
letwith a mismatched value is an error, such aslet 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(). Passfalseto negate, as inx.isNum(false).x.parseTo(type)converts a value. Any value converts tostr. Digits convert tonum, decimals todec,"true"/"false"totof,numtodec, and a wholedectonum.x.parseTo(type, err => deny)does nothing on failure. Without it, a failed conversion is an error.x.autoParse(type)converts the same way asparseTo, 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, orNil. A tuple lists its distinct types in order, such asStr, Num. A dict prints its one stored value type.
Operators
From lowest to highest precedence:
| Level | Operators | Notes |
|---|---|---|
| 1 | OR, NOR | Logical. Left to right. |
| 2 | AND | Logical. 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 mod | Multiply, 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 asNAMES.LIST <= [...].divrounds to the nearest whole number, halves away from zero:7 div 2is 4 and-7 div 2is -4./is not allowed. Usediv.modtakes the sign of the divisor:-7 mod 3is 2 and7 mod -3is -2.2^3^2is 512 and-5^2is -25.++joins onlystrvalues.==and!=need both sides to be the same type.nilcompares 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
ANDandORstop early, like Python: the right side runs only when the left side does not decide the answer.NORis true only when both sides are false.!andNOTboth negate atofvalue. They bind tighter than comparisons, so!true == falseis true.- The operands of
AND,ORandNORmust betof.
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. NOTmust be capitalized.if NOT thencontinues the chain directly after anifblock.- 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 arenum, 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 typesets the return type. A function withoutwithcannot 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.
returnValholds 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=valuepasses 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.lenchecks the length of text. Checks can be joined withANDorOR.ANDbinds tighter thanOR.- 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.choisegives the option key the caller picked, such asFront.- The form
{Key: "text" => value}turns the text into a value.tof::ofAge with values: => {ofAge: "Yes" => true, ofAge: "No" => false}makes"Yes"meantrue. - A default can name an option:
?? No::falsemeans the optionNowith the valuefalse. 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 itsinit.- 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]isDylan. 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 asName: "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 throughchange.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 asstats -> MP -> "5".stats.findKey('MP' => remove);deletes a key.findKey('MP' => replace);restores a key's starting value.value as str IN statsis true when the dict holds a value of that type equal tovalue.stats.type()prints the dict's value type, such asStr.
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), orfindPath.- 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:
"|textkeeps backslashes as they are. - Single-quoted strings:
'text'. - Interpolation:
*"Hi {{name}}, {{count + 1}}". The*must come right before the quote.
| Method | Does | Example |
|---|---|---|
s.len() | Character count. | "abc".len() is 3 |
s.changeTo(lower, i) / upper | Changes 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
minValandmaxValapply tonumanddec.- Rules apply on every
change: numbers are kept inside the limits. myNum.minValreads a rule's value.
Link
let code as num => 123;
link code with {
type => 000 <= { hy.write("zero"); },
type => 123 <= { hy.write("one twenty three"); };
}.closeLink();
The first matching case runs. No match does nothing.
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 bareFAIL {{ }}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 fromhy.writeIn.err("message")stops the program with a message.
hy commands
| Command | What 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)givesjson,textorbin. Check withhy.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)andhy.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
Maindoes not run. - A broken
.hydrofile 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
pullneeded: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
#orb, then an octave digit. A4 is 440 Hz. playAudioplays 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), orffplay(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:
| Member | What 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 |
host | the host for the screen |
giveAction | gives an action to the screen |
ActiveElement | the element with focus |
ELEMENTS | all elements on the screen |
ready | true when the screen has loaded |
stop() | closes the screen |
SMNG (pages, experimental)
| Member | What it does |
|---|---|
activeScreen(path) | opens a page from a folder |
GetElement(id="...") | finds an element on the page |
Edit | changes the page |
GetActive | the 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".
| Group | Functions |
|---|---|
| CPU | cpuTemp, activeThreads, coreAmount, cpuFrequency, cpuMaxFrequency, cpuMinFrequency, cpuVModel, cpuArchitecture, cpuName, cpuPerc |
| System | machineType, getSystem |
| GPU | gpuName, gpuModel, gpuArchitecture, gpuAmount, gpuTemp, gpuPerc, gpuMemPerc, gpuFrequency, gpuMaxFrequency, gpuPower, gpuMaxPower, gpuFanSpeed, gpuDriverVersion |
| Graphics memory | vramTotal, vramUsed, vramFree |
| Memory | memTotal, memUsed, memFree, memAvailable, memPerc |
Command line and editor
python -m hydro file.hydroruns a file.python -m hydro --checkreads a program from stdin and prints its errors as a JSON list (used by the VS Code extension).python -m hydrowith 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.hydroFolderto the folder that contains thehydropackage.
What is new
AND,OR,NORlogic 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 withoutpull ADM. - Dicts:
keyLen(),keys(),keys(all),findPath(value), and.autoParse(type)in dict literals. value as str IN dictmembership check.using hy(.end());so if blocks end with};.hy.stop();to end a program.text %P 50?<target>is true whentextis at least that percent as long astarget. 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
autoParseconverts 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, withANDandORjoins,name.choise, and option defaults.NOT?(=> cond) then => {...}else-if.divworks ondecvalues.- Editor and VS Code extension: all keywords and built-in words are in autocomplete, including
rangeOf,changeTo, and the rule words.