This directory contains example TargaScript programs that demonstrate various language features and capabilities. These examples are designed to be clear, well-documented, and easy to follow.
TargaScript provides a rich set of built-in functions for common operations:
print(...args)- Print values to standard outputprintf(format, ...args)- Print formatted values using format specifierstype(arg)- Return the type of a value as a stringrange(start, end)- Create an array with integers from start to end (inclusive)
toString(arg)- Convert a value to a stringtoInt(arg)- Convert a value to an integertoFloat(arg)- Convert a value to a float
abs(num)- Return the absolute value of a numbersqrt(num)- Return the square root of a numberpow(base, exponent)- Return base raised to the power of exponentround(num)- Round a number to the nearest integerfloor(num)- Round a number down to the nearest integerceil(num)- Round a number up to the nearest integermin(a, b)- Return the smaller of two numbersmax(a, b)- Return the larger of two numbersrandom()- Generate a random number between 0 and 1
now()- Return the current Unix timestamp (seconds since Jan 1, 1970)timeFormat(timestamp, format)- Format a Unix timestamp using the provided format string
TargaScript provides several loop constructs:
-
Collection-based loops - Iterate over arrays or objects:
repeat item in collection { // Code to execute for each item } -
Condition-based loops - Loop as long as a condition is true:
repeat condition { // Code to execute while condition is true } -
Range-based loops - Iterate over a numerical range:
repeat i in range(start, end) { // Code to execute for each number in the range } -
Loop Control Statements - Control the flow of loops:
break // Exit the loop immediately continue // Skip to the next iteration
TargaScript uses method-style dot notation for strings and arrays, which allows for more expressive and chainable operations:
.length- Get the length of a string, array, or hash
Strings support the following method-style operations:
str.length- Get the length of the stringstr.trim()- Remove whitespace from both endsstr.lower()- Convert to lowercasestr.upper()- Convert to uppercasestr.replace(old, new)- Replace all occurrences of 'old' with 'new'str.split(delimiter)- Split into an array of substrings
Example of string method chaining:
// Using method-style notation
print(" hello ".trim().upper()) // Prints "HELLO"
Arrays support the following method-style operations:
array.first()- Get the first elementarray.last()- Get the last elementarray.rest()- Get all elements except the firstarray.insert(value)- Insert a value at the endarray.join(separator)- Join into a string with the separatorarray.map(function)- Transform each elementarray.filter(function)- Filter elements by a conditionarray.reduce(function, initialValue)- Reduce to a single value
Example of array method chaining:
// Using method-style notation
let result = [1, 2, 3, 4, 5]
.filter(fn(x) { return x % 2 == 0 })
.map(fn(x) { return x * 2 })
.join(",")
// Result: "4,8"
Method-style notation is particularly useful for complex data transformations, making the code more readable and maintainable:
// Process an array of strings and join the results
let processed = ["hello", "WORLD", " TargaScript "]
.map(fn(word) { return word.trim().lower() })
.join(" ")
// Result: "hello world targascript"
// Parse and transform structured data
let entries = "NAME:John,AGE:30,CITY:New York"
.split(",")
.map(fn(entry) {
let parts = entry.split(":")
return {
"key": parts[0].lower(),
"value": parts[1].trim()
}
})
For comprehensive examples, see dot_notation.tg which demonstrates all available methods and various chaining patterns.
-
functions_demo.tg - Comprehensive demonstration of built-in functions
- Type conversion, type inspection, and properties
- Math functions
- Method-style string and array operations
-
dot_notation.tg - Demonstration of method-style dot notation syntax
- String methods (trim, lower, upper, replace, split)
- Array methods (join, map, filter, reduce)
- Method chaining for complex transformations
- Combining string and array methods
-
loops.tg - Comprehensive examples of loop constructs
- Collection-based loops, condition-based loops, and range-based loops
- Loop control with break and continue
- Nested loops and practical applications
-
logical_operators_comprehensive.tg - Complete exploration of logical operators
- Basic boolean operations
- Truthy/falsy values across different types
- Short-circuit evaluation and operator precedence
-
format_test.tg - Demonstrates printf and format specifiers
- Basic format specifiers for all data types
- Multiple values and expressions
- Advanced formatting techniques and practical examples
-
operators.tg - Demonstrates basic operators
- Arithmetic operations (+, -, *, /, %)
- Comparison operators (==, !=, <, >, <=, >=)
- Logical operators (&&, ||, !)
- String concatenation
-
string_operations.tg - String concatenation, manipulation, and formatting
- String creation and concatenation
- Method-style string manipulation
- String formatting techniques
-
array_transformations.tg - Working with arrays and transformations
- Array creation and manipulation
- Using array methods (map, filter, reduce)
- Practical array transformation examples
-
data_processor.tg - Practical data processing with method chaining
- Processing text data using method chains
- Filtering and transforming collections of objects
- Statistical analysis with chained operations
- Combining multiple transformations in a single chain
-
math_string_time.tg - Math calculations, string operations, and time functions
- Math operations and functions
- String manipulation techniques
- Date and time handling
-
fibonacci.tg - Multiple implementations of the Fibonacci sequence
- Recursive, iterative, and dynamic programming approaches
- Performance comparisons and optimization techniques
-
calculator.tg - A simple calculator implementation
- Basic arithmetic operations
- Scientific functions
- Formula calculations
-
prime_numbers.tg - Functions for working with prime numbers
- Prime number checking
- Prime number generation
- Prime factorization
-
todo_list.tg - A todo list application demonstrating state management
- Object-oriented programming style
- State management patterns
- CRUD operations (Create, Read, Update, Delete)
-
contacts_manager.tg - A contacts management application
- Contact creation and storage
- Searching and filtering contacts
- Contact modification and deletion
-
sorting.tg - Implementation of sorting algorithms
- Bubble sort implementation
- Algorithm benchmarking
-
function_scoping_test.tg - Test cases for function parameter scoping
- Demonstrates how function parameters shadow outer variables
- Shows scope isolation between function calls
- Tests nested function scoping behavior
-
if_scoping_test.tg - Test cases for block scoping in if statements
- Demonstrates variable shadowing in if blocks
- Shows block-level variable scope isolation
- Tests nested block scoping behavior
-
const_test.tg - Test cases for constant variable declarations
- Demonstrates using the
constkeyword for immutable variables - Shows how constants behave with different data types
- Tests reassignment protection for constants
- Demonstrates using the
To run any example, use:
go run main.go examples/filename.tg
For example:
go run main.go examples/functions_demo.tg
Feel free to modify these examples or create your own! TargaScript is designed to be intuitive and expressive, making it easy to experiment with different programming concepts.
If you create an interesting example, consider contributing it back to the main repository.