Language GuideNative Functions

Native Functions

KodiScript provides a rich set of built-in functions with consistent names and behaviour across its SDKs.

Method-call syntax: Any function whose first argument is the value it operates on can also be called as a method, and calls can be chained. value.method(args) is equivalent to method(value, args). For example "hello".toUpperCase(), [3, 1, 2].sort().join(","), or nums.map(fn(x){ x * 2 }). See Functions.

String Functions

FunctionSignatureDescription
toStringtoString(value)Converts any value to its string representation
toNumbertoNumber(value)Converts a value to a number
lengthlength(str)Returns the length of a string
substringsubstring(str, start, [end])Extracts a portion of a string
toUpperCasetoUpperCase(str)Converts string to uppercase
toLowerCasetoLowerCase(str)Converts string to lowercase
trimtrim(str)Removes whitespace from both ends
splitsplit(str, separator)Splits a string into an array
joinjoin(array, separator)Joins array elements into a string
replacereplace(str, old, new)Replaces all occurrences of a substring
containscontains(str, substr)Checks if string contains a substring
startsWithstartsWith(str, prefix)Checks if string starts with prefix
endsWithendsWith(str, suffix)Checks if string ends with suffix
indexOfindexOf(str, substr)Returns index of first occurrence (-1 if not found)
repeatrepeat(str, count)Repeats a string count times
padLeftpadLeft(str, len, [pad])Pads the start of a string to len characters
padRightpadRight(str, len, [pad])Pads the end of a string to len characters

Examples

let text = "  Hello, World!  "
print(trim(text))           // "Hello, World!"
print(toUpperCase("hello")) // "HELLO"
print(split("a,b,c", ","))  // ["a", "b", "c"]
print(contains("hello", "ell")) // true
print(repeat("ab", 3))      // "ababab"
print(padLeft("7", 3, "0")) // "007"

Math Functions

FunctionSignatureDescription
absabs(n)Returns absolute value
floorfloor(n)Rounds down to nearest integer
ceilceil(n)Rounds up to nearest integer
roundround(n)Rounds to nearest integer
minmin(a, b, ...)Returns the smallest value
maxmax(a, b, ...)Returns the largest value
powpow(base, exp)Returns base raised to the power of exp
sqrtsqrt(n)Returns square root
sinsin(n)Returns sine (n in radians)
coscos(n)Returns cosine (n in radians)
tantan(n)Returns tangent (n in radians)
loglog(n)Returns natural logarithm
log10log10(n)Returns base-10 logarithm
expexp(n)Returns e raised to the power of n

Examples

print(abs(-5))        // 5
print(floor(3.7))     // 3
print(ceil(3.2))      // 4
print(pow(2, 8))      // 256
print(min(5, 3, 8))   // 3

Random Functions

FunctionSignatureDescription
randomrandom()Returns a random number between 0 and 1
randomIntrandomInt(min, max)Returns a random integer in range [min, max]
randomUUIDrandomUUID()Returns a random UUID v4 string

Examples

print(random())           // 0.742...
print(randomInt(1, 100))  // 42
print(randomUUID())       // "550e8400-e29b-41d4-a716-446655440000"

Type Functions

FunctionSignatureDescription
typeOftypeOf(value)Returns type as string: “null”, “string”, “number”, “boolean”, “array”, “object”
isNullisNull(value)Returns true if value is null
isNumberisNumber(value)Returns true if value is a number
isStringisString(value)Returns true if value is a string
isBoolisBool(value)Returns true if value is a boolean

Examples

print(typeOf(42))       // "number"
print(typeOf("hello"))  // "string"
print(isNull(null))     // true
print(isNumber(3.14))   // true

Array Functions

