ProtoLang.net

Reference: Function

☰ Hide Sidebar
TOKEN FUNCTION
ALIAS None

The Function token allows you to define reusable blocks of code that can accept parameters and return values. Functions help organize code, reduce repetition, and create modular programs. Each function has its own local scope for variables, and can be called multiple times throughout your program.

Syntax

The short syntax structure uses the word FUNCTION:

FUNCTION NAME ( PARAMETERS )
    STATEMENTS
END FUNCTION

The long syntax structure uses the word FUNCTION:

FUNCTION NAME GROUP PARAMETERS END GROUP
    STATEMENTS
END FUNCTION

Function Components

A function definition consists of several required parts:

1. Function Name

The unique identifier for the function. Function names follow the same variable rules names: they can contain letters (both uppercase and lowercase) and are case-sensitive.

FUNCTION greet ( )
    PRINTLN "Hello!"
END FUNCTION

2. Parameters (Optional)

Parameters are variables that receive values when the function is called. Each parameter must specify its Data Type. Multiple parameters are separated by the Divider token.

FUNCTION add ( INT a , INT b )
    NEW INT sum = a + b
    RETURN sum
END FUNCTION

3. Function Body

The statements that execute when the function is called. These can include any valid ProtoLang commands, including variable declarations, loops, conditionals, and other function calls.

4. Return Statement

The RETURN token specifies the value the function sends back to the caller. The return value's data type must match what the function is expected to return.

FUNCTION multiply ( INT x , INT y )
    NEW INT result = x * y
    RETURN result
END FUNCTION

Basic Function Examples

Example: Function with No Parameters

FUNCTION sayHello ( )
    PRINTLN "Hello, World!"
END FUNCTION

sayHello ( ) // Calls the function
// Displays: Hello, World!

Example: Function with One Parameter

FUNCTION greetUser ( STR name )
    PRINTLN "Hello, " .. name .. "!"
END FUNCTION

greetUser ( "Alice" )
greetUser ( "Bob" )
// Displays: Hello, Alice!
// Displays: Hello, Bob!

Example: Function with Multiple Parameters

FUNCTION addNumbers ( INT a , INT b )
    NEW INT sum = a + b
    RETURN sum
END FUNCTION

NEW INT result = addNumbers ( 5 , 3 )
PRINTLN result // Displays: 8

Example: Function Returning Boolean

FUNCTION isEven ( INT number )
    NEW BOOL result = ( number % 2 ) == 0
    RETURN result
END FUNCTION

NEW BOOL check = isEven ( 4 )
PRINTLN check // Displays: TRUE

Function with Return Values

Example: Returning Integer

FUNCTION square ( INT n )
    NEW INT result = n * n
    RETURN result
END FUNCTION

NEW INT value = square ( 5 )
PRINTLN "Square: " .. value // Displays: Square: 25

Example: Returning Float

FUNCTION calculateArea ( FLOAT width , FLOAT height )
    NEW FLOAT area = width * height
    RETURN area
END FUNCTION

NEW FLOAT roomArea = calculateArea ( 10.5 , 8.0 )
PRINTLN "Area: " .. roomArea // Displays: Area: 84.0

Example: Returning String

FUNCTION getFullName ( STR firstName , STR lastName )
    NEW STR fullName = firstName .. " " .. lastName
    RETURN fullName
END FUNCTION

NEW STR name = getFullName ( "John" , "Doe" )
PRINTLN name // Displays: John Doe

Example: Returning Boolean

FUNCTION isAdult ( INT age )
    NEW BOOL adult = age >= 18
    RETURN adult
END FUNCTION

IF isAdult ( 25 )
    PRINTLN "Can vote"
ELSE
    PRINTLN "Cannot vote"
END IF
// Displays: Can vote

Temperature Conversion Functions

Example: Celsius to Fahrenheit

FUNCTION celsiusToFahrenheit ( FLOAT celsius )
    NEW FLOAT fahrenheit = 0.0
    SET fahrenheit = ( celsius * 9.0 / 5.0 ) + 32.0
    RETURN fahrenheit
