### Control Flow and Loops Source: https://logos-lang.vercel.app/llms.txt Examples of conditional logic using if/else and switch statements, alongside iteration using for loops and for-in loops. ```Logos if x > 10 { print("big") } else { print("small") } for i, v in arr { print("${i}: ${v}") } ``` -------------------------------- ### Time Module Source: https://logos-lang.vercel.app/llms.txt Provides functions for getting the current time, formatting timestamps, and pausing execution. ```APIDOC ## Time Module ### Description Functions for retrieving current time information, formatting timestamps, and controlling execution flow with sleep. ### Functions - **timeNow()**: Returns the current Unix timestamp in seconds (integer). - **timeMs()**: Returns the current Unix timestamp in milliseconds (integer). - **timeStr()**: Returns the current time as a string in the format "HH:MM:SS" (e.g., "15:04:05"). - **dateStr()**: Returns the current date as a string in the format "YYYY-MM-DD" (e.g., "2026-03-16"). - **dateTimeStr()**: Returns the current date and time as a string (e.g., "2026-03-16 15:04:05"). - **timeFormat(ts, fmt)**: Formats a Unix timestamp `ts` using the Go time layout string `fmt`. - **sleep(ms)**: Pauses the execution for the specified number of milliseconds `ms`. ``` -------------------------------- ### Logos Type and Inspection Functions Source: https://logos-lang.vercel.app/llms.txt Offers utilities for inspecting the type and properties of variables. Functions include retrieving the type name of a value, getting the length of strings or arrays, listing table keys and values, and checking for the existence of a key in a table. ```Logos type(val) len(val) keys(t) values(t) has(t, key) ``` -------------------------------- ### Logos HTTP Client Functions Source: https://logos-lang.vercel.app/llms.txt Enables making HTTP requests to external resources. Supports GET, POST, PUT, PATCH, and DELETE methods. These functions return a result table containing the response body and status code, or an error object if the request fails. ```Logos httpGet(url, headers?) httpPost(url, body, headers?) httpPut(url, body, headers?) httpPatch(url, body, headers?) httpDelete(url, headers?) ``` -------------------------------- ### Embedding Logos in Go Source: https://logos-lang.vercel.app/llms.txt Demonstrates how to create and configure Logos virtual machines (VMs) in Go, register Go functions for use in Logos scripts, set and retrieve variables between Go and Logos, and run Logos scripts. It also outlines the supported type conversions between Go and Logos. ```go import "github.com/codetesla51/logos/logos" // Create VM (all capabilities enabled) vm := logos.New() // Create sandboxed VM vm := logos.NewWithConfig(logos.SandboxConfig{ AllowFileIO: false, AllowNetwork: false, AllowShell: false, AllowExit: false, }) // Register a Go function callable from Logos vm.Register("greet", func(args ...logos.Object) logos.Object { name := args[0].(*logos.String).Value return &logos.String{Value: "Hello, " + name} }) // Set a variable in the Logos environment vm.SetVar("count", 42) vm.SetVar("config", map[string]interface{}{"port": 8080}) // Run a script string err := vm.Run(`print(greet("World"))`) // Get a variable back as a Go value result := vm.GetVar("count") // returns interface{} // Call a Logos function from Go result, err := vm.Call("myFunction", arg1, arg2) ``` -------------------------------- ### Regex Module Source: https://logos-lang.vercel.app/llms.txt Provides functions for working with regular expressions using Go's regexp syntax. Patterns should use backticks for raw strings. ```APIDOC ## Regex Module ### Description Functions for regular expression matching, finding, replacing, splitting, and capturing groups. Uses Go regexp syntax. Patterns use backticks for raw strings. ### Functions - **reMatch(pattern, text)**: Returns `true` if `pattern` matches `text`. - **reFind(pattern, text)**: Returns the first match of `pattern` in `text` or `null` if no match is found. - **reFindAll(pattern, text)**: Returns an array of all matches of `pattern` in `text`. - **reReplace(pattern, text, repl)**: Replaces all occurrences of `pattern` in `text` with `repl`. - **reSplit(pattern, text)**: Splits `text` by the `pattern`. - **reGroups(pattern, text)**: Returns an array of capture groups from matching `pattern` against `text`. ``` -------------------------------- ### System / OS Module Source: https://logos-lang.vercel.app/llms.txt Provides functions for interacting with the operating system and environment. Note: These functions are disabled in the sandbox environment. ```APIDOC ## System / OS Module ### Description Functions for interacting with the operating system, environment variables, and command-line arguments. These functions are disabled in the sandbox. ### Functions - **osname()**: Returns the operating system name as a string ("linux", "darwin", or "windows"). - **pwd()**: Returns the current working directory as a string. - **cd(path)**: Changes the current working directory to the specified `path`. - **env(key)**: Returns the value of the environment variable `key` as a string, or `null` if it does not exist. - **setenv(key, val)**: Sets the environment variable `key` to the value `val`. - **args()**: Returns the command-line arguments as an array of strings. Returns an empty array if no arguments are provided. - **exit(code?)**: Exits the process. An optional integer `code` can be provided (defaults to 0). - **shell(cmd)**: Executes a shell command string `cmd` and returns a result table containing the `output` string. - **run(cmd, args...)**: Executes a command `cmd` with separate arguments `args...`. Returns a result table. ``` -------------------------------- ### std/testing Module Source: https://logos-lang.vercel.app/llms.txt Provides functions for writing and running tests. ```APIDOC ## std/testing Module ### Description Provides utilities for creating and executing unit tests, including assertion functions and test suite management. ### Functions - **assert(name, got, expected)**: Asserts that the `got` value is equal to the `expected` value, reporting a failure with the given `name` if they differ. - **suite(name, func)**: Defines a test suite named `name` and executes the provided function `func` within it. - **summary()**: Prints a summary of the test results. ``` -------------------------------- ### std/path Module Source: https://logos-lang.vercel.app/llms.txt Provides functions for manipulating file paths. ```APIDOC ## std/path Module ### Description Functions for common file path manipulations, including joining, extracting components, and checking path properties. ### Functions - **pathJoin(arr)**: Joins an array of path parts `arr` into a single path string using the system's separator (typically '/'). - **pathBase(path)**: Returns the filename portion of the given `path`. - **pathDir(path)**: Returns the directory portion of the given `path`. - **pathExt(path)**: Returns the file extension of the `path` (e.g., ".lgs"). - **pathIsAbs(path)**: Returns `true` if the `path` is an absolute path. - **pathClean(path)**: Cleans up the given `path`, removing redundant separators and `.` or `..` components. - **pathExists(path)**: Returns `true` if the file or directory at the given `path` exists. - **pathWithoutExt(path)**: Returns the `path` without its file extension. ``` -------------------------------- ### std/math Module Source: https://logos-lang.vercel.app/llms.txt Provides mathematical functions for calculations. ```APIDOC ## std/math Module ### Description Provides a collection of mathematical functions, including Fibonacci, factorial, statistical measures, and number theory operations. ### Functions - **mathFib(n)**: Returns the nth Fibonacci number. - **mathFactorial(n)**: Returns the factorial of `n` (n!). - **mathMean(arr)**: Calculates the arithmetic mean (average) of the numbers in the array `arr`. - **mathMedian(arr)**: Calculates the median value of the numbers in the array `arr`. - **mathMode(arr)**: Returns the mode (most frequently occurring value) of the numbers in the array `arr`. - **mathClamp(n, min, max)**: Constrains the number `n` to be within the range [`min`, `max`]. - **mathLerp(a, b, t)**: Performs linear interpolation between `a` and `b` using the factor `t`. - **mathIsPrime(n)**: Returns `true` if the number `n` is a prime number. - **mathGcd(a, b)**: Calculates the greatest common divisor (GCD) of two numbers `a` and `b`. - **mathLcm(a, b)**: Calculates the least common multiple (LCM) of two numbers `a` and `b`. ``` -------------------------------- ### std/time Module (Datetime) Source: https://logos-lang.vercel.app/llms.txt Provides advanced functions for working with datetime objects, including formatting, comparison, and arithmetic. ```APIDOC ## std/time Module (Datetime) ### Description Advanced functions for manipulating datetime objects, allowing for precise time-based operations and comparisons. All functions operate on datetime objects, which are tables containing `timestamp`, `str`, `date`, and `time` fields. ### Functions - **datetimeNow()**: Returns the current datetime object. - **datetimeFromTimestamp(ts)**: Creates a datetime object from a Unix timestamp `ts`. - **datetimeFormat(dt, fmt)**: Formats a datetime object `dt` using the Go time layout string `fmt`. - **datetimeIsAfter(dt1, dt2)**: Returns `true` if `dt1` is after `dt2`. - **datetimeIsBefore(dt1, dt2)**: Returns `true` if `dt1` is before `dt2`. - **datetimeIsEqual(dt1, dt2)**: Returns `true` if `dt1` is equal to `dt2`. - **datetimeDiff(dt1, dt2, unit)**: Calculates the difference between `dt1` and `dt2` in the specified `unit` (e.g., "seconds", "minutes", "hours", "days"). - **datetimeAdd(dt, amount, unit)**: Adds `amount` of time in the specified `unit` to the datetime object `dt`. - **datetimeSubtract(dt, n, u)**: Subtracts `n` units of time specified by `u` from the datetime object `dt`. - **datetimeToStr(dt)**: Converts a datetime object `dt` to its string representation. ``` -------------------------------- ### std/log Module Source: https://logos-lang.vercel.app/llms.txt Provides functions for logging messages at different severity levels. ```APIDOC ## std/log Module ### Description Functions for emitting log messages with different severity levels, useful for debugging and monitoring application behavior. ### Functions - **logDebug(msg)**: Logs a message `msg` at the debug level (typically displayed in white). - **logInfo(msg)**: Logs a message `msg` at the info level (typically displayed in green). - **logWarn(msg)**: Logs a message `msg` at the warning level (typically displayed in yellow). - **logError(msg)**: Logs a message `msg` at the error level (typically displayed in red). ``` -------------------------------- ### Logos Common Patterns: File Operations Source: https://logos-lang.vercel.app/llms.txt Illustrates how to perform file operations in Logos, specifically reading a file and parsing its content as JSON. This is a fundamental pattern for configuration loading or data ingestion. ```logos let content = try fileRead("config.json") let config = try parseJson(content) print(config.port) ``` -------------------------------- ### Logos Common Patterns: Error Handling with try Source: https://logos-lang.vercel.app/llms.txt Shows how to implement robust error handling in Logos using the `try` expression. This pattern allows for cleaner handling of operations that might fail, such as network requests or JSON parsing. ```logos fn safeFetch(url) { let res = try httpGet(url) let data = try parseJson(res.value.body) return data } ``` -------------------------------- ### std/string Module Source: https://logos-lang.vercel.app/llms.txt Provides utility functions for string manipulation. ```APIDOC ## std/string Module ### Description Utility functions for common string operations such as capitalization, reversal, palindrome checking, and padding. ### Functions - **strCapitalize(str)**: Capitalizes the first letter of the string `str`. - **strReverse(str)**: Reverses the characters in the string `str`. - **strIsPalindrome(str)**: Returns `true` if the string `str` is a palindrome. - **strIsEmpty(str)**: Returns `true` if the string `str` is empty or contains only whitespace. - **strCount(str, sub)**: Counts the number of non-overlapping occurrences of the substring `sub` in the string `str`. - **strRepeat(str, n)**: Repeats the string `str` `n` times. - **strPadStart(str, length, char)**: Pads the beginning of the string `str` with `char` until it reaches the specified `length`. - **strPadEnd(str, length, char)**: Pads the end of the string `str` with `char` until it reaches the specified `length`. ``` -------------------------------- ### Data Structures: Arrays and Tables Source: https://logos-lang.vercel.app/llms.txt Shows the syntax for defining arrays and tables (maps). Tables support both dot notation and bracket access for key-value retrieval. ```Logos let arr = [1, 2, 3, "four", true] let user = table{ name: "Uthman", age: 20 } user.name = "New Name" let val = user["name"] ``` -------------------------------- ### Logos Common Patterns: CLI Arguments Source: https://logos-lang.vercel.app/llms.txt Explains how to access command-line arguments passed to a Logos script. The `args()` function provides access to these arguments, excluding the binary and script paths. ```logos // Running: lgs script.lgs --name "Alice" --verbose" let cliArgs = args() print(cliArgs[0]) // "--name" (NOT binary path!) print(cliArgs[1]) // "Alice" // Binary and script paths are already removed ``` -------------------------------- ### Pipe Operator and Error Handling Source: https://logos-lang.vercel.app/llms.txt Demonstrates the pipe operator for chaining function calls and the try expression for propagating errors from result tables. ```Logos let result = nums |> filter(fn(x) -> x % 2 == 0) |> map(fn(x) -> x * 2) fn fetchData() { let res = try httpGet("https://api.example.com/data") return res.value.body } ``` -------------------------------- ### Concurrency with Spawn Source: https://logos-lang.vercel.app/llms.txt Utilizes the spawn block to execute statements concurrently and the spawn for-in loop to process array items in parallel. ```Logos spawn { print("task 1") print("task 2") } spawn for item in jobs { process(item) } ``` -------------------------------- ### Logos File I/O Operations Source: https://logos-lang.vercel.app/llms.txt Provides functions for interacting with the file system. These include reading, writing, appending, deleting files, creating directories, and listing directory contents. Most functions return a result table indicating success or failure, except for `fileExists`. ```Logos fileRead(path) fileWrite(path, content) fileAppend(path, content) fileDelete(path) fileMkdir(path) fileReadDir(path) fileGlob(pattern) fileCopy(src, dst) fileMove(src, dst) fileExists(path) ``` -------------------------------- ### Variable Declaration and Constants Source: https://logos-lang.vercel.app/llms.txt Demonstrates how to declare mutable variables and immutable constants in Logos. Reassigning a constant will trigger a runtime error. ```Logos let x = 10 let name = "Uthman" const PI = 3.14159 // PI = 3.14 // This would throw an error ``` -------------------------------- ### Logos Math Functions Source: https://logos-lang.vercel.app/llms.txt Includes a suite of mathematical functions for common operations. Supports absolute value, square root, power, floor, ceiling, rounding, min/max, and random number generation. Also provides access to the value of Pi. ```Logos mathAbs(n) mathSqrt(n) mathPow(base, exp) mathFloor(n) mathCeil(n) mathRound(n) mathMin(a, b) mathMax(a, b) mathRandom() mathRandomInt(min, max) mathPi() ``` -------------------------------- ### Logos Common Patterns: HTTP, JSON, and Piping Source: https://logos-lang.vercel.app/llms.txt Illustrates a common pattern in Logos for handling HTTP requests, parsing JSON responses, and filtering/mapping the data using pipes. This pattern is useful for data retrieval and transformation tasks. ```logos let users = try httpGet("https://api.example.com/users") |> try parseJson |> filter(fn(u) -> u.active) |> map(fn(u) -> u.name) print(users) ``` -------------------------------- ### Logos I/O Functions Source: https://logos-lang.vercel.app/llms.txt Provides functions for interacting with the standard input and output streams. These include printing with and without newlines, reading user input, prompting for input, creating confirmation prompts, displaying numbered menus, and clearing the terminal screen. ```Logos print(args...) printn(args...) input(prompt?) prompt(msg) confirm(msg) select(msg, options[]) clear() ``` -------------------------------- ### Function Definitions and Closures Source: https://logos-lang.vercel.app/llms.txt Covers standard function definitions, anonymous functions, arrow functions for single expressions, and closure creation. ```Logos fn greet(name) { return "Hello " + name } let double = fn(x) -> x * 2 fn makeCounter() { let count = 0 return fn() { count += 1 return count } } ``` -------------------------------- ### std/array Module Source: https://logos-lang.vercel.app/llms.txt Provides utility functions for manipulating arrays. ```APIDOC ## std/array Module ### Description Utility functions for common array operations like mapping, filtering, reducing, and more. ### Functions - **map(arr, func)**: Transforms each element of the array `arr` using the function `func`. - **filter(arr, func)**: Returns a new array containing only the elements of `arr` for which the function `func` returns true. - **reduce(arr, func, initial)**: Combines all elements of the array `arr` into a single value using the function `func`, starting with an `initial` value. - **unique(arr)**: Returns a new array with duplicate elements removed from `arr`. - **flat(arr)**: Flattens a nested array `arr` into a single-level array. - **sum(arr)**: Calculates the sum of all numbers in the array `arr`. - **min(arr)**: Returns the smallest number in the array `arr`. - **max(arr)**: Returns the largest number in the array `arr`. - **indexOf(arr, val)**: Returns the index of the first occurrence of `val` in the array `arr`, or -1 if not found. - **containsAll(arr, items)**: Returns `true` if all elements in the `items` array are present in the array `arr`. ``` -------------------------------- ### Logos Common Patterns: String Interpolation Source: https://logos-lang.vercel.app/llms.txt Demonstrates string interpolation in Logos, allowing variables to be embedded directly within string literals. This simplifies the creation of dynamic strings. ```logos let name = "Alice" let age = 28 print("${name} is ${age} years old") ``` -------------------------------- ### Logos String Manipulation Functions Source: https://logos-lang.vercel.app/llms.txt Provides a comprehensive set of functions for manipulating strings. Includes operations like changing case, trimming whitespace, replacing substrings, splitting and joining strings, checking for containment, and formatted string output. ```Logos upper(s) lower(s) trim(s) replace(s, old, new) split(s, sep) join(arr, sep) contains(val, sub) startsWith(s, prefix) endsWith(s, suffix) indexOf(s, sub) repeat(s, n) slice(val, s, e) format(tmpl, args...) ``` -------------------------------- ### std/type Module Source: https://logos-lang.vercel.app/llms.txt Provides functions for checking the type of a value. ```APIDOC ## std/type Module ### Description Utility functions to determine the data type of a given value, ensuring correct data handling and logic. ### Functions - **isNull(val)**: Returns `true` if the value `val` is null. - **isString(val)**: Returns `true` if the value `val` is a string. - **isInt(val)**: Returns `true` if the value `val` is an integer. - **isFloat(val)**: Returns `true` if the value `val` is a floating-point number. - **isBool(val)**: Returns `true` if the value `val` is a boolean. - **isArray(val)**: Returns `true` if the value `val` is an array. - **isTable(val)**: Returns `true` if the value `val` is a table (map/dictionary). - **isNumber(val)**: Returns `true` if the value `val` is either an integer or a float. - **isCallable(val)**: Returns `true` if the value `val` is a function. ``` -------------------------------- ### Logos Array Manipulation Functions Source: https://logos-lang.vercel.app/llms.txt Offers utilities for working with arrays (lists). Functions include adding elements, removing elements, accessing first/last elements, reversing, sorting, slicing, checking for containment, and generating numeric ranges. ```Logos push(arr, val) pop(arr) first(arr) last(arr) tail(arr) prepend(arr, val) reverse(arr) sort(arr) slice(arr, s, e) contains(arr, val) range(start, end, step?) ``` -------------------------------- ### Logos JSON Parsing and Serialization Source: https://logos-lang.vercel.app/llms.txt Enables conversion between Logos values and JSON strings. `parseJson` converts a JSON string to a Logos value, while `toJson` and `prettyJson` convert Logos values to JSON strings, with `prettyJson` providing formatted output. These functions return a result object indicating success or failure. ```Logos parseJson(str) tooJson(val) prettyJson(val) ``` -------------------------------- ### Logos Color Output Functions Source: https://logos-lang.vercel.app/llms.txt Enables colored text output in the terminal using ANSI escape codes. Each function takes a string and returns the string wrapped in the appropriate color or style codes. These functions are useful for highlighting specific information in console applications. ```Logos colorRed(str) colorGreen(str) colorYellow(str) colorBlue(str) colorMagenta(str) colorCyan(str) colorWhite(str) colorBold(str) ``` -------------------------------- ### Logos Type Conversion Functions Source: https://logos-lang.vercel.app/llms.txt Facilitates the conversion of values between different data types. Supports conversion to string, integer, and float, with aliases for common conversions. These functions are essential for data manipulation and ensuring type compatibility. ```Logos str(val) int(val) float(val) toStr(val) toInt(val) toFloat(val) toBool(val) ``` -------------------------------- ### Logos Table Manipulation Functions Source: https://logos-lang.vercel.app/llms.txt Provides functions for interacting with tables (key-value maps). Includes retrieving keys and values, checking for key existence, deleting entries, and merging tables. These are fundamental for data structuring. ```Logos keys(t) values(t) has(t, key) tableDelete(t, key) merge(t1, t2) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.