FunctionSignatureDescription
sizesize(array)Returns the number of elements
firstfirst(array)Returns the first element or null
lastlast(array)Returns the last element or null
reversereverse(array)Returns a reversed copy of the array
sliceslice(array, start, [end])Returns a portion of the array
sortsort(array, ["asc"|"desc"])Returns a sorted copy (ascending by default)
sortBysortBy(array, field, ["asc"|"desc"])Sorts array of objects by a field

Examples

let nums = [3, 1, 4, 1, 5]
print(size(nums))       // 5
print(first(nums))      // 3
print(last(nums))       // 5
print(sort(nums))       // [1, 1, 3, 4, 5]
print(sort(nums, "desc")) // [5, 4, 3, 1, 1]
print(reverse(nums))    // [5, 1, 4, 1, 3]

Functional Helpers

Higher-order functions that take a callback. Each also works with method-call syntax (e.g. nums.map(...)).

FunctionSignatureDescription
mapmap(array, fn)Transforms each element, returns a new array
filterfilter(array, fn)Keeps elements where fn returns truthy
reducereduce(array, fn, initial)Folds the array into a single value
findfind(array, fn)Returns the first matching element (or null)
findIndexfindIndex(array, fn)Returns the index of the first match (-1 if none)
somesome(array, fn)true if any element matches
everyevery(array, fn)true if all elements match
flatMapflatMap(array, fn)Maps each element to an array, then flattens one level

Examples

let nums = [1, 2, 3, 4, 5]
print(nums.map(fn(x){ x * 2 }))          // [2, 4, 6, 8, 10]
print(nums.filter(fn(x){ x % 2 == 0 }))  // [2, 4]
print(reduce(nums, fn(acc, x){ acc + x }, 0))  // 15
print(find(nums, fn(x){ x > 3 }))        // 4
print(some(nums, fn(x){ x > 4 }))        // true
print(every(nums, fn(x){ x > 0 }))       // true
print(flatMap([1, 2], fn(x){ [x, x * 10] }))   // [1, 10, 2, 20]

Collection Utilities

FunctionSignatureDescription
rangerange(end) / range(start, end)Builds [start, end) as an array
sumsum(array)Sum of all numbers
avgavg(array)Average of all numbers
uniqueunique(array)Removes duplicate values
flattenflatten(array)Flattens nested arrays one level deep
pushpush(array, item, ...)Returns a new array with items appended (non-mutating)
concatconcat(arr1, arr2, ...)Concatenates multiple arrays

Examples

print(range(5))              // [0, 1, 2, 3, 4]
print(range(2, 5))           // [2, 3, 4]
print(sum([1, 2, 3, 4, 5]))  // 15
print(avg([1, 2, 3, 4, 5]))  // 3
print(unique([1, 1, 2, 3, 3]))     // [1, 2, 3]
print(flatten([[1, 2], [3, 4]]))   // [1, 2, 3, 4]
print(push([1, 2], 3))       // [1, 2, 3]
print(concat([1, 2], [3, 4]))      // [1, 2, 3, 4]

Object Functions

FunctionSignatureDescription
keyskeys(object)Array of keys, sorted alphabetically
valuesvalues(object)Array of values, ordered by sorted key
entriesentries(object)Array of [key, value] pairs, ordered by sorted key
hashas(object, key) / has(array, value)Checks key presence (objects) or membership (arrays)

Examples

let obj = {z: 1, a: 2, m: 3}
print(keys(obj))       // [a, m, z]
print(values(obj))     // [2, 3, 1]
print(entries(obj))    // [[a, 2], [m, 3], [z, 1]]
print(has(obj, "a"))   // true
print(has([1, 2, 3], 3))   // true

Parsing Functions

FunctionSignatureDescription
parseIntparseInt(str)Parses a value into an integer (truncates)
parseFloatparseFloat(str)Parses a value into a floating-point number

Examples

print(parseInt("99"))     // 99
print(parseInt("3.9"))    // 3
print(parseFloat("3.14")) // 3.14

Regex Functions

