Skip to content
Documentation

Language guide

A guided tour of Luca Code, one small chapter at a time. Every snippet is a complete, runnable program — type it into a .lucc file, run luca that-file.lucc, and compare what you see with the shown output. Nothing here assumes prior experience with any particular language; if you have programmed before, skim the early chapters.

Before starting, install the luca command: install. Verify with luca --version (prints luca 1.0.4 Beta).

How to follow along

  1. Create a folder for practice and open a terminal there.
  2. Create a file ending in .lucc (for example tour.lucc) and paste in a snippet.
  3. Run it:
luca tour.lucc

Luca runs programs top to bottom, prints output as it goes, and stops with a plain-language message if something is wrong — nothing to configure.

Chapters

#ChapterYou learn
1Hello, LucaRunning your first program
2Values and typesNumbers (int, exact dec), text, booleans, none
3Variablesdef var/def const, reassigning, change, forget, clear()
4StringsInterpolation, joining, comments, escapes
5OperatorsArithmetic precedence, worded comparisons, logic
6Conditionalsif / else if / else with indented blocks
7Loopsfor … times, while, for … from, stop/skip
8Functionsdef func, parameters, defaults, return, closures
9CollectionsLists, tuples, sets, dictionaries, 1-based indexing
10ModulesSharing code between files, the standard library
11Errorstry/capture/finally, custom errors with raise
12Input and the libraryask, command-line arguments, Math/Text/File/System

After the tour, keep the language reference, stdlib, and CLI within reach, and browse the runnable examples.

Conventions used in this tour: console blocks show what the terminal prints; inline code like def marks Luca keywords; little asides about what an error looks like quote the real message you would see.

1. Hello, Luca

Luca Code programs are plain text files ending in .lucc. Create one:

print("Hello, Luca!")

Say the file is named hello.lucc and you are in its folder:

luca hello.lucc

You see exactly:

Hello, Luca!

That is a whole program. Two things worth noticing right away:

  • There is no main() and no startup ceremony. Luca runs your file top to bottom, statement by statement, and prints as it goes.
  • print(...) takes exactly one argument. To include several values, put them in one string with {name} placeholders — that is the next chapters' subject.

To try more than one statement, make a slightly bigger file. Whitespace between statements does not matter, and lines starting with -- are comments:

-- A three-line program.
print("First")
print("Second")

print("Third")
First
Second
Third

Next: values and types.

2. Values and types

Luca has five everyday types plus one special value:

TypeHoldsExamples
intwhole numbers7, -2, 0
decdecimal numbers, kept exact2.5, 0.10, -1.75
strtext in double quotes"Luca", "Age 16"
booltrue or falsetrue, false
uniany value, including a whole collection1, "any", true, [1, "two"]
none"no value" — a special value, not a typenone

You can print any value directly:

print(10 / 4)
print(20.00 + 1.50)
print(true)
print(none)
2.5
21.50
true
none

Decimals are exact

This is Luca's headline numeric feature: 10 / 4 is 2.5, not the truncated 2 that many languages produce for whole-number types. Decimal arithmetic keeps the digits you wrote — 20.00 + 1.50 prints 21.50, keeping two decimal places — and 0.1 + 0.2 really is 0.3, with no hidden floating-point fuzz.

print(10 / 4)
print(0.1 + 0.2)
print(2 - 0.5)
2.5
0.3
1.5

When int and dec values are mixed by arithmetic, the result is dec. Division is numeric division, so even whole results come back as dec: 6 / 2 prints 3.0, while 6 % 2 (remainder) is 0.

Two boundaries to remember:

  • Division or modulo by zero is an error: print(1 / 0) fails with Error at 1:9: Division by zero.
  • Integer results that exceed the 64-bit limit are an error too: Error at 1:27: Integer overflow.

Decimals carry at most 28 fractional digits. A literal with more is rejected, and a division that never terminates is cut (not rounded) at that point: print(1 / 3) gives 0.3333333333333333333333333333.