END FUNCTION

NEW FLOAT tempC = 25.0
PRINTLN tempC .. " C = " .. celsiusToFahrenheit ( tempC ) .. " F"
// Displays: 25.0 C = 77.0 F

Example: Fahrenheit to Celsius

FUNCTION fahrenheitToCelsius ( FLOAT fahrenheit )
    NEW FLOAT celsius = 0.0
    SET celsius = ( fahrenheit - 32.0 ) * 5.0 / 9.0
    RETURN celsius
END FUNCTION

NEW FLOAT tempF = 77.0
PRINTLN tempF .. " F = " .. fahrenheitToCelsius ( tempF ) .. " C"
// Displays: 77.0 F = 25.0 C

Example: Complete Temperature Conversion Program

FUNCTION celsiusToFahrenheit ( FLOAT celsius )
    NEW FLOAT fahrenheit = 0.0
    SET fahrenheit = ( celsius * 9.0 / 5.0 ) + 32.0
    RETURN fahrenheit
END FUNCTION

FUNCTION fahrenheitToCelsius ( FLOAT fahrenheit )
    NEW FLOAT celsius = 0.0
    SET celsius = ( fahrenheit - 32.0 ) * 5.0 / 9.0
    RETURN celsius
END FUNCTION

NEW FLOAT tempC = 25.0
NEW FLOAT tempF = 77.0
PRINTLN "Temperature Conversions:"
PRINTLN tempC .. " C = " .. celsiusToFahrenheit ( tempC ) .. " F"
PRINTLN tempF .. " F = " .. fahrenheitToCelsius ( tempF ) .. " C"
// Displays: Temperature Conversions:
// Displays: 25.0 C = 77.0 F
// Displays: 77.0 F = 25.0 C

Local Scope

Variables created inside a function exist only within that function. They are destroyed when the function ends and cannot be accessed from outside the function.

Example: Local Variables

FUNCTION calculate ( INT x )
    NEW INT localVar = x * 2
    RETURN localVar
END FUNCTION

NEW INT result = calculate ( 5 )
PRINTLN result // Displays: 10
// PRINTLN localVar // Runtime error! localVar doesn't exist here

Example: Same Variable Name in Different Scopes

NEW INT value = 100

FUNCTION modifyValue ( INT n )
    NEW INT value = n * 2 // Different variable, local scope
    RETURN value
END FUNCTION

NEW INT result = modifyValue ( 10 )
PRINTLN "Function result: " .. result // Displays: Function result: 20
PRINTLN "Global value: " .. value // Displays: Global value: 100

Example: Parameters are Local

FUNCTION processNumber ( INT num )
    SET num = num + 10
    PRINTLN "Inside function: " .. num
    RETURN num
END FUNCTION

NEW INT original = 5
NEW INT processed = processNumber ( original )
PRINTLN "Original: " .. original // Displays: Original: 5
PRINTLN "Processed: " .. processed // Displays: Processed: 15

Functions Calling Other Functions

Example: Nested Function Calls

FUNCTION double ( INT n )
    NEW INT result = n * 2
    RETURN result
END FUNCTION

FUNCTION quadruple ( INT n )
    NEW INT doubled = double ( n )
    NEW INT result = double ( doubled )
    RETURN result
END FUNCTION

NEW INT value = quadruple ( 5 )
PRINTLN value // Displays: 20

Example: Helper Functions

FUNCTION isPositive ( INT n )
    NEW BOOL result = n > 0
    RETURN result
END FUNCTION

FUNCTION absoluteValue ( INT n )
    IF isPositive ( n )
        RETURN n
    ELSE
        RETURN n * -1
    END IF
END FUNCTION

NEW INT value = absoluteValue ( -15 )
PRINTLN value // Displays: 15

Functions with Conditionals

Example: Grading Function

FUNCTION getGrade ( INT score )
    NEW STR grade = ""
    IF score >= 90
        SET grade = "A"
    ELIF score >= 80
        SET grade = "B"
    ELIF score >= 70
        SET grade = "C"
    ELIF score >= 60
        SET grade = "D"
    ELSE
        SET grade = "F"
    END IF
    RETURN grade
