Skip to content

Variables

Variables store data that can be used and modified throughout your program.

Declaring Variables

Use the let keyword to declare variables:

let name = "Alice";
let age = 30;
let score = 95.5;
let isActive = true;

Variable Names

Variable names must follow these rules:

  • Start with a letter or underscore (_)
  • Contain only letters, numbers, and underscores
  • Cannot be a reserved keyword

Valid Names

let userName = "Bob";
let user_name = "Carol";
let _private = 42;
let value1 = 100;
let myVariable2023 = "data";

Invalid Names

let 123name = "error";    // Cannot start with number
let user-name = "error";  // Cannot contain hyphen
let let = "error";        // Cannot use keyword

Type Inference

CacaoLang automatically determines the type of a variable:

let number = 42;         // Type: number
let text = "hello";      // Type: string
let flag = true;         // Type: bool
let items = [1, 2, 3];   // Type: array

Check types with typeof():

let x = 42;
print typeof(x);  // number

Variable Assignment

Initial Assignment

let count = 0;
let message = "Hello";

Reassignment

Variables can be reassigned to new values:

let count = 0;
count = 10;      // Reassign to 10
count = 20;      // Reassign to 20
print count;     // 20

Important Note

Variables must be declared with let before reassignment:

// Wrong - variable not declared
counter = 10;    // Error!

// Correct
let counter = 0;
counter = 10;    // OK

Scope

Variables have different scopes depending on where they're declared.

Global Scope

Variables declared at the top level are globally accessible:

let global_var = "I'm global";

fn my_function() {
    print global_var;  // Can access global variable
}

my_function();  // I'm global

Function Scope

Variables declared inside functions are local to that function:

fn calculate() {
    let local_var = 42;    // Local to calculate()
    print local_var;       // 42
}

calculate();
print local_var;  // Error: Undefined variable

Block Scope

Variables declared in control structures have block scope:

let x = 10;

if true {
    let y = 20;     // Local to if block
    print x;        // 10 (can access outer scope)
    print y;        // 20
}

print x;            // 10
print y;            // Error: Undefined variable

Nested Scopes

Inner scopes can access outer scope variables:

let outer = "outer";

fn test() {
    let inner = "inner";

    if true {
        let nested = "nested";
        print outer;   // outer (global)
        print inner;   // inner (function scope)
        print nested;  // nested (block scope)
    }
}

test();

Shadowing

Inner scopes can shadow outer variables:

let x = 10;

fn test() {
    let x = 20;     // Shadows global x
    print x;        // 20
}

test();
print x;            // 10 (global x unchanged)

Variable Initialization

Variables should be initialized when declared:

// Good
let count = 0;
let name = "";
let items = [];

// Avoid (may cause issues)
let uninitialized;

Naming Conventions

Descriptive Names

Use clear, descriptive names:

// Good
let user_age = 25;
let total_price = 99.99;
let is_logged_in = true;

// Avoid
let x = 25;
let tp = 99.99;
let flag = true;

Snake Case

CacaoLang commonly uses snake_case for variables:

let user_name = "Alice";
let max_retry_count = 3;
let is_valid_input = true;

camelCase Alternative

camelCase is also acceptable:

let userName = "Bob";
let maxRetryCount = 3;
let isValidInput = true;

Constants

For values that shouldn't change, use UPPERCASE:

let MAX_USERS = 100;
let PI = 3.14159;
let APP_NAME = "MyApp";

Note: CacaoLang doesn't enforce immutability, but this convention helps communicate intent.

Common Patterns

Accumulator Pattern

let sum = 0;
let numbers = [1, 2, 3, 4, 5];

for i in 0..len(numbers) {
    sum = sum + numbers[i];
}

print sum;  // 15

Flag Pattern

let found = false;
let items = ["apple", "banana", "cherry"];
let target = "banana";

for i in 0..len(items) {
    if items[i] == target {
        found = true;
        break;
    }
}

if found == true {
    print "Found #{target}!";
}

Swap Pattern

let a = 10;
let b = 20;

// Swap using temporary variable
let temp = a;
a = b;
b = temp;

print a;  // 20
print b;  // 10

Counter Pattern

let count = 0;

while count < 10 {
    print count;
    count = count + 1;
}

Multiple Variables

Declare multiple variables separately:

let x = 10;
let y = 20;
let z = 30;

Working with Different Types

Numbers

let integer = 42;
let decimal = 3.14;
let negative = -17;
let result = integer + decimal;

Strings

let greeting = "Hello";
let name = "World";
let message = greeting + ", " + name + "!";

Booleans

let is_active = true;
let is_complete = false;
let can_proceed = is_active && !is_complete;

Arrays

let numbers = [1, 2, 3, 4, 5];
let first = numbers[0];
let length = len(numbers);

Structs

struct Point {
    x,
    y
}

let point = Point { x: 10, y: 20 };
let x_coord = point.x;

Variable Lifetime

Variables exist from declaration until the end of their scope:

let global = "exists throughout program";

fn example() {
    let local = "exists during function call";

    if true {
        let block = "exists during if block";
    }
    // 'block' no longer exists here
}
// 'local' no longer exists here

// 'global' still exists

Best Practices

1. Initialize Variables

// Good
let count = 0;
let name = "";
let items = [];

// Risky
let count;

2. Use Meaningful Names

// Good
let user_age = 25;
let order_total = 150.00;

// Bad
let a = 25;
let t = 150.00;

3. Limit Scope

Keep variables in the smallest scope necessary:

// Good
if needs_calculation {
    let temp = expensive_calculation();
    process(temp);
}

// Less efficient
let temp = 0;
if needs_calculation {
    temp = expensive_calculation();
    process(temp);
}

4. Avoid Magic Numbers

// Good
let MAX_RETRIES = 3;
let TAX_RATE = 0.08;

for i in 0..MAX_RETRIES {
    // ...
}

// Avoid
for i in 0..3 {
    // What is 3?
}
// Player data
let player_name = "Alice";
let player_score = 1000;
let player_level = 5;

// Game settings
let difficulty = "hard";
let sound_enabled = true;

Common Mistakes

Forgetting to Declare

// Wrong
count = 10;  // Error: undefined variable

// Correct
let count = 10;

Reassigning Wrong Variable

let total = 0;
let count = 0;

// Later...
total = 100;  // Did you mean to change total or count?

Type Confusion

let number = "42";     // String, not number
let result = number + 10;  // Error: can't add string and number

// Correct
let number = 42;
let result = number + 10;

Next Steps