none means "nothing here"

none is a value that means no value. Printing it prints none; comparing it is fine (value is == to none); but doing arithmetic or logic with it is an error. You will meet it again in variables (a cleared variable becomes none) and collections (a missing entry reads as none).

Text (str) and booleans get their own chapters next, briefly in strings and operators.

Next: variables.

3. Variables

A variable holds a value under a name. Declare it with def var (changeable) or def const (never changes). A type in parentheses is optional when Luca can tell the type from the value you assign:

def const name (str) = "Luca"
def var visits (int) = 1
def var mood = "calm"          -- inferred: str
print("{name} visited {visits} times, mood is {mood}")
Luca visited 1 times, mood is calm

Reassign an existing variable by naming it with its type again — same name, same type:

def var visits (int) = 1
visits (int) = visits + 1
print(visits)
2

change — switch a variable's type

Normally a variable keeps its declared type forever. change is the one (explicit) way to give a variable a new type and value:

def var badge = "ready"
change badge (bool) = false
print(badge)
false

The badge variable no longer holds text — it now holds a boolean. change is always written out in full, and it is the only way to switch types.

clear() — set a variable to none

Calling .clear() on a mutable variable sets it to none while keeping its name and type; you can assign a new value of that type afterwards. Clearing a const is an error.

def var score (int) = 50
score.clear()
print(score)
score (int) = 12
print(score)
none
12

forget — remove a variable, then optionally re-declare

forget removes a binding entirely. The name can then be declared again — even with a different type.

def var mode = "fast"
forget var mode (str)
def var mode (bool) = true
print(mode)
true

The rules in one place

  • One binding per name per scope; re-declaring an existing name is an error (Error at 3:21: 'visits' is already declared).
  • const cannot be reassigned, cleared, or mutated (Cannot change constant).
  • Assigning a value that does not match the declared type is an error: Error at 1:1: Expected int, found str for def var age (int) = "hi".
  • A variable of any declared type may hold none. Working with that none in arithmetic or logic is an error; print it or compare it instead.
  • uni accepts any value: def var anything (uni) = 1, then later anything (uni) = "text" is fine. A uni binding may also hold a collection (def var mixed (uni) = [1, "two"]); collection methods and change mixed[i] = ... operate on the runtime value, and the binding can switch back to a scalar later.

Next: strings.

4. Strings

Text is written between double quotes:

print("Luca Code is a programming language.")
Luca Code is a programming language.

Interpolation — put values inside text

Inside a string, {name} inserts the declared variable name. Interpolation renders the value for printing, so you never convert manually:

def const name (str) = "Luca"
def const age (int) = 16
print("Hello, {name}. You are {age} years old.")
Hello, Luca. You are 16 years old.

Every {...} must name a variable and only a variable — plain braces ({}), math inside braces, or an unknown name are all errors:

  • print("brace {} here") → Error at 1:7: Interpolation supports variable names only in this milestone
  • print("Hi {ghost}") (never declared) → Error at 1:7: 'ghost' is not declared

Joining strings

+ accepts exactly two strings — no mixing text with numbers:

print("fresh " + "water")
print("version " + "1")
fresh water
version 1

print("a" + 1) is an error: Error at 1:11: Arithmetic requires matching numeric types; '+' also accepts two str values. Use interpolation instead.

Escapes

Escapes start with a backslash: \n newline, \r carriage return, \t tab, \" double quote, \\ a literal backslash. Any other escaped character passes through as itself.

print("first\nsecond")
print("quote:\" inner")
first
second
quote:" inner

A string literal cannot span lines — Error at 1:19: String literal cannot contain a raw newline; write \n instead.

Comments

-- This whole line is a comment.
print("seen")       -- This end-of-line part is too.

[[
    Everything here is a multiline comment.
    print("not executed")
]]
print("also seen")
seen
also seen