END FUNCTION

NEW INT studentScore = 85
NEW STR letterGrade = getGrade ( studentScore )
PRINTLN "Grade: " .. letterGrade // Displays: Grade: B

Example: Max Function

FUNCTION max ( INT a , INT b )
    IF a > b
        RETURN a
    ELSE
        RETURN b
    END IF
END FUNCTION

NEW INT largest = max ( 15 , 23 )
PRINTLN "Max: " .. largest // Displays: Max: 23

Example: Sign Function

FUNCTION sign ( INT n )
    NEW STR result = ""
    IF n > 0
        SET result = "positive"
    ELIF n < 0
        SET result = "negative"
    ELSE
        SET result = "zero"
    END IF
    RETURN result
END FUNCTION

PRINTLN sign ( 10 ) // Displays: positive
PRINTLN sign ( -5 ) // Displays: negative
PRINTLN sign ( 0 ) // Displays: zero

Functions with Loops

Example: Factorial Function

FUNCTION factorial ( INT n )
    NEW INT result = 1
    NEW INT i = 1
    WHILE i <= n
        SET result = result * i
        SET i = i + 1
    END WHILE
    RETURN result
END FUNCTION

NEW INT fact5 = factorial ( 5 )
PRINTLN "5! = " .. fact5 // Displays: 5! = 120

Example: Sum Range Function

FUNCTION sumRange ( INT start , INT end )
    NEW INT sum = 0
    NEW INT i = start
    WHILE i <= end
        SET sum = sum + i
        SET i = i + 1
    END WHILE
    RETURN sum
END FUNCTION

NEW INT total = sumRange ( 1 , 10 )
PRINTLN "Sum 1-10: " .. total // Displays: Sum 1-10: 55

Example: Count Occurrences

FUNCTION countEven ( INT start , INT end )
    NEW INT count = 0
    NEW INT i = start
    WHILE i <= end
        IF i % 2 == 0
            SET count = count + 1
        END IF
        SET i = i + 1
    END WHILE
    RETURN count
END FUNCTION

NEW INT evenCount = countEven ( 1 , 20 )
PRINTLN "Even numbers: " .. evenCount // Displays: Even numbers: 10

Mathematical Functions

Example: Power Function

FUNCTION power ( INT base , INT exponent )
    NEW INT result = 1
    NEW INT i = 1
    WHILE i <= exponent
        SET result = result * base
        SET i = i + 1
    END WHILE
    RETURN result
END FUNCTION

NEW INT value = power ( 2 , 3 )
PRINTLN "2^3 = " .. value // Displays: 2^3 = 8

Example: Average Function

FUNCTION average ( FLOAT a , FLOAT b , FLOAT c )
    NEW FLOAT sum = a + b + c
    NEW FLOAT avg = sum / 3.0
    RETURN avg
END FUNCTION

NEW FLOAT result = average ( 10.0 , 20.0 , 30.0 )
PRINTLN "Average: " .. result // Displays: Average: 20.0

Example: Circle Area

FUNCTION circleArea ( FLOAT radius )
    NEW FLOAT pi = 3.14159
    NEW FLOAT area = pi * radius * radius
    RETURN area
END FUNCTION

NEW FLOAT r = 5.0
NEW FLOAT area = circleArea ( r )
PRINTLN "Area: " .. area // Displays: Area: 78.53975

String Processing Functions

Example: Repeat String

FUNCTION repeatString ( STR inputString , INT repeatTimes )
    NEW STR result = ""
    NEW INT i = 1
    WHILE i <= repeatTimes
        SET result = result .. inputString
        SET i = i + 1
    END WHILE
    RETURN result
END FUNCTION

NEW STR repeated = repeatString ( "Ha" , 3 )
PRINTLN repeated // Displays: HaHaHa

Example: Create Label

FUNCTION createLabel ( STR name , INT value )
    NEW STR label = name .. ": " .. value
    RETURN label
