The comet language, from zero
This page teaches the whole language. Every example has a Run in playground link, so you can change things and see what happens. Nothing to install until you want to.
What comet is
comet is a small language for writing programs that run fast. You write short code that looks a lot like Python, and the comet command turns it into a real native program through C++. Three ideas drive the design:
- Less typing. No semicolons. No type words for numbers:
x = 5creates a number. Only text and true/false use a word (string,bool). - One number type. There is no int vs float.
7 / 2is3.5, and5prints as5, not5.0. - Real speed. Programs are compiled with g++ (or clang++) at -O3, tuned for your own CPU. Variables that only ever hold whole numbers (counters, indexes, sizes) become 64-bit integers, like in C, and the rest are doubles. Lists stay range-checked, so a wrong index gives a message instead of silent garbage. The runtime is comet's own, without the C++ standard library, so compiling takes a fraction of a second and a hello-world program is about 15 KB.
Install and run
Get the compiler from the download page. On Windows run the installer: it puts comet on your PATH by itself and brings its own C++ compiler. On Linux the one-line install script does the same, and you need g++ installed (sudo apt install g++).
Save your program as a file ending in .cmt, then in a terminal:
comet hello.cmt # compile and run in the terminal (errors are shown first)
comet compile hello.cmt # make hello.exe / hello, a standalone program
comet compile hello.cmt -o game # pick the name (optional)
comet make hello.cmt # make hello.exe and run it at once
Or skip all that and use the playground in your browser.
Your first program
Every program starts at a function called main. Code lives inside curly braces. A line is a statement; you never need a semicolon (but one is allowed).
use basic
fun main() {
printl("Hello, comet!")
}Hello, comet!
Commands in this program (3)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
The first line, use basic, tells the compiler which parts of the language this program needs. basic is the everyday set: printing, input, numbers, text, lists, structs, files. You will meet the other modules (map, random, chrono, gui) as you go, and the use section explains the whole idea. A file without any use line still works: it simply gets everything.
Comments start with // or #, and /* ... */ works for longer ones.
Variables and numbers
A variable starts to exist the first time you give it a value. Numbers need no type word.
use basic
fun main() {
x = 5
y = 3.5
z = 10 % 3 // 1 — remainder
half = 7 / 2 // 3.5 — division is exact, never rounded
big = 2 ** 10 // 1024 — power
x = x + 1
x += 1 // same as x = x + 1 (also -= *= /= %=)
x++ // same as x += 1
printl(x, y, z, big, half)
}8 3.5 1 1024 3.5
Commands in this program (3)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
A variable keeps its kind. Once x holds a number it cannot hold text later; the compiler tells you if you try. Text and true/false values are declared with a word:
use basic
fun main() {
string name = "comet"
bool ready = true
name = name + "!"
ready = not ready
printl(name, ready)
}comet! false
Commands in this program (3)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
string s (an empty string) and bool b (false) possible without a value.Useful number functions: abs(x), sqrt(x), floor(x), ceil(x), round(x), round(x, 2), min(a, b), max(a, b), pow(a, b) and int(x) (drops the fraction). Random numbers have their own section.
Strings
Strings are text in double or single quotes. Join them with +; numbers and bools join in automatically. Or put any expression inside { }. Write {{ for a literal brace.
use basic
fun main() {
name = "dan"
age = 17
printl("Hi " + name + ", next year you are " + (age + 1))
printl("Hi {name}, next year you are {age + 1}")
printl("{name.upper()} has {name.len()} letters")
printl("a tab:\t| a new line:\n| braces: {{ }}")
}Hi dan, next year you are 18
Hi dan, next year you are 18
DAN has 3 letters
a tab: | a new line:
| braces: { }Commands in this program (3)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
Strings have many methods (see the reference). The ones you will use most:
use basic
fun main() {
s = " Hello World "
t = s.trim() // "Hello World"
printl(t.upper(), t.lower(), t.len())
printl(t.contains("World"), t.starts_with("He"), t.find("o"))
printl(t.replace("World", "comet"))
printl(t.substr(0, 5), t[0], t[-1])
parts = "a,b,c".split(",") // a list: ["a", "b", "c"]
printl(parts.join(" + "))
printl("-" * 10, "ab" * 3)
for (ch in "hey") { print(ch, end=" ") }
}HELLO WORLD hello world 11 true true 4 Hello comet Hello H d a + b + c ---------- ababab h e y
Commands in this program (16)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.s.trim()A copy without spaces, tabs and new lines at both ends; spaces in the middle stay. Use it on everything a user types.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.s.upper() / s.lower()Copies of the text in capitals or small letters. The original does not change. lower() is the easy way to compare answers without caring how the user typed them.s.len()The number of characters in the text, counting letters from any language as one each. Spaces count as well.s.contains(t)true when t appears anywhere in the text. "x" in s means the same and reads nicely in an if. The match is exact, capitals included.s.starts_with(t) / s.ends_with(t)Check how the text begins or ends. Useful for commands typed by a user, or for checking a file's type.s.find(t)The position where t first appears, counting from 0, or -1 when it is not there. Check for -1 before you use the result.s.replace(a, b)A copy with every a swapped for b. Give an empty b to remove something.s.substr(from, to) / s.substr(from)The piece of text from index from up to, but not including, to. Without to it goes to the end. Negative numbers count from the end, so -2 means the last two characters. slice is another name for it.list [a, b, c]A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.s.split(sep) / s.split()Cuts the text into a list of pieces at every sep. Without an argument it cuts at any spaces and ignores extras, which is perfect for words. join does the opposite.l.join(sep)Glues the items into one text with sep between them. It is the opposite of split, and works for numbers too.for (i in a to b)Repeats a block for every whole number from a up to, but not including, b. Add step to count in other steps (also backwards). for (x in list) goes through a list, a map's keys or a text's characters.print(a, b, …)Works like printl but stays on the same line, so the next print continues right after it. Use it to build one line out of several steps, for example inside a loop. Nothing is added between two separate print calls.
Turn text into a number with num("42") and check first with "42".is_num(). Turn anything into text with str(x).
Printing and input
printl takes any number of values, puts a space between them and ends the line. print is the same but stays on the line (no
at the end), so several prints build one line. Both accept end="…" to choose what comes after the values.
use basic
fun main() {
printl("a", 1, true, [1, 2])
print("no newline")
printl(" ...continued")
printl() // an empty line
}a 1 true [1, 2] no newline ...continued
Commands in this program (5)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.list [a, b, c]A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.print(a, b, …)Works like printl but stays on the same line, so the next print continues right after it. Use it to build one line out of several steps, for example inside a loop. Nothing is added between two separate print calls.
input() reads one line typed by the user and returns it as a string. Give it a prompt to show first.
use basic
fun main() {
name = input("What is your name? ")
years = input("How old are you? ")
if (years.is_num()) {
printl("{name}, in 10 years you will be {num(years) + 10}")
} else {
printl("that is not a number,", name)
}
}Commands in this program (6)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.input(prompt)Shows the prompt, waits until the user types a line and presses Enter, and gives that line back as text. The answer is always text, so use num() when you need a number. In the playground you type the answer right in the console.if / else if / elseRuns a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.s.is_num()true when the text is a number, decimals and minus sign included. Always check user input with it before calling num().printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
In the playground the output panel is a live console: when the program asks, type your answer there and press Enter.
Conditions
if, else if and else. The parentheses around the condition are optional. Compare with == != < > <= >=, combine with and, or, not (&&, ||, ! also work).
use basic
fun main() {
score = 72
if (score >= 90) {
printl("A")
} else if (score >= 70 and score < 90) {
printl("B")
} else {
printl("try again")
}
passed = score >= 50 ? "passed" : "failed" // short form
printl(passed)
if (not "".len() > 0) { printl("empty string") }
}B passed empty string
Commands in this program (5)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.if / else if / elseRuns a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.s.len()The number of characters in the text, counting letters from any language as one each. Spaces count as well.
A number can be used directly as a condition (0 is false), and so can a string or list (empty is false). x in list and "a" in text check membership.
Loops
There are four ways to loop. break leaves a loop, continue jumps to the next round.
use basic
fun main() {
// a range: from 0 up to (not including) 5
for (i in 0 to 5) { print(i, end=" ") }
printl()
// a range with a step, counting down
for (i in 10 to 0 step -2) { print(i, end=" ") }
printl()
// over the items of a list (or the characters of a string, or the keys of a map)
for (word in ["red", "green", "blue"]) { printl(word.upper()) }
// the classic C-style loop
for (i = 0; i < 3; i++) { printl("round", i) }
// while, with break and continue
n = 0
while (true) {
n += 1
if (n % 2 == 0) { continue }
if (n > 7) { break }
print(n, end=" ")
}
printl()
}0 1 2 3 4 10 8 6 4 2 RED GREEN BLUE round 0 round 1 round 2 1 3 5 7
Commands in this program (9)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.for (i in a to b)Repeats a block for every whole number from a up to, but not including, b. Add step to count in other steps (also backwards). for (x in list) goes through a list, a map's keys or a text's characters.print(a, b, …)Works like printl but stays on the same line, so the next print continues right after it. Use it to build one line out of several steps, for example inside a loop. Nothing is added between two separate print calls.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.list [a, b, c]A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.s.upper() / s.lower()Copies of the text in capitals or small letters. The original does not change. lower() is the easy way to compare answers without caring how the user typed them.while (condition)Repeats a block as long as the condition is true. break leaves the loop at once, continue skips to the next round.if / else if / elseRuns a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.
0 to 10 gives 0 through 9, like Python's range(0, 10). That makes for (i in 0 to items.len()) visit every index.Functions
Declare a function with fun. Parameters have no type words; you can pass numbers, strings, lists, anything. Use return to give a value back. Functions can be declared in any order.
use basic
fun greet(name) {
printl("Hello,", name)
}
fun area(w, h) {
return w * h
}
fun describe(x) {
if (x < 0) { return "negative" }
if (x == 0) { return "zero" }
return "positive"
}
fun factorial(n) {
if (n <= 1) { return 1 }
return n * factorial(n - 1)
}
fun main() {
greet("comet")
printl(area(3, 4), describe(-2), factorial(10))
}Hello, comet 12 negative 3628800
Commands in this program (4)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.if / else if / elseRuns a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.
If you want, a parameter can be marked string or bool so that callers get a clear error when they pass the wrong thing: fun shout(string s) { ... }.
Numbers, strings and bools are copied when passed to a function. Lists, maps and structs are shared: a function that changes a list changes the caller's list too, like in Python.
use basic
fun add_one(nums) {
nums.add(1)
}
fun main() {
items = []
add_one(items)
add_one(items)
printl(items) // [1, 1]
}Commands in this program (5)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.l.add(x)Adds an item to the end of the list. push and append are other names for the same thing. An empty list [] takes its kind from the first thing you add.list [a, b, c]A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
Variables declared outside every function are globals; every function can read and change them. The program's entry point main may return a number, which becomes the exit code.
Lists
A list is an ordered collection in square brackets. Indexes start at 0; negative indexes count from the end. All items in a list share one kind (numbers, strings, structs, other lists…).
use basic
fun main() {
nums = [5, 3, 8]
nums.add(1) // [5, 3, 8, 1]
printl(nums[0], nums[-1], nums.len())
nums[1] = 30
nums.sort() // changes the list: [1, 5, 8, 30]
printl(nums, nums.sum(), nums.max())
printl(nums.contains(8), nums.index_of(8), 99 in nums)
printl(nums.slice(1, 3)) // [5, 8]
nums.remove(5) // removes the value 5
last = nums.pop() // removes and returns the last item
printl(nums, last)
names = [] // empty; its kind is set by the first add
names.add("mia")
names.add("bob")
printl(names.join(", "), names.reversed())
grid = [[1, 2], [3, 4]]
grid[1][0] = 30
printl(grid, grid[1][0])
}5 1 4 [1, 5, 8, 30] 44 30 true 2 false [5, 8] [1, 8] 30 mia, bob ["bob", "mia"] [[1, 2], [30, 4]] 30
Commands in this program (15)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.list [a, b, c]A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.l.add(x)Adds an item to the end of the list. push and append are other names for the same thing. An empty list [] takes its kind from the first thing you add.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.s.len()The number of characters in the text, counting letters from any language as one each. Spaces count as well.l.sort() / l.sort_desc()Puts the list itself in order, smallest first, or biggest first with sort_desc. Text sorts alphabetically, with capitals before small letters.l.sum() / l.min() / l.max()Add up the list, or find its smallest or biggest item, without writing a loop.s.contains(t)true when t appears anywhere in the text. "x" in s means the same and reads nicely in an if. The match is exact, capitals included.l.contains(x) / l.index_of(x) / l.count(x)contains says whether x is in the list, index_of gives its position (or -1), and count says how many times it appears. x in l is the same as contains.l.slice(from, to)A new list with the items from position from up to, but not including, to. Without to it goes to the end. Negative numbers count from the end.l.remove(x) / l.remove_at(i)remove finds the first item equal to x and takes it out, and tells you with true or false whether it found one. remove_at takes out the item at a position.l.pop() / l.pop(i)Removes an item and gives it back: the last one, or the one at position i. pop with add makes a stack; pop(0) with add makes a queue.l.join(sep)Glues the items into one text with sep between them. It is the opposite of split, and works for numbers too.l.sorted() / l.reversed() / l.copy()These give back a new list and leave the original alone. copy matters because lists are shared: b = a does not make a copy, both names mean the same list.
Build a list of numbers quickly with range(5) → [0, 1, 2, 3, 4] or range(1, 10, 2). Indexing past the end stops the program with a clear runtime error instead of reading garbage.
Maps
A map stores values under keys, written {key: value}. Keys are kept in sorted order. Reading a key that is not there is an error, so use has or get with a fallback.
use map
fun main() {
ages = {"dan": 17, "bob": 20}
ages["eve"] = 30 // add or change
printl(ages["dan"], ages.len(), ages.has("zoe"))
printl(ages.get("zoe", 0)) // 0 because zoe is missing
for (name in ages) { // loops over the keys
printl(name, "is", ages[name])
}
printl(ages.keys(), ages.values())
ages.remove("bob")
printl(ages)
counts = {} // empty; kinds are set by the first use
for (w in "a b a c a".split(" ")) {
counts[w] = counts.get(w, 0) + 1
}
printl(counts)
}17 3 false
0
bob is 20
dan is 17
eve is 30
["bob", "dan", "eve"] [20, 17, 30]
{"dan": 17, "eve": 30}
{"a": 3, "b": 1, "c": 1}Commands in this program (12)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.map {key: value}A map stores values under keys, like a dictionary: m["apple"] is the value saved under "apple". Keys are text or numbers. See comet help has, comet help keys, comet help get.list [a, b, c]A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.s.len()The number of characters in the text, counting letters from any language as one each. Spaces count as well.m.has(key)true when the key is in the map. key in m means the same.m.get(key, fallback)Like m[key], but gives the fallback when the key is missing instead of stopping the program. It is the classic way to count things.for (i in a to b)Repeats a block for every whole number from a up to, but not including, b. Add step to count in other steps (also backwards). for (x in list) goes through a list, a map's keys or a text's characters.m.keys() / m.values()Lists of all keys and all values, always in sorted key order. for (k in m) walks the keys directly.l.remove(x) / l.remove_at(i)remove finds the first item equal to x and takes it out, and tells you with true or false whether it found one. remove_at takes out the item at a position.s.split(sep) / s.split()Cuts the text into a list of pieces at every sep. Without an argument it cuts at any spaces and ignores extras, which is perfect for words. join does the opposite.
Structs
A struct is your own kind of value: a bundle of named fields, plus functions (methods) that work on them. Every field has a starting value. Inside a method, fields are used by their plain names.
use basic
struct Player {
string name = "guest"
score = 0
items = []
fun hit(points) {
score += points
}
fun pick(item) {
items.add(item)
printl("{name} picked up {item}")
}
}
fun main() {
p = Player() // all fields at their starting values
q = Player("dan", 50) // values in field order
p.name = "mia"
p.hit(10)
q.hit(5)
q.pick("key")
printl(p.name, p.score, q.name, q.score)
printl(q) // structs print nicely
team = [p, q]
for (member in team) { member.hit(100) }
printl(p.score, q.score)
}dan picked up key
mia 10 dan 55
Player{name: dan, score: 55, items: ["key"]}
110 155Commands in this program (7)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.struct NameMakes your own kind of value with named fields (and functions inside it, called methods). Name(...) makes one; the values fill the fields in order, missing ones keep their starting value.list [a, b, c]A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.l.add(x)Adds an item to the end of the list. push and append are other names for the same thing. An empty list [] takes its kind from the first thing you add.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.for (i in a to b)Repeats a block for every whole number from a up to, but not including, b. Add step to count in other steps (also backwards). for (x in list) goes through a list, a map's keys or a text's characters.
Struct values are shared, not copied: team holds the same players as p and q, so hitting a team member changes p. Fields can hold other structs (center = Point()), lists of structs, and so on. The word self refers to the struct itself inside a method, for example to pass it to a function.
Random numbers
Random numbers come from the random module (see use below; a file without use lines has it). Ranges are written with to and include both ends.
use random
fun main() {
dice = random(1 to 6) // 1, 2, 3, 4, 5 or 6
price = float.random(4.5 to 10) // for example 7.3129
printl("you rolled", dice)
printl("price:", round(price, 2))
printl(random(), random(-)) // a big whole number, then a negative one
}Commands in this program (6)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.random(a to b)A whole number from a to b, and both ends can come up. This is the one you want for dice, for picking a position, or any "choose a number" job. Every run gives different results.float.random(a to b)A decimal number between a and b. Use it for smooth values such as a speed or a price. float.random() with nothing gives a number from 0 up to 1.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.round(x) / round(x, n)Rounds to the nearest whole number. With a second number it keeps that many decimals, which is the usual way to print prices or results neatly.
random() alone gives a whole number from 0 up to 2147483647, random(-) a negative one, random(list) picks an item, and list.shuffle() mixes a list.
use: picking modules
comet's built-in functions come in groups called modules. A use line at the top of a file names the modules the program needs, and the compiler then builds the program with exactly those, nothing more. Think of it as the program saying what it is about: use random means "this program rolls dice", use gui means "this program opens a window".
use random, map
fun main() {
scores = {"dan": random(1 to 100), "mia": random(1 to 100)}
for (name in scores) {
printl(name, scores[name])
}
}Commands in this program (7)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.map {key: value}A map stores values under keys, like a dictionary: m["apple"] is the value saved under "apple". Keys are text or numbers. See comet help has, comet help keys, comet help get.random(a to b)A whole number from a to b, and both ends can come up. This is the one you want for dice, for picking a position, or any "choose a number" job. Every run gives different results.for (i in a to b)Repeats a block for every whole number from a up to, but not including, b. Add step to count in other steps (also backwards). for (x in list) goes through a list, a map's keys or a text's characters.printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.list [a, b, c]A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.
The rules
- Where:
uselines go at the very top, before anyfunorstruct. Several modules can share one line (use random, map) or each get their own line. - basic is always there. Writing
use basicis the way to say "nothing special"; you never have to add it for the other modules to work. Lists, strings, numbers, structs, printing, input and files are all basic. - No use line at all: the program gets every module except
gui, so older programs and quick experiments keep working. The compiler then reads the whole runtime, which makes the compile a little slower. - Using something you did not name stops the compile with a message that tells you the exact line to add, for example random() needs `use random` at the top of the file. You do not have to know which module a function belongs to; the message tells you.
- gui is the exception: windows always need an explicit
use gui, even in a file with no otheruselines, because a window program is built very differently from a console program. - Spellings:
use listanduse vectorare accepted and mean nothing extra (lists are basic);use timeis the same asuse chrono.
Why it exists
The top of a file shows at a glance whether it uses randomness, maps, timing or a window, and mistakes are caught with a precise message. A file that names its modules also compiles a little faster than one with no use line, because the compiler reads only those parts of the runtime. comet's runtime has no C++ standard library in it, so the difference is small and a small program compiles in a fraction of a second either way.
Windows and graphics
With use gui a program can open real windows: on Windows out of the box, on Linux with the X11 headers installed (sudo apt install libx11-dev), and in the playground, where the window is drawn right in the page and your keys and clicks go to the program. new.window(title) or new.window(title, width, height) makes one. Positions are pixels from the top-left corner; leave them out for the top-left.
Want to really learn windows? The Windows page teaches them step by step: coordinates, colours, shapes, buttons, animation, the keyboard and mouse, pictures and a whole game.
use gui
fun main() {
window = new.window("Hello window", 500, 320)
window.print("Hello from comet!")
window.print("What is your name?", 20, 60)
string name = window.input("name: ", 20, 90)
window.color("green")
window.print("Nice to meet you, " + name + "!", 20, 140)
window.button("Quit", 20, 190)
while (window.open()) {
if (window.clicked("Quit")) { break }
window.sleep(0.02)
}
}Commands in this program (11)
use basic, map, random, chrono, guiThe first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b)Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.new.window(title, width, height)Opens a new window on the screen and gives it back to you. title is the text in the window's top bar, width and height are its size in pixels (the tiny dots of the screen); leave them out for 640 wide and 480 high. Keep the window in a variable, usually called window: every other window command is written after it, like window.print(...), window.rect(...).window.print(text) / window.print(text, x, y)Writes text inside the window, like printl does in the console. With x and y you choose where: x is how many pixels from the left edge, y how many pixels down from the top edge, and that point is the top-left corner of the text. Without x and y, each print goes on the next line under the last one (or where window.goto said). The text stays there until window.clear().window.input(prompt) / window.input(prompt, x, y)Asks the user to type something. It shows the prompt text with a typing box next to it, waits until the user presses Enter, and gives back what they typed, as text. Your program stops on this line until then. x and y choose where the prompt and box appear.window.color(name)Picks the colour for everything you draw after it: text, lines, rectangles and circles. Think of it as picking up a different pen; it stays until you pick another. The name is a colour word like "red" or "green" (see the colour table), or your own colour as "#rrggbb".window.button(text, x, y) / window.clicked(text)window.button puts a clickable button in the window, with text written on it, at x pixels from the left and y pixels from the top; you make it once. window.clicked("text") tells you whether that button was clicked: it is true one time after each click and false otherwise, so you ask it again and again inside a loop.while (condition)Repeats a block as long as the condition is true. break leaves the loop at once, continue skips to the next round.window.open() / window.wait() / window.close()window.open() is true while the window is still there and turns false when the user closes it; that is why loops say while (window.open()). window.wait() just waits until the user closes the window, for programs that show something and are done. window.close() closes the window from your program.if / else if / elseRuns a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.window.sleep(seconds)Waits a short time while keeping the window alive, and shows what you have drawn so far. In a window loop always use this one, never plain sleep(), because plain sleep freezes the window. window.sleep(0.02) waits 0.02 seconds, which makes 50 pictures (frames) a second: a smaller number makes a game faster.
new.window(title, width, height)Opens a new window on the screen and gives it back to you. title is the text in the window's top bar, width and height are its size in pixels (the tiny dots of the screen); leave them out for 640 wide and 480 high. Keep the window in a variable, usually called window: every other window command is written after it, like window.print(...), window.rect(...).
window = new.window("My app", 400, 300)
window.wait()window = new.window("Big")
window.wait()one = new.window("One", 200, 100)
two = new.window("Two", 200, 100)
one.print("first")
two.print("second")
one.wait()window.print(text) / window.print(text, x, y)Writes text inside the window, like printl does in the console. With x and y you choose where: x is how many pixels from the left edge, y how many pixels down from the top edge, and that point is the top-left corner of the text. Without x and y, each print goes on the next line under the last one (or where window.goto said). The text stays there until window.clear().
window = new.window("Text")
window.print("first")
window.print("second")
window.wait()window = new.window("Text")
window.print("over here", 200, 100)
window.wait()window = new.window("Score")
score = 12
window.print("Score: {score}", 10, 10)
window.wait()window.goto(x, y)Moves the writing position: the next window.print or window.input without its own x and y starts at this point (x pixels from the left, y pixels from the top). After each print the position moves one line down, so a few prints after one goto make a neat column.
window = new.window("Goto")
window.goto(50, 80)
window.print("at 50, 80")
window.wait()window = new.window("Goto")
window.goto(100, 20)
window.print("one")
window.print("two")
window.wait()window = new.window("Table")
window.goto(20, 20)
window.print("name")
window.goto(150, 20)
window.print("score")
window.wait()window.color(name)Picks the colour for everything you draw after it: text, lines, rectangles and circles. Think of it as picking up a different pen; it stays until you pick another. The name is a colour word like "red" or "green" (see the colour table), or your own colour as "#rrggbb".
window = new.window("Colours")
window.color("yellow")
window.print("yellow text")
window.wait()window = new.window("Colours")
window.color("#ff8800")
window.print("orange text")
window.wait()window = new.window("Colours")
window.color("red")
window.rect(20, 20, 50, 50)
window.color("blue")
window.circle(120, 45, 25)
window.wait()window.background(name)Paints the whole window in one colour, behind everything else. Without it the window is dark. Usually you set it once, right after new.window.
window = new.window("Blue")
window.background("blue")
window.wait()window = new.window("Light")
window.background("white")
window.color("black")
window.print("dark on light")
window.wait()window = new.window("Sea")
window.background("#004466")
window.wait()window.input(prompt) / window.input(prompt, x, y)Asks the user to type something. It shows the prompt text with a typing box next to it, waits until the user presses Enter, and gives back what they typed, as text. Your program stops on this line until then. x and y choose where the prompt and box appear.
window = new.window("Ask")
string name = window.input("name: ")
window.print("hi " + name)
window.wait()window = new.window("Ask")
string age = window.input("age: ", 50, 100)
window.print("next year: " + (num(age) + 1), 50, 140)
window.wait()window = new.window("Form")
first = window.input("first name: ")
last = window.input("last name: ")
window.print(first + " " + last)
window.wait()window.button(text, x, y) / window.clicked(text)window.button puts a clickable button in the window, with text written on it, at x pixels from the left and y pixels from the top; you make it once. window.clicked("text") tells you whether that button was clicked: it is true one time after each click and false otherwise, so you ask it again and again inside a loop.
window = new.window("Button")
window.button("Quit", 20, 20)
while (window.open()) {
if (window.clicked("Quit")) { break }
window.sleep(0.02)
}window = new.window("Count")
window.button("Click me", 20, 20)
n = 0
while (window.open()) {
if (window.clicked("Click me")) {
n += 1
window.title("clicks: {n}")
}
window.sleep(0.02)
}window = new.window("Choose")
window.button("Yes", 20, 20)
window.button("No", 100, 20)
while (window.open()) {
if (window.clicked("Yes")) { window.alert("yes!") }
if (window.clicked("No")) { window.alert("no!") }
window.sleep(0.02)
}window.image(file, x, y, width, height)Draws a picture (a png, jpg, bmp or gif file next to your program) in the window. x and y are where its top-left corner goes; width and height stretch it to that size, or leave them out to get the picture's own size. Transparent parts stay see-through. In the playground city.png and bird.png are ready to use, and the Add image button brings in your own.
window = new.window("City", 480, 640)
window.image("city.png", 0, 0, 480, 640)
window.wait()window = new.window("Bird", 480, 640)
window.image("city.png", 0, 0, 480, 640)
window.image("bird.png", 100, 200)
window.wait()window = new.window("Fly", 480, 300)
for (x in 0 to 400 step 4) {
window.clear()
window.image("bird.png", x, 100, 48, 36)
window.sleep(0.02)
}window.line(x1, y1, x2, y2)Draws a straight line from one point to another, in the current colour (window.color). The first point is x1, y1 and the second is x2, y2, each counted in pixels from the window's top-left corner. Example: window.line(0, 0, 100, 100) goes from the corner diagonally down to the right.
window = new.window("Line")
window.line(0, 0, 200, 100)
window.wait()window = new.window("Cross")
window.color("red")
window.line(50, 50, 150, 150)
window.line(150, 50, 50, 150)
window.wait()window = new.window("Fan")
for (x in 0 to 300 step 30) {
window.line(150, 200, x, 0)
}
window.wait()window.rect(x, y, width, height)Draws a filled rectangle (a box), filled with the current colour (window.color). x and y say where its top-left corner is: x pixels from the left edge, y pixels down from the top. width says how wide the box is and height how tall, in pixels. Example: window.rect(10, 20, 100, 50) draws a box 100 wide and 50 tall whose corner is 10 from the left and 20 from the top. Use it for walls, bars, buttons, a player, the ground.
window = new.window("Rect")
window.color("red")
window.rect(20, 20, 100, 50)
window.wait()window = new.window("Bars")
for (i in 0 to 5) {
window.rect(20 + i * 40, 150 - i * 20, 30, i * 20 + 10)
}
window.wait()window = new.window("Board", 200, 200)
for (y in 0 to 4) {
for (x in 0 to 4) {
if ((x + y) % 2 == 0) { window.rect(x * 50, y * 50, 50, 50) }
}
}
window.wait()window.circle(x, y, radius)Draws a filled circle (a disc) in the current colour. x and y are the centre of the circle (not its corner, unlike rect), and radius is how far the edge is from the centre, so the circle is radius * 2 pixels wide. Example: window.circle(200, 150, 30) draws a circle 60 wide around the point 200, 150.
window = new.window("Circle")
window.color("green")
window.circle(100, 100, 40)
window.wait()window = new.window("Row")
for (i in 0 to 5) {
window.circle(40 + i * 60, 80, 20)
}
window.wait()window = new.window("Target")
window.color("red")
window.circle(100, 100, 60)
window.color("white")
window.circle(100, 100, 40)
window.color("red")
window.circle(100, 100, 20)
window.wait()window.clear()Wipes the window clean: all text, shapes, pictures and buttons disappear, and only the background colour is left. Moving pictures use it at the start of every frame: clear, draw everything at its new place, then window.sleep shows the new picture all at once, so nothing flickers.
window = new.window("Clear")
window.print("gone in a second")
window.sleep(1)
window.clear()
window.wait()window = new.window("Move")
for (x in 0 to 300 step 3) {
window.clear()
window.rect(x, 50, 20, 20)
window.sleep(0.01)
}window = new.window("Count")
for (i in 3 to 0 step -1) {
window.clear()
window.print("{i}", 100, 100)
window.sleep(1)
}window.key()Tells you which key was pressed: it gives back the key's name, like "a", "space" or "left", or "" (empty text) if nothing was pressed since you last asked. Each press is given only once, which is right for single actions like jump, pause or quit. Key names are lowercase: letters, digits, enter, space, escape, left, right, up, down, backspace, tab, shift, ctrl, alt, delete, home, end, f1 and so on.
window = new.window("Keys")
while (window.open()) {
k = window.key()
if (k != "") { window.print(k) }
window.sleep(0.02)
}window = new.window("Press escape")
while (window.open()) {
if (window.key() == "escape") { break }
window.sleep(0.02)
}window = new.window("Jump")
jumps = 0
while (window.open()) {
if (window.key() == "space") {
jumps += 1
window.title("jumps: {jumps}")
}
window.sleep(0.02)
}window.key_down(name)Tells you whether one key is being held down right now: true while it is held, false when it is not. Use it for movement, so holding an arrow keeps moving. The name is the key's lowercase name, like "left", "up", "space" or "a".
window = new.window("Hold")
x = 100
while (window.open()) {
if (window.key_down("left")) { x -= 3 }
if (window.key_down("right")) { x += 3 }
window.clear()
window.rect(x, 100, 30, 30)
window.sleep(0.02)
}window = new.window("Move")
x = 100
y = 100
while (window.open()) {
if (window.key_down("left")) { x -= 3 }
if (window.key_down("right")) { x += 3 }
if (window.key_down("up")) { y -= 3 }
if (window.key_down("down")) { y += 3 }
window.clear()
window.circle(x, y, 15)
window.sleep(0.02)
}window = new.window("WASD")
x = 100
while (window.open()) {
if (window.key_down("a")) { x -= 3 }
if (window.key_down("d")) { x += 3 }
window.clear()
window.rect(x, 80, 30, 30)
window.sleep(0.02)
}window.mouse_x() / window.mouse_y() / window.mouse_down()Tell you about the mouse: mouse_x is how many pixels the pointer is from the window's left edge, mouse_y how many from the top edge, and mouse_down is true while the left mouse button is held down. On a phone, a finger touching the window counts as the mouse.
window = new.window("Paint")
while (window.open()) {
if (window.mouse_down()) { window.circle(window.mouse_x(), window.mouse_y(), 5) }
window.sleep(0.01)
}window = new.window("Follow")
while (window.open()) {
window.clear()
window.circle(window.mouse_x(), window.mouse_y(), 20)
window.sleep(0.01)
}window = new.window("Where")
while (window.open()) {
window.title("{window.mouse_x()}, {window.mouse_y()}")
window.sleep(0.05)
}window.alert(text) / window.ask(text)Pop-up messages. window.alert shows a small box with your text and an OK button, and waits until OK is pressed. window.ask shows your question with Yes and No buttons, waits for the answer, and gives back true for Yes and false for No.
window = new.window("Hi")
window.alert("Saved!")window = new.window("Save")
if (window.ask("Save the file?")) {
window.alert("Saved!")
}window = new.window("Game")
while (window.ask("Play again?")) {
window.alert("Playing…")
}window.sleep(seconds)Waits a short time while keeping the window alive, and shows what you have drawn so far. In a window loop always use this one, never plain sleep(), because plain sleep freezes the window. window.sleep(0.02) waits 0.02 seconds, which makes 50 pictures (frames) a second: a smaller number makes a game faster.
window = new.window("Wait")
window.print("one moment")
window.sleep(1)window = new.window("Loop")
while (window.open()) {
window.sleep(0.02)
}window = new.window("Slow")
for (i in 0 to 5) {
window.print("line {i}")
window.sleep(0.3)
}
window.wait()window.open() / window.wait() / window.close()window.open() is true while the window is still there and turns false when the user closes it; that is why loops say while (window.open()). window.wait() just waits until the user closes the window, for programs that show something and are done. window.close() closes the window from your program.
window = new.window("Stay")
window.print("close me")
window.wait()window = new.window("Loop")
while (window.open()) {
window.sleep(0.05)
}
printl("the window was closed")window = new.window("Short")
window.sleep(1)
window.close()window.title(text) / window.width() / window.height()window.title changes the text in the window's top bar. window.width() and window.height() give the size of the inside of the window in pixels, so window.width() / 2 is always the middle, even after the user made the window bigger.
window = new.window("Old")
window.title("New")
window.wait()window = new.window("Size", 300, 200)
window.title("{window.width()} x {window.height()}")
window.wait()window = new.window("Centre", 300, 200)
window.circle(window.width() / 2, window.height() / 2, 30)
window.wait()Two whole games: the snake example draws with shapes, and flappy uses a city image as the background and a bird image.
Built-in functions
Every command, what it does, and three examples with what they print. Each example has a Run link that opens it as a complete program in the playground, so you can change it and try again.
Printing and input
printl(a, b, …)Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
printl("Hello!")Hello!
age = 17
printl("age:", age, "adult:", age >= 18)age: 17 adult: false
printl("first")
printl()
printl("third")first third
print(a, b, …)Works like printl but stays on the same line, so the next print continues right after it. Use it to build one line out of several steps, for example inside a loop. Nothing is added between two separate print calls.
print("Hello, ")
printl("world")Hello, world
for (i in 0 to 5) {
print(i)
}
printl()01234
print("a", "b")
print("c")
printl()a bc
print(x, end="…")end= chooses what is written after the values instead of the usual ending. It works on both print and printl. It is the easy way to separate items by a comma or to end a line with something of your own.
for (i in 1 to 4) {
print(i, end=", ")
}
printl()1, 2, 3,
printl("done", end="!\n")done!
for (i in 0 to 5) {
print("#", end="")
}
printl(" 100%")##### 100%
input(prompt)Shows the prompt, waits until the user types a line and presses Enter, and gives that line back as text. The answer is always text, so use num() when you need a number. In the playground you type the answer right in the console.
name = input("What is your name? ")
printl("Hi " + name)years = input("Your age? ")
printl("Next year you are", num(years) + 1)answer = input("A number please: ")
while (not answer.is_num()) {
answer = input("That is not a number. Again: ")
}
printl("Thanks,", answer)The screen: position and colours
goto(x, y)Moves the cursor to a place on the screen, and the next print starts there. x counts characters from the left and y counts lines from the top; the top-left corner is 0, 0. It lets you draw anywhere, which is what animations and text games need.
command("cls")
goto(20, 5)
printl("in the middle")command("cls")
for (i in 0 to 10) {
goto(i * 2, i)
print("*")
}
printl()command("cls")
for (x in 0 to 30) {
goto(x, 2)
print(" o")
sleep(0.05)
}
printl()color("name")Changes the colour of all text printed after it, until the next color call. The names are red, green, blue, yellow, white, black, gray, orange, purple, pink, brown, cyan, dark and light, or any colour written like #ff8800. color("reset") goes back to the terminal's normal colour; do it before your program ends.
color("red")
printl("Warning!")
color("reset")color("#ff8800")
printl("orange text")
color("reset")for (c in ["red", "green", "blue"]) {
color(c)
print(c + " ")
}
color("reset")
printl()color("text", "background")With two names, the second one colours the space behind the text. This is how you make highlighted labels, or solid blocks by printing spaces.
color("white", "red")
print(" ALERT ")
color("reset")
printl()color("black", "yellow")
print(" note ")
color("reset")
printl(" read this")color("white", "green")
print(" ")
color("reset")
printl()cursor(on)cursor(false) hides the blinking cursor and cursor(true) shows it again. Hide it while an animation runs so it does not flicker around the screen, and always bring it back at the end.
cursor(false)
for (i in 0 to 10) {
print(".")
sleep(0.1)
}
cursor(true)
printl()cursor(false)
goto(5, 5)
printl("no cursor while drawing")
cursor(true)cursor(false)
cursor(true)
printl("back to normal")screen_width() / screen_height()How many characters fit across the terminal, and how many lines fit down it. Use them so that your drawing fits any window instead of guessing a size.
printl(screen_width(), "x", screen_height())printl("-" * screen_width())command("cls")
text = "centre"
goto((screen_width() - text.len()) / 2, screen_height() / 2)
printl(text)command("cls")Clears the whole screen and puts the cursor at the top-left. "cls" and "clear" do the same on every system, also in the playground. Use it at the start of a text game or between the frames of an animation.
printl("this disappears")
command("cls")
printl("clean screen")for (i in 3 to 0 step -1) {
command("cls")
printl(i)
sleep(0.5)
}command("clear")
printl("clear works too")Text and numbers
num(text)Turns text into a number. You need it because input() and split() give you text, and text cannot do math. If the text is not a number the program stops with a clear error, so check with .is_num() first when the text comes from a user.
printl(num("41") + 1)42
printl(num("2.5") * 2)5
s = "abc"
if (s.is_num()) {
printl(num(s))
} else {
printl("not a number")
}not a number
str(x)Turns any value into text. Often you do not need it, because + and {curly braces} already convert for you, but it is handy when you want to call a text method on a number.
s = str(42)
printl(s.len(), "characters")2 characters
printl(str(7).pad_left(3, "0"))007
printl(str(true) + " " + str([1, 2]))true [1, 2]
int(x)Drops everything after the decimal point, so it always moves toward zero. It is not rounding: 3.9 becomes 3. Use round() if you want the nearest whole number.
printl(int(3.9), int(3.1))3 3
printl(int(-3.9))-3
printl(int("12.7"))12
bool(x)Turns a value into true or false. A number is false only when it is 0. Text is true when it says "true", "1" or "yes".
printl(bool(0), bool(5))false true
printl(bool("yes"), bool("no"))true false
answer = "yes"
if (bool(answer)) { printl("ok then") }ok then
len(x)The size of something: letters in a string, items in a list, keys in a map. It is the same as calling .len() on the value, so use whichever reads better.
printl(len("comet"))5
printl(len([1, 2, 3]))3
names = ["mia", "bob"]
for (i in 0 to len(names)) {
printl(i, names[i])
}0 mia 1 bob
type(x)The kind of a value, as text: number, string, bool, list, map or the name of your struct. Useful when you are learning or debugging and want to see what a value really is.
printl(type(5), type("a"), type(true))number string bool
printl(type([1, 2]))list
printl(type(1.5))number
chr(n) / ord(s)Every character has a code number. ord gives the code of a character and chr gives the character for a code. They let you do math with letters.
printl(ord("A"), chr(65))65 A
printl(chr(ord("a") + 1))b
for (i in 0 to 5) {
print(chr(ord("a") + i))
}
printl()abcde
Math
abs(x)The distance from zero: a negative number loses its minus sign and a positive one stays the same. Handy for "how far apart are these two values".
printl(abs(-5), abs(5))5 5
printl(abs(3 - 10))7
a = 1.0
b = 1.01
printl(abs(a - b) < 0.1)true
sqrt(x)The square root: the number that gives x when multiplied by itself. It is the core of the distance formula used in games.
printl(sqrt(16))4
printl(round(sqrt(2), 3))1.414
dx = 3
dy = 4
printl(sqrt(dx * dx + dy * dy))5
pow(a, b)a multiplied by itself b times. The ** operator does exactly the same and is shorter to write.
printl(pow(2, 10))1024
printl(2 ** 10)1024
printl(pow(9, 0.5))3
floor(x) / ceil(x)floor always rounds down to the whole number below, ceil always rounds up to the one above. Note the direction with negative numbers: floor(-2.5) is -3.
printl(floor(2.7), ceil(2.1))2 3
printl(floor(-2.5), ceil(-2.5))-3 -2
printl(ceil(25 / 10))3
round(x) / round(x, n)Rounds to the nearest whole number. With a second number it keeps that many decimals, which is the usual way to print prices or results neatly.
printl(round(2.4), round(2.6))2 3
printl(round(3.14159, 2))3.14
printl("average:", round(10 / 3, 1))average: 3.3
min(a, b) / max(a, b)The smaller or the bigger of two numbers. Given one list, they find its smallest or biggest item. Together they are a simple way to keep a value inside limits.
printl(min(3, 7), max(3, 7))3 7
printl(max([1, 9, 4]), min([1, 9, 4]))9 1
x = 130
printl(max(0, min(x, 100)))100
sum(list)Adds up all the numbers in a list. It is the same as .sum() on the list, and saves you from writing a loop.
printl(sum([1, 2, 3]))6
scores = [70, 80, 90]
printl(sum(scores) / len(scores))80
printl(sum(range(10)))45
sin(x), cos(x), tan(x)The trigonometry functions. Angles are in radians, not degrees: multiply degrees by 3.14159 / 180. They are what you use for circles, waves and rotating things.
printl(sin(0), cos(0))0 1
angle = 90 * 3.14159265 / 180
printl(round(sin(angle), 3))1
for (i in 0 to 5) {
printl(" " * (5 + int(4 * sin(i))) + "*")
} *
*
*
*
*log(x), log10(x), exp(x)log is the natural logarithm, log10 the base-ten one, and exp is the opposite of log. log10 tells you how many digits a number has, roughly.
printl(log10(1000))3
printl(exp(0), round(log(exp(2)), 3))1 2
n = 12345
printl(floor(log10(n)) + 1)5
range(n) / range(a, b) / range(a, b, step)Makes a list of numbers. One value counts from 0, two values count from a up to (not including) b, and a third value sets the step. Use it when you want the numbers themselves as a list; to just loop, for (i in 0 to n) is simpler.
printl(range(4))[0, 1, 2, 3]
printl(range(2, 6))[2, 3, 4, 5]
printl(range(0, 10, 5))[0, 5]
Random numbers
random(a to b)A whole number from a to b, and both ends can come up. This is the one you want for dice, for picking a position, or any "choose a number" job. Every run gives different results.
printl(random(1 to 6))for (i in 0 to 10) {
print(random(1 to 6), end=" ")
}
printl()if (random(0 to 1) == 1) { printl("heads") } else { printl("tails") }float.random(a to b)A decimal number between a and b. Use it for smooth values such as a speed or a price. float.random() with nothing gives a number from 0 up to 1.
printl(float.random(4.5 to 10))printl(round(float.random(1 to 20), 2))if (float.random() < 0.3) { printl("lucky!") }random()A big whole number from 0 to 2147483647. Good when you only need "some number", for example as an id; use % to bring it into a smaller range.
printl(random())printl("id-" + random())printl(random() % 10)random(-)A negative whole number, from -2147483647 to -1.
printl(random(-))printl(random(-) < 0)printl(random(-10 to -1))random(list)Picks one item of a list. All items have the same chance. The list stays as it is.
printl(random(["red", "green", "blue"]))answers = ["yes", "no", "maybe"]
printl(random(answers))printl(random([10, 20, 30]))Time
sleep(seconds)Pauses the program. Decimals are fine, so sleep(0.1) waits a tenth of a second. It also sends everything printed so far to the screen, which makes it the heart of every console animation.
printl("wait…")
sleep(0.1)
printl("done")wait… done
for (i in 0 to 3) {
printl(i)
sleep(0.1)
}0 1 2
for (i in 0 to 5) {
print(".")
sleep(0.05)
}
printl().....
time()The current time as seconds since the year 1970. It is mostly useful for measuring long waits, or as a number that is different every run.
printl(time() > 1000000000)true
printl(floor(time() / 86400) > 19000)true
start = time()
sleep(0.2)
printl(time() - start > 0.1)true
clock()A stopwatch with very high precision. A single reading means nothing; subtract two readings to see how long something took. It is the right tool to measure the speed of your code.
start = clock()
sleep(0.1)
printl(clock() - start > 0.05)true
start = clock()
total = 0
for (i in 0 to 1000000) { total += i }
printl(total, clock() - start < 1)499999500000 true
start = clock()
sleep(0.25)
printl(round(clock() - start, 2), "seconds")Files and the system
write_file(path, text)Creates a file with this text. If the file already exists, its old content is replaced. To add to a file instead, use append_file.
write_file("note.txt", "hello")
printl(read_file("note.txt"))hello
write_file("note.txt", "one")
write_file("note.txt", "two")
printl(read_file("note.txt"))two
items = ["milk", "eggs"]
write_file("shop.txt", items.join("\n"))
printl(read_file("shop.txt"))milk eggs
read_file(path)Gives the whole file as one text. Combine it with .lines() to go through a file line by line. If the file does not exist the program stops with an error, so check with file_exists first when you are not sure.
write_file("a.txt", "hi there")
printl(read_file("a.txt"))hi there
write_file("a.txt", "one\ntwo")
for (line in read_file("a.txt").lines()) {
printl("line:", line)
}line: one line: two
write_file("a.txt", "the quick brown fox")
printl(read_file("a.txt").split().len())4
append_file(path, text)Adds text at the end of a file and creates it when needed. Old content stays, which makes it the right command for a log or a score list. Add "\n" yourself if you want a new line.
write_file("log.txt", "a")
append_file("log.txt", "b")
printl(read_file("log.txt"))ab
write_file("log.txt", "")
append_file("log.txt", "first\n")
append_file("log.txt", "second\n")
print(read_file("log.txt"))first second
write_file("n.txt", "")
for (i in 0 to 3) {
append_file("n.txt", str(i))
}
printl(read_file("n.txt"))012
file_exists(path)true when the file is there. Use it before read_file, for example to load a save file only if one exists.
printl(file_exists("no-such-file.txt"))false
write_file("yes.txt", "x")
printl(file_exists("yes.txt"))true
if (file_exists("save.txt")) {
printl("loading")
} else {
printl("new game")
}new game
command("text")Runs a command of the operating system, as if you typed it in the terminal, and gives back its exit code: 0 usually means it worked. Commands differ between Windows and Linux, so a program using it may only work on one of them. In the playground commands run in the sandbox.
code = command("exit 0")
printl("exit code", code)exit code 0
printl(command("exit 3"))3
command("dir")open("target")Opens something the way a double-click would: a program, a file with its usual program, or a web link. It gives back true when that worked and your program keeps running. In the playground and the phone app only web links can open, in a new tab.
open("https://comet.okak0.com")open("photo.png")open("notepad")args()The words typed after your program's name on the command line, as a list of text. With comet game.cmt easy 3 you get ["easy", "3"]. They are text, so use num() for numbers.
printl(args().len())0
for (a in args()) {
printl(a)
}level = "normal"
if (args().len() > 0) { level = args()[0] }
printl(level)normal
exit() / exit(code)Ends the program immediately, wherever you are. The number is the exit code that other programs can see; 0 means everything went well and any other number means a problem.
printl("bye")
exit(0)
printl("never printed")bye
ok = true
if (not ok) { exit(1) }
printl("still running")still running
for (i in 0 to 100) {
if (i == 2) {
printl("stopping at", i)
exit()
}
}stopping at 2
Methods
Strings
s.len()The number of characters in the text, counting letters from any language as one each. Spaces count as well.
printl("comet".len())5
printl("a b".len())3
printl("héllo".len())5
s.upper() / s.lower()Copies of the text in capitals or small letters. The original does not change. lower() is the easy way to compare answers without caring how the user typed them.
printl("Comet".upper(), "Comet".lower())COMET comet
s = "Hi"
s.upper()
printl(s)Hi
answer = "YES"
printl(answer.lower() == "yes")true
s.trim()A copy without spaces, tabs and new lines at both ends; spaces in the middle stay. Use it on everything a user types.
printl("[" + " hi ".trim() + "]")[hi]
printl("[" + " a b ".trim() + "]")[a b]
typed = " yes "
printl(typed.trim() == "yes")true
s.contains(t)true when t appears anywhere in the text. "x" in s means the same and reads nicely in an if. The match is exact, capitals included.
printl("comet".contains("ka"))false
printl("x" in "comet")false
printl("Comet".contains("co"), "Comet".lower().contains("co"))false true
s.starts_with(t) / s.ends_with(t)Check how the text begins or ends. Useful for commands typed by a user, or for checking a file's type.
printl("main.cmt".starts_with("main"), "main.cmt".ends_with(".cmt"))true true
line = "add milk"
if (line.starts_with("add ")) { printl("adding", line.substr(4)) }adding milk
printl("photo.png".ends_with(".jpg"))false
s.find(t)The position where t first appears, counting from 0, or -1 when it is not there. Check for -1 before you use the result.
printl("hello".find("ll"))2
printl("hello".find("z"))-1
s = "name,age"
printl(s.substr(0, s.find(",")))name
s.count(t)How many times t appears in the text, without overlaps.
printl("banana".count("a"))3
printl("the cat and the dog".count("the"))2
printl("comet".count("z"))0
s.replace(a, b)A copy with every a swapped for b. Give an empty b to remove something.
printl("a-b-c".replace("-", "+"))a+b+c
printl("h e l l o".replace(" ", ""))hello
printl("I like cats".replace("cats", "dogs"))I like dogs
s.split(sep) / s.split()Cuts the text into a list of pieces at every sep. Without an argument it cuts at any spaces and ignores extras, which is perfect for words. join does the opposite.
printl("a,b,c".split(","))["a", "b", "c"]
printl("the quick fox".split())["the", "quick", "fox"]
total = 0
for (p in "1 2 3".split()) { total += num(p) }
printl(total)6
s.lines() / s.chars()lines() gives a list with one item per line, and chars() a list with one item per character. Looping for (c in s) also walks the characters.
printl("one\ntwo".lines())["one", "two"]
printl("hey".chars())["h", "e", "y"]
printl("a\nb\nc".lines().len())3
s.substr(from, to) / s.substr(from)The piece of text from index from up to, but not including, to. Without to it goes to the end. Negative numbers count from the end, so -2 means the last two characters. slice is another name for it.
printl("comet lang".substr(0, 4))come
printl("comet lang".substr(5))lang
printl("comet".substr(-2))et
s[i]One character, as text. The first is s[0] and the last is s[-1]. Text cannot be changed this way; build a new string instead.
printl("comet"[0], "comet"[-1])c t
s = "hello"
printl(s[1])e
w = "comet"
printl(w[0].upper() + w.substr(1))Comet
s.reverse()A backwards copy of the text.
printl("comet".reverse())temoc
s = "level"
printl(s == s.reverse())true
printl(str(123).reverse())321
s.repeat(n) / s * nn copies of the text joined together. The * form is the shorter one.
printl("ab".repeat(3))ababab
printl("-" * 10)----------
for (i in 1 to 4) {
printl("*" * i)
}* ** ***
s.pad_left(n) / s.pad_right(n)Fills the text up to width n, with spaces or with a character you give. Great for lining up columns and for numbers with leading zeros.
printl("7".pad_left(3, "0"))007
printl("[" + "ab".pad_right(5) + "]")[ab ]
printl("milk".pad_right(8) + "2")
printl("bread".pad_right(8) + "1")milk 2 bread 1
s.is_num()true when the text is a number, decimals and minus sign included. Always check user input with it before calling num().
printl("42".is_num(), "4x".is_num())true false
printl("-2.5".is_num())true
s = "12"
printl(s.is_num() ? num(s) * 2 : 0)24
Lists
l.add(x)Adds an item to the end of the list. push and append are other names for the same thing. An empty list [] takes its kind from the first thing you add.
l = [1]
l.add(2)
printl(l)[1, 2]
names = []
names.add("mia")
names.add("bob")
printl(names)["mia", "bob"]
squares = []
for (i in 1 to 5) { squares.add(i * i) }
printl(squares)[1, 4, 9, 16]
l[i]Reads or changes one item. Counting starts at 0, and negative numbers count from the end. Going past the end stops the program with a clear message rather than giving you garbage.
l = [5, 6, 7]
printl(l[0], l[-1])5 7
l = [5, 6, 7]
l[1] = 60
printl(l)[5, 60, 7]
l = ["a", "b"]
for (i in 0 to l.len()) { printl(i, l[i]) }0 a 1 b
l.len() / l.empty()len is the number of items and empty is true when there are none.
printl([1, 2, 3].len())3
l = []
l.add(1)
printl(l.empty())false
q = [4]
if (not q.empty()) { printl(q[0]) }4
l.insert(i, x)Puts x at position i and moves the rest one step right. insert(0, x) puts it at the front.
l = [1, 3]
l.insert(1, 2)
printl(l)[1, 2, 3]
l = ["b"]
l.insert(0, "a")
printl(l)["a", "b"]
l = [1]
l.insert(1, 2)
printl(l)[1, 2]
l.extend(other) / a + bextend adds all items of another list to this one. a + b leaves both lists alone and makes a new joined list.
l = [1]
l.extend([2, 3])
printl(l)[1, 2, 3]
a = [1]
b = [2]
printl(a + b, a)[1, 2] [1]
all = []
for (part in [[1, 2], [3]]) { all.extend(part) }
printl(all)[1, 2, 3]
l.pop() / l.pop(i)Removes an item and gives it back: the last one, or the one at position i. pop with add makes a stack; pop(0) with add makes a queue.
l = [1, 2, 3]
printl(l.pop(), l)3 [1, 2]
l = [1, 2, 3]
printl(l.pop(0), l)1 [2, 3]
l = ["a", "b"]
while (not l.empty()) { printl(l.pop()) }b a
l.remove(x) / l.remove_at(i)remove finds the first item equal to x and takes it out, and tells you with true or false whether it found one. remove_at takes out the item at a position.
l = [1, 2, 3]
l.remove(2)
printl(l)[1, 3]
l = ["a", "b", "c"]
l.remove_at(0)
printl(l)["b", "c"]
l = [1]
printl(l.remove(9), l.remove(1))false true
l.contains(x) / l.index_of(x) / l.count(x)contains says whether x is in the list, index_of gives its position (or -1), and count says how many times it appears. x in l is the same as contains.
l = [4, 5]
printl(l.contains(5), 9 in l)true false
printl(["a", "b"].index_of("b"), ["a"].index_of("z"))1 -1
printl([1, 2, 1, 1].count(1))3
l.sort() / l.sort_desc()Puts the list itself in order, smallest first, or biggest first with sort_desc. Text sorts alphabetically, with capitals before small letters.
l = [2, 3, 1]
l.sort()
printl(l)[1, 2, 3]
l = [2, 3, 1]
l.sort_desc()
printl(l)[3, 2, 1]
l = ["zoe", "adam"]
l.sort()
printl(l)["adam", "zoe"]
l.sorted() / l.reversed() / l.copy()These give back a new list and leave the original alone. copy matters because lists are shared: b = a does not make a copy, both names mean the same list.
l = [2, 1]
printl(l.sorted(), l)[1, 2] [2, 1]
printl([1, 2, 3].reversed())[3, 2, 1]
a = [1]
b = a
c = a.copy()
a.add(2)
printl(b, c)[1, 2] [1]
l.reverse() / l.shuffle()Change the list itself: reverse flips the order and shuffle mixes it randomly. shuffle needs use random.
l = [1, 2, 3]
l.reverse()
printl(l)[3, 2, 1]
cards = [1, 2, 3, 4, 5]
cards.shuffle()
printl(cards)deck = ["A", "K", "Q"]
deck.shuffle()
printl("you drew", deck.pop())l.slice(from, to)A new list with the items from position from up to, but not including, to. Without to it goes to the end. Negative numbers count from the end.
printl([1, 2, 3, 4].slice(1, 3))[2, 3]
printl([1, 2, 3].slice(1))[2, 3]
printl([1, 2, 3].slice(-2))[2, 3]
l.first() / l.last()The first and the last item. Same as l[0] and l[-1], but they read well. Calling them on an empty list stops the program with a message.
l = [7, 8, 9]
printl(l.first(), l.last())7 9
printl([3, 1, 2].sorted().first())1
printl(["a", "b"].last())b
l.sum() / l.min() / l.max()Add up the list, or find its smallest or biggest item, without writing a loop.
l = [1, 2, 3]
printl(l.sum(), l.min(), l.max())6 1 3
l = [2, 4]
printl(l.sum() / l.len())3
l = [5, 1, 9]
printl(l.max() - l.min())8
l.join(sep)Glues the items into one text with sep between them. It is the opposite of split, and works for numbers too.
printl(["a", "b"].join(" and "))a and b
printl([1, 2, 3].join("-"))1-2-3
printl(["o", "k"].join(""))ok
l.clear()Removes all items; the list itself stays and can be filled again. Because lists are shared, everyone holding this list sees it empty.
l = [1, 2]
l.clear()
printl(l)[]
l = [1]
l.clear()
l.add(5)
printl(l)[5]
a = [1]
b = a
a.clear()
printl(b)[]
Maps (use map)
m[key] / m[key] = vA map stores values under keys. m[key] reads a value and stops with an error if the key is missing; m[key] = v adds the key or changes its value.
ages = {"dan": 17}
printl(ages["dan"])17
ages = {"dan": 17}
ages["mia"] = 20
ages["dan"] = 18
printl(ages){"dan": 18, "mia": 20}names = {1: "one", 2: "two"}
printl(names[2])two
m.get(key, fallback)Like m[key], but gives the fallback when the key is missing instead of stopping the program. It is the classic way to count things.
m = {"a": 1}
printl(m.get("a", 0), m.get("z", 0))1 0
counts = {}
for (w in "a b a".split()) { counts[w] = counts.get(w, 0) + 1 }
printl(counts){"a": 2, "b": 1}settings = {"size": 10}
printl(settings.get("speed", 5))5
m.has(key)true when the key is in the map. key in m means the same.
m = {"a": 1}
printl(m.has("a"), m.has("z"))true false
printl("a" in {"a": 1})true
m = {"a": 1}
if (m.has("b")) { printl(m["b"]) } else { printl("no b") }no b
m.set(key, v) / m.remove(key)set does the same as m[key] = v. remove deletes a key and tells you with true or false whether it was there.
m = {"a": 1}
m.set("b", 2)
printl(m){"a": 1, "b": 2}m = {"a": 1, "b": 2}
m.remove("a")
printl(m){"b": 2}m = {"a": 1}
printl(m.remove("z"), m.remove("a"))false true
m.keys() / m.values()Lists of all keys and all values, always in sorted key order. for (k in m) walks the keys directly.
m = {"b": 2, "a": 1}
printl(m.keys(), m.values())["a", "b"] [1, 2]
m = {"x": 1, "y": 2}
for (k in m) { printl(k, m[k]) }x 1 y 2
printl({"a": 1, "b": 2}.values().sum())3
m.len() / m.empty() / m.clear() / m.copy()The same as for lists: how many keys, is it empty, remove everything, and make a real copy.
m = {"a": 1}
printl(m.len(), m.empty())1 false
m = {"a": 1}
m.clear()
printl(m.len())0
a = {"x": 1}
c = a.copy()
a["y"] = 2
printl(c.len(), a.len())1 2
Errors
Mistakes are reported with the file, line, a caret and plain words. The compiler checks names, argument counts, that a variable keeps its kind, that list items match, and much more before any C++ is involved.
hello.cmt:3:9: error: 's' is a string, cannot store a number in it
3 | s = 5
^
Runtime errors (an index past the end of a list, a missing map key, num("abc"), reading input when there is none) stop the program with Runtime error: … and exit code 1.
A few rules that trip people up at first:
- A variable first set inside an
ifor loop and used after it must get a starting value before the block (total = 0). - An empty list
[]or map{}takes its kind from the firstadd/ assignment the compiler can see; give it a value early. - A function that calls itself should have its simple case (a
returnwithout the recursive call) first, so the compiler can tell what it returns. - Strings cannot be changed in place (
s[0] = "x"); build a new one instead.
The comet command
Every command has exactly one name. To run a program you write just the file: comet main.cmt. For everything else the command comes first, then the file. Type comet help for the list, or comet help and a command name (for example comet help make) for what it does, its options and examples.
| Command | What it does |
|---|---|
| comet file.cmt [things for the program] | Compiles the program and runs it right in your terminal. Nothing is left in your folder: the compiled program is kept in comet's cache, so running the same code again starts instantly. If there is a mistake, comet shows the line and runs nothing. Words after the file name go to your program: comet main.cmt hello 42 makes args() give ["hello", "42"]. |
| comet compile file.cmt [-o name] | Makes a standalone program file you can copy to another computer: comet compile main.cmt gives main.exe on Windows (main on Linux), and -o game names it game.exe (you only need -o when you want another name). It does not run it. |
| comet make file.cmt [-o name] [things for the program] | Both at once: makes the program file like comet compile, then runs it in the terminal like comet main.cmt. Use it when you want the exe and want to try it straight away. |
| comet check file.cmt | Only looks for mistakes; runs nothing and makes no file. Prints "no errors" when the code is fine. |
| comet cpp file.cmt [-o folder] | Your program as plain, readable C++ with std::cout, std::string, std::vector and std::map. With -o folder it saves main.cpp, comet.hpp (a few helpers) and how to build it: g++ -std=c++20 main.cpp -o main. |
| comet c file.cmt [-o folder] | Your program as plain, readable C (window programs not yet). With -o folder it saves main.c, okak_rt.h and how to build it with any C compiler: gcc main.c -o main -lm. |
| comet version | Prints which comet you have, for example comet 1.0.0. |
| comet update | Downloads and installs the newest comet. The compiler checks once a day and tells you when there is one. |
| comet help [command] | The list of commands, or everything about one command. It also explains every command of the language with its examples and their output, the same as this page: comet help print, comet help split, comet help for, comet help window.rect. |
Options go before or after the file name:
| Option | Works with | What it does |
|---|---|---|
| -o name | compile, make | Optional. The name of the program file; without it the program gets the name of your .cmt file (main.cmt makes main.exe). |
| --portable | compile, make | A program for any 64-bit PC. Without it the program is tuned for your own CPU, which is a little faster but may not start on an older computer. |
| --size | compile, make | Makes the program file as small as possible. |
| --debug | compile, make | No optimising: compiles quicker, runs slower. |
| --fast | running, compile, make | Skips the check that list indexes are inside the list. A little faster, but a wrong index crashes instead of giving a message. |
| --v | every command | Also shows the C++ compiler's own messages next to comet's. |
| --clang | every command | Builds with clang++ instead of g++ when both are installed. |
Mistype something and comet tells you what to write instead; for example comet --version answers Write: comet version, and comet run main.cmt answers Write: comet <file.cmt>.
About speed: a small program compiles in a fraction of a second, and an unchanged program starts instantly from the cache. The Windows installer also prepares windows.h for window programs. The cache lives in ~/.cache/comet (Linux) or %LOCALAPPDATA%\comet\cache (Windows) and can be deleted at any time.
Cheat sheet
// program structure
fun main() { ... } // entry point
fun name(a, b) { return a + b } // functions
struct Point { x = 0; y = 0; fun len() { return sqrt(x*x + y*y) } }
// values
n = 5 s = "text" string t = "" bool ok = true
l = [1, 2, 3] m = {"a": 1} p = Point(3, 4)
// text
"{n} items" "a" + n s.len() s.upper() s.split(",") s.trim()
// control
if (c) { } else if (d) { } else { } x = c ? a : b
for (i in 0 to 10) { } for (i in 10 to 0 step -1) { }
for (x in list) { } for (i = 0; i < n; i++) { }
while (c) { break; continue }
// operators
+ - * / % ** == != < > <= >= and or not x in list
+= -= *= /= %= x++ x--
// lists & maps
l.add(x) l[i] l.len() l.sort() l.join(",") l.contains(x) l.pop()
m[k] = v m[k] m.get(k, d) m.has(k) m.keys() m.remove(k)
// the screen
goto(x, y) color("green") color("reset") cursor(false) screen_width()
// i/o
printl(a, b) print(x) print(x, end=" ") input("? ") num(s) str(x)
command("cls") command("dir") open("notepad") open("https://comet.okak0.com")
// modules (top of the file; none = everything except gui)
use random, map random(1 to 6) float.random(0 to 1) random(-)
use gui w = new.window("t") w.print("hi", x, y) w.goto(x, y) w.input("? ")
w.color("red") w.image("city.png", x, y, width, height) w.wait()