Beware: [[ always starts a multiline comment, which matters in chapter 9 when writing lists of lists (a leading space [ [ … is the habit to keep).

Next: operators.

5. Operators and comparisons

Arithmetic

OperatorMeaningExampleResult
+add (two numbers) or join (two strings)4 + 37
-subtract10 - 46
*multiply2 * 36
/numeric division10 / 42.5
%remainder10 % 31
- (unary)negate3 - -2 — note the spaces5

Division is always numeric (see chapter 2). Division or remainder by zero is an error, as is integer overflow.

Precedence

Highest first: not, then * / %, then + -, then comparisons, then and, then or. Parentheses override everything:

print(2 + 3 * 4)
print((2 + 3) * 4)
print(10 / 2 - 1)
14
20
4.0

Unary minus needs a space on its left: 3 - -2 is 5. Written without one, 3--2, the -- starts a comment and swallows the rest of the line (Error at 1:12: print accepts exactly one argument).

Worded comparisons

Comparisons read as words: is == to, is != to, is > to, is >= to, is < to, is <= to.

print(5 is == to 5)
print(3 is < to 9)
print(3.0 is >= to 3)
print("abc" is < to "abd")
print(16 is != to 20)
true
true
true
true
true

Equality (is == to, is != to) also works for booleans and, later, collections — and with none: x is == to none. Ordering (is > to and friends) works for numbers and for strings (lexicographic, case-sensitive); ordering anything else is an error. Comparing values of incompatible types is an error rather than false.

Logic

and, or, and not work on booleans only, and and/or short-circuit (the right side is skipped when the left decides the outcome):

print(true and true)
print(false or true)
print(not false)
true
true
true

Next: conditionals.

6. Conditionals

A conditional runs a block only when a condition is true. The colon : opens an indented block; then ends the condition:

def const name (str) = "Luca"
if name is == to "Luca" then :
    print("Hello, {name}!")
else :
    print("Hello.")
Hello, Luca!

Chain alternatives with else if:

def var hour (int) = 15
if hour is < to 12 then :
    print("Morning")
else if hour is < to 18 then :
    print("Afternoon")
else :
    print("Evening")
Afternoon

Blocks indent by four spaces (or tabs) — one level per block, used consistently. In the example above, the two print calls belong to their respective branches; the second print after the block below would run unconditionally.

def var age (int) = 16
if age is >= to 16 then :
    print("Old enough")
print("Checked")     -- outside the block: always runs
Old enough
Checked

Conditions must be booleans

There is no truthiness: numbers, strings, collections, and none are not conditions. if count then : when count is a number fails with Error at 2:1: Condition must be bool; found 2. Compare or combine explicitly:

def var count (int) = 2
if count is > to 0 and count is < to 10 then :
    print("in range")
if not (count is == to 3) then :
    print("not three")
in range
not three

Anything except an empty block may live inside the branches — declarations, loops, more conditionals (nesting indents one more level), even def func.

Next: loops.

7. Loops

Luca has three loop shapes. All of them open an indented block with repeat :.

A fixed number of times

for 3 times repeat :
    print("hi")
hi
hi
hi

The count is any int expression, and it must not be negative. It is evaluated once, before the loop starts — the loop above prints one x, because 3 - n is 1 where n is 2.

While a condition holds

def var count (int) = 3
while count is > to 0 repeat :
    print(count)
    count (int) = count - 1
3
2
1

Like with if, the condition must be a real boolean. An endless while runs forever — Luca does not add a hidden iteration limit, so loop logic is yours to get right.

Over a collection

def list names (str) = ["Luca", "Alex", "Sam"]
for name from names repeat :
    print("Hi {name}")
Hi Luca
Hi Alex
Hi Sam

This reads each item in turn: list, tuple, and set items come out as stored, and dictionary keys iterate (a dict is a set of entries, so the chapter-9 example prints its keys). You do not declare name — the loop binding exists inside the block.

Mutating a collection while iterating it is an error; build a fresh list instead if you need changes.

Leaving early: stop and skip

stop exits the innermost loop; skip jumps straight to the next iteration. Both are exact words, not functions, and using either outside a loop is an error.

for 5 times repeat :
    if true then :
        skip
    print("never printed")
print("done")

for n from [1, 2, 3] repeat :
    if n is == to 2 then :
        stop
    print(n)
print("stopped at two")
done
1
stopped at two

Note the second loop's [1, 2, 3]: collections can be written inline wherever a value is expected, not only in declarations.

Next: functions.

8. Functions

A function bundles steps behind a name and can hand a value back. The block opens with : like the other chapters' blocks:

def func greet(name (str)) (str):
    return "Hello, {name}!"

print(greet("Luca"))
print(greet("Alex"))
Hello, Luca!
Hello, Alex!

Read the signature as: define function greet taking a parameter name of type str, returning str. Types are optional — an untyped parameter accepts any value, and a function without a return type may return different kinds of results.

Defaults and multiple parameters

Parameters are separated by commas; any may carry a default with = value, which makes it optional at the call site. Calls are positional — name(argument), nothing more:

def func describe(name (str) = "you") (str):
    return "Hi {name}"

print(describe())
print(describe("Sam"))
Hi you
Hi Sam

Too many arguments is Error at 3:7: Expected 2 arguments, found 3; too few is Error at 3:7: Missing argument for 'b' (named for the first parameter you failed to supply). Keyword-style calls (describe(a = "x")) do not exist — Error at 5:18: Expected ')' after arguments — that field = value shape belongs to raise in chapter 11.

Returning none

No return type means no invented value at the end: a function that reaches its end — or says plain return — returns none. Calling it in a print shows exactly that:

def func shout(text (str)) :
    print("{text}!")
    -- no return: yields none

print(shout("Here"))
Here!
none

An explicit return type, (str) in the first example, checks every return x against it. In this Beta, none satisfies any declared return type: a bare return, return none, or simply reaching the end of a typed function all yield none rather than an error, so a caller that expects a real value should check for it.

Recursion

A function may call itself; nesting is capped at 64 deep — going past it errors with Recursion limit exceeded rather than hanging. Counting down is the clearest demo:

def func countdown(n (int)) :
    if n is == to 0 then :
        return
    print(n)
    countdown(n - 1)

countdown(3)
3
2
1

Closures

A function may access variables declared outside it — read them, and modify mutable ones. Each call sees the same outer binding:

def var total (int) = 0
def func add(n (int)) :
    total (int) = total + n

add(2)
add(3)
print(total)
5

Rules worth knowing: return outside a function is an error; there is no overloading (two functions with one name is an error); parameters are independent values, so reassigning one inside does not change the caller's variable; recursion and local functions may shadow names freely.

Next: collections.

9. Collections

Luca has four collection kinds. Declaring one reads almost like prose — the kind, then the element type:

def list names (str) = ["Luca", "Alex"]
def tuple data (uni) = (123, true, "Luca")
def set labels (str) = {"alpha", "stable"}
def dict person = {"Name" = "Luca", "Age" = 16}

Lists, tuples, and sets hold one element type (str above; uni when values differ). Dictionaries pair string keys with values, and each value carries its own type.

Reading and indexing

Indices are 1-based — the first item is [1]:

def list names (str) = ["Luca", "Alex"]
print(names[1])
print(names.length)
Luca
2

.length counts items (also string characters and int/dec digit counts); .contains(value) answers membership. A missing read produces a warning and yields none — the program continues:

def list names (str) = ["Luca", "Alex"]
print(names[5])
print("still running")
Warning at 2:8: Index out of range
none
still running

For a dictionary, index with the key: person["Name"]. Missing keys warn with Key 'Phone' not found and similarly yield none.

Changing contents

.add and .remove are statements; change name[index] = value rewrites one slot, and the replacement must match the element type:

def list names (str) = ["Luca", "Alex"]
names.add("Sam")
print(names)
names.remove("Luca")
print(names)
change names[1] = "Jordan"
print(names)
["Luca", "Alex", "Sam"]
["Alex", "Sam"]
["Jordan", "Sam"]

Dictionaries mirror this: person.add("City", "Berlin"), change person["Age"] = 17, person.remove("Name"), and person.clear() empties it. Membership has two forms: person.contains(key = "Age") and person.contains(value = 16).

Notes that save surprises later:

  • A set ignores duplicates: adding "alpha" again warns (Set value already exists) and changes nothing. Sets display in insertion order, though membership logic treats them as unordered.
  • Duplicate dictionary keys at creation warn (Duplicate dictionary key) and keep the first value.
  • Mixing a declaration like def dict person = ... without a value type means values may differ — look again at the Age = 16 line: no (str)-style forcing is needed.
  • Collections read like values but share storage: passing one to a function gives the function the same collection, so its .add calls are visible to you afterwards.
  • [[ starts a multiline comment, so a list whose first item is a list needs a space: write [ [1, 2], [3] ], never [[1, 2], [3] ].

Looping

for item from collection repeat : visits each element; for dictionaries it visits keys:

def dict person = {"Name" = "Luca", "Age" = 16}
for key from person repeat :
    print(key)
Name
Age

Next: modules.

10. Modules

Code lives in files; modules are how files share what they declare. import Name reads the file Name.lucc — same folder first, then the folder you run from — and gives you everything it declared at top level.

Make two files in the same folder.

Helpers.lucc:

def const company (str) = "Luca"
def func hello(name (str)) (str):
    return "hi {name}"

main.lucc:

import Helpers
print(Helpers.company + " says it.")
print(Helpers.hello("you"))
Luca says it.
hi you

What the example shows: the file Helpers.lucc becomes the module Helpers — the import name and the file name match exactly — and every top-level def inside it is automatically visible through the module's name, no export keyword needed. The module is also all you can see from outside: main.lucc's own variables stay home.

Module behavior, briefly:

  • Own scope. A module cannot read your variables; you cannot reach its locals if they are not top-level definitions.
  • Runs once. The first import executes the module's top-level statements; each later import of the same name (even import Helpers inside another imported file) reuses that result. If the top level fails, the error surfaces at the importer.
  • Module.member reads values; Module.func(args) calls functions. Prints of the module itself are not supported.
  • Circular imports are errors (Circular import 'C'), as are missing files (missing module 'Nope') and unknown members (Module 'X' has no member 'y').

The standard library arrives as modules

Math, Text, File, and System are built-in modules — import them exactly like your own, and they win if you ever have a file with the same name:

import Math
print(Math.sqrt(25))
5.0

Forgetting the import is an error: Error at 1:11: Module 'Text' is not imported. Chapter 12 tells the whole story of ask and the library; the stdlib reference lists every function.

Next: errors.

11. Errors

Some mistakes stop the program — that is a plain and useful behavior. This chapter is about the parts of Luca that let you respond to a failing operation instead of crashing.

The shape of trouble

When something cannot proceed, Luca prints one message giving what and where, then stops:

Error at 1:9: Division by zero

Line 1, column 9 — the failing expression. If the program had printed earlier lines, they are not shown: an uncaught error discards pending output (warnings/errors still arrive), which keeps the terminal showing only the diagnosis.

try to — run something, catch the error

import File

def var contents (str) = none
try to :
    contents (str) = File.read("missing.txt")
    print("Read worked")
capture error :
    print("Could not read the file.")
finally :
    print("Cleanup finished")
Could not read the file.
Cleanup finished

Three blocks, each optional except try to : itself:

  • try to : — the risky part. A statement in it fails → the rest of the block is skipped.
  • capture error : — runs only when the try block failed. Only runtime errors land here, not syntax mistakes.
  • finally : — always runs last: after success, after capture, and once before an error keeps propagating outward.

Errors thrown inside functions and modules propagate upward too: capture error in the caller catches a failure from the callee. Warnings, by contrast, are never errors: out-of-range reads, removing absent entries, duplicate keys, missing-deletes — they print a Warning at line:column and continue.

The caught error is a dictionary

Inside capture error :, the name error is bound to a dictionary with the details. Built-in failures carry the location (line, column) and mark code as none:

import Math

try to :
    print(Math.sqrt(-1))
capture error :
    print(error["code"])
    print(error["column"])
none
15

Column 15 points into the failing call on line 2 — the location of the operation that went wrong, not of the capture block.

Custom errors: def error and raise

A custom error declares at least code and message:

def error Validation :
    code = "VALIDATION"
    message = "no good input"

try to :
    raise Validation(code = "EMPTY_NAME", message = "The name was empty")
capture error :
    print(error["code"])
    print(error["message"])
    print(error["line"])
EMPTY_NAME
The name was empty
6

Reading the rules plainly: each raise Name(field = value, ...) replaces the declared field value for this one raise; parentheses after the name are required (raise Validation alone is an error: Expected '(' after error name); line/column tell the raise's spot. Unknown field names or mismatched types are themselves errors — an override must name a field the error actually declares, with a value of that field's type. raise is a statement, never a value-producing expression.

Then the big easy claims: recursion is capped, warnings are nonfatal, and System.exit(n) — the standard library's way to terminate — cannot be caught, though a finally block still runs before the process ends.

Next: input and the library.

12. Input and the library

ask — read one line from the user

ask "question" is an expression that produces the user's input, converted to the type of whatever will hold it:

def const name (str) = ask "What is your name?"
def var age (int) = ask "How old are you?"
print("Hello, {name}. You are {age} years old.")

In a terminal this shows the question, then reads the next line you type:

What is your name?
Luca
How old are you?
16
Hello, Luca. You are 16 years old.

(The console above includes your typed answers; piping input in — printf 'Luca\n16\n' | luca ask.lucc — feeds the same two answers without echoing them.)

Conversion rules, straight from the receiving variable:

  • str keeps the line exactly as typed.
  • int parses whole numbers (signed, trimmed). dec accepts decimals too, including integer-looking input like 16.
  • bool accepts exactly true or false — case-sensitive.

Anything unparseable for the declared type is an error — Error at 2:21: Invalid input 'yesterday': expected int (the ask that reads it) — or if the input stream has ended, No more input available. Both are ordinary runtime errors: they stop the program unless a try to catches them, and no retry is attempted.

ask works anywhere an expression works, which also lets you compose it — print(ask "Who?") reads a line and passes it straight to print.

The standard library at a glance

Four built-in modules cover the everyday terrain; all of them are imported like any module and enforce strict types on their arguments.

ModuleCoversExamples
Mathexact math helpersMath.sqrt(25) → 5.0, Math.max(1, 2.5) → 2.5
Textstring surgeryText.upper("shout") → "SHOUT", Text.split("a-b-c", "-")
Filefiles on diskFile.read("data.txt"), File.exists("notes.md")
Systemthe host worldSystem.os, System.args(), System.exit(3)
import Text

def var raw (str) = ask "tag: "
def var tags (str) = Text.replace(raw, " ", "-")
print(Text.upper(tags))
tag: live demo
LIVE-DEMO

(The tag: prompt prints first, then your typed line follows it in the console.)

Notes worth internalizing now:

  • Wrong argument types or counts are errors — e.g. Math.sqrt(-1) refuses negative numbers, Math.pow needs an integer exponent, and every module function rejects none arguments.
  • File functions that cannot succeed — reading a missing file, writing into a nonexistent directory — are errors and pair well with try to. Deleting an already absent file is the exception: a warning, no change.
  • System.args() returns the full command line as list(str): the luca program itself, your script's path, then any extra words after it. System.env() returns the process environment as a dictionary. System.exit(code) ends the run immediately — uncapturable (chapter 11), with finally still running; the OS sees your code.
  • System.os and System.arch are properties, read without parentheses: System.os() with parens is an error.

Where next? The complete function tables live in the stdlib reference, exact wordings of every message in the language reference, and the runnable showcase programs in the examples gallery.