END FUNCTION

NEW STR output = createLabel ( "Score" , 95 )
PRINTLN output // Displays: Score: 95

Validation Functions

Example: In Range Check

FUNCTION inRange ( INT value , INT min , INT max )
    NEW BOOL result = ( value >= min ) && ( value <= max )
    RETURN result
END FUNCTION

IF inRange ( 50 , 1 , 100 )
    PRINTLN "In range"
ELSE
    PRINTLN "Out of range"
END IF
// Displays: In range

Example: Valid Age Check

FUNCTION isValidAge ( INT age )
    NEW BOOL valid = ( age >= 0 ) && ( age <= 120 )
    RETURN valid
END FUNCTION

NEW INT age = 25
IF isValidAge ( age )
    PRINTLN "Valid age"
ELSE
    PRINTLN "Invalid age"
END IF
// Displays: Valid age

Practical Applications

Example: Discount Calculator

FUNCTION calculateDiscount ( FLOAT price , FLOAT percent )
    NEW FLOAT discount = price * ( percent / 100.0 )
    RETURN discount
END FUNCTION

FUNCTION applyDiscount ( FLOAT price , FLOAT percent )
    NEW FLOAT discount = calculateDiscount ( price , percent )
    NEW FLOAT finalPrice = price - discount
    RETURN finalPrice
END FUNCTION

NEW FLOAT originalPrice = 100.0
NEW FLOAT finalPrice = applyDiscount ( originalPrice , 20.0 )
PRINTLN "Original: $" .. originalPrice
PRINTLN "Final: $" .. finalPrice
// Displays: Original: $100.0
// Displays: Final: $80.0

Example: Tax Calculator

FUNCTION calculateTax ( FLOAT amount , FLOAT rate )
    NEW FLOAT tax = amount * rate
    RETURN tax
END FUNCTION

FUNCTION getTotalWithTax ( FLOAT amount , FLOAT taxRate )
    NEW FLOAT tax = calculateTax ( amount , taxRate )
    NEW FLOAT total = amount + tax
    RETURN total
END FUNCTION

NEW FLOAT subtotal = 50.0
NEW FLOAT total = getTotalWithTax ( subtotal , 0.08 )
PRINTLN "Subtotal: $" .. subtotal
PRINTLN "Total: $" .. total
// Displays: Subtotal: $50.0
// Displays: Total: $54.0

Example: BMI Calculator

FUNCTION calculateBMI ( FLOAT weight , FLOAT height )
    NEW FLOAT bmi = weight / ( height * height )
    RETURN bmi
END FUNCTION

FUNCTION getBMICategory ( FLOAT bmi )
    NEW STR category = ""
    IF bmi < 18.5
        SET category = "Underweight"
    ELIF bmi < 25.0
        SET category = "Normal"
    ELIF bmi < 30.0
        SET category = "Overweight"
    ELSE
        SET category = "Obese"
    END IF
    RETURN category
END FUNCTION

NEW FLOAT weight = 70.0
NEW FLOAT height = 1.75
NEW FLOAT bmi = calculateBMI ( weight , height )
NEW STR category = getBMICategory ( bmi )
PRINTLN "BMI: " .. bmi
PRINTLN "Category: " .. category

Example: Fibonacci Function

FUNCTION fibonacci ( INT n )
    NEW INT a = 0
    NEW INT b = 1
    NEW INT temp = 0
    NEW INT count = 1
    
    IF n == 1
        RETURN a
    END IF
    
    WHILE count < n
        SET temp = a
        SET a = b
        SET b = temp + b
        SET count = count + 1
    END WHILE
    
    RETURN a
END FUNCTION

NEW INT fib10 = fibonacci ( 10 )
PRINTLN "10th Fibonacci: " .. fib10 // Displays: 10th Fibonacci: 34

Example: Prime Number Check

FUNCTION isPrime ( INT n )
    IF n <= 1
        RETURN FALSE
    END IF
    
    NEW INT i = 2
    WHILE i * i <= n
        IF n % i == 0
            RETURN FALSE
        END IF
        SET i = i + 1
    END WHILE
    
    RETURN TRUE