FunctionSignatureDescription
regexMatchregexMatch(str, pattern)Returns true if the pattern matches anywhere in the string
regexReplaceregexReplace(str, pattern, replacement)Replaces all matches of the pattern

Examples

print(regexMatch("order-123", "[0-9]+"))       // true
print(regexReplace("a1b2c3", "[0-9]", "#"))     // "a#b#c#"

JSON Functions

FunctionSignatureDescription
jsonParsejsonParse(str)Parses a JSON string into an object/array
jsonStringifyjsonStringify(value)Converts a value to JSON string

Examples

let obj = jsonParse('{"name": "Alice", "age": 30}')
print(obj.name)  // "Alice"
 
let arr = [1, 2, 3]
print(jsonStringify(arr))  // "[1,2,3]"

Encoding Functions

Base64

FunctionSignatureDescription
base64Encodebase64Encode(str)Encodes string to Base64
base64Decodebase64Decode(str)Decodes Base64 string

URL

FunctionSignatureDescription
urlEncodeurlEncode(str)URL-encodes a string
urlDecodeurlDecode(str)Decodes a URL-encoded string

Examples

print(base64Encode("Hello"))  // "SGVsbG8="
print(base64Decode("SGVsbG8="))  // "Hello"
 
print(urlEncode("hello world"))  // "hello+world"
print(urlDecode("hello+world"))  // "hello world"

Date/Time Functions

FunctionSignatureDescription
nownow()Returns current timestamp in milliseconds
datedate()Returns current date as string (YYYY-MM-DD)
timetime()Returns current time as string (HH:MM:SS)
datetimedatetime()Returns current ISO 8601 datetime string
timestamptimestamp([dateStr])Parses date string to timestamp, or returns current if no arg
formatDateformatDate(ts, [format])Formats timestamp with pattern (YYYY, MM, DD, HH, mm, ss)
yearyear([ts])Extracts year from timestamp (or current)
monthmonth([ts])Extracts month (1-12) from timestamp
dayday([ts])Extracts day of month from timestamp
hourhour([ts])Extracts hour (0-23) from timestamp
minuteminute([ts])Extracts minute (0-59) from timestamp
secondsecond([ts])Extracts second (0-59) from timestamp
dayOfWeekdayOfWeek([ts])Returns day of week (0=Sunday, 6=Saturday)
addDaysaddDays(ts, days)Adds days to timestamp
addHoursaddHours(ts, hours)Adds hours to timestamp
diffDaysdiffDays(ts1, ts2)Returns difference in days between two timestamps

Examples

// Current date/time
print(now())       // 1735638735000 (timestamp)
print(date())      // "2024-12-31"
print(time())      // "09:32:15"
print(datetime())  // "2024-12-31T09:32:15.000Z"
 
// Parse and format
let ts = timestamp("2024-12-25")
print(formatDate(ts, "DD/MM/YYYY"))  // "25/12/2024"
 
// Extract components
print(year())      // 2024
print(month())     // 12
print(day())       // 31
print(dayOfWeek()) // 2 (Tuesday)
 
// Date arithmetic
let tomorrow = addDays(now(), 1)
let nextWeek = addDays(now(), 7)
let diff = diffDays(ts, now())  // Days since Christmas

Crypto/Hash Functions

FunctionSignatureDescription
md5md5(str)Returns MD5 hash as hex string
sha1sha1(str)Returns SHA-1 hash as hex string
sha256sha256(str)Returns SHA-256 hash as hex string

Examples

print(md5("hello"))     // "5d41402abc4b2a76b9719d911017c592"
print(sha256("hello"))  // "2cf24dba5fb0a30e26e83b2ac5b9e29e..."

Output Function

FunctionSignatureDescription
printprint(value, ...)Outputs values (captured by interpreter)

The print function is special - it doesn’t return a value but captures output that can be retrieved from the interpreter after execution.

print("Hello, World!")
print("The answer is:", 42)