END FUNCTION

NEW INT number = 17
IF isPrime ( number )
    PRINTLN number .. " is prime"
ELSE
    PRINTLN number .. " is not prime"
END IF
// Displays: 17 is prime

Function Naming Best Practices

Example: Descriptive Names

// Good: Clear purpose
FUNCTION calculateCircleArea ( FLOAT radius )
    NEW FLOAT area = 3.14159 * radius * radius
    RETURN area
END FUNCTION

// Good: Action-oriented
FUNCTION convertToUppercase ( STR text )
    // Implementation would go here
    RETURN text
END FUNCTION

Important Notes

  • Functions must be defined before they are called in the code.
  • Function names are case-sensitive (myFunction and MyFunction are different).
  • Multiple parameters are separated by commas.
  • Variables created inside a function are local to that function.
  • The RETURN statement sends a value back to the caller.
  • The returned value's type must match the expected return type.
  • Functions can call other functions.
  • Parameters are passed by value (changes inside function don't affect original variables).
  • Every function must end with END FUNCTION.
  • Functions help organize code and reduce repetition.

Common Errors

Error: Missing END FUNCTION

FUNCTION add ( INT a , INT b )
    NEW INT sum = a + b
    RETURN sum
// Syntax error! Missing END FUNCTION

// Correct:
FUNCTION add ( INT a , INT b )
    NEW INT sum = a + b
    RETURN sum
END FUNCTION

Error: Missing Return Type Declaration

FUNCTION getValue ( )
    RETURN 42 // Return value will be typed based on what's returned
END FUNCTION

Error: Parameter Without Type

FUNCTION process ( value ) // Syntax error! TYPE Missing
    RETURN value
END FUNCTION

// Correct:
FUNCTION process ( INT value )
    RETURN value
END FUNCTION

Error: Calling Function Before Definition

NEW INT result = calculate ( 5 ) // Runtime error! Function not yet defined

FUNCTION calculate ( INT n )
    RETURN n * 2
END FUNCTION

// Correct: Define function first
FUNCTION calculate ( INT n )
    RETURN n * 2
END FUNCTION

NEW INT result = calculate ( 5 )

Error: Wrong Number of Parameters

FUNCTION add ( INT a , INT b )
    RETURN a + b
END FUNCTION

NEW INT result = add ( 5 ) // Runtime error! Missing parameter
// Correct:
NEW INT result = add ( 5 , 3 )

Error: Wrong Parameter Type

FUNCTION double ( INT n )
    RETURN n * 2
END FUNCTION

NEW INT result = double ( 5.5 ) // Type error! Expected INT, got FLOAT
// Correct:
NEW INT result = double ( 5 )

Error: Missing RETURN Statement

FUNCTION getValue ( )
    NEW INT x = 10
    // Runtime error! No RETURN statement
END FUNCTION

// Correct:
FUNCTION getValue ( )
    NEW INT x = 10
    RETURN x
END FUNCTION

Error: Accessing Local Variable Outside Function

FUNCTION calculate ( )
    NEW INT localValue = 100
    RETURN localValue
END FUNCTION

NEW INT result = calculate ( )
PRINTLN localValue // Runtime error! localValue doesn't exist here
// Correct:
PRINTLN result

Error: Mismatched Return Type

FUNCTION getText ( )
    RETURN 42 // Returns INT
END FUNCTION

NEW STR message = getText ( ) // Type error! Cannot assign INT to STR
// Correct:
FUNCTION getText ( )
    RETURN "Hello"
END FUNCTION

NEW STR message = getText ( )

Error: Duplicate Function Names

FUNCTION process ( INT n )
    RETURN n * 2
END FUNCTION

FUNCTION process ( INT n ) // Runtime error! Function already defined
    RETURN n * 3
END FUNCTION

// Correct: Use different names
FUNCTION double ( INT n )
    RETURN n * 2
END FUNCTION

FUNCTION triple ( INT n )
    RETURN n * 3
END FUNCTION