Nesta página
Biblioteca Padrão
Zolo inclui uma biblioteca padrão abrangente construída sobre o runtime Lua. Todas as funções estão disponíveis automaticamente sem importações.
Funções de String¶
Todas as funções de string estão no namespace string:
| Função | Descrição | Exemplo |
|---|---|---|
string.trim(s) |
Remover espaços em branco do início/fim | string.trim(" hi ") → "hi" |
string.trim_start(s) |
Remover espaços em branco do início | string.trim_start(" hi") → "hi" |
string.trim_end(s) |
Remover espaços em branco do fim | string.trim_end("hi ") → "hi" |
string.starts_with(s, prefix) |
Verificar se começa com prefixo | string.starts_with("hello", "he") → true |
string.ends_with(s, suffix) |
Verificar se termina com sufixo | string.ends_with("hello", "lo") → true |
string.contains(s, substr) |
Verificar se contém substring | string.contains("hello", "ell") → true |
string.split(s, sep) |
Dividir em array | string.split("a,b,c", ",") → ["a","b","c"] |
string.replace(s, old, new) |
Substituir ocorrências | string.replace("aa", "a", "b") → "bb" |
string.chars(s) |
Dividir em caracteres | string.chars("hi") → ["h","i"] |
string.pad_start(s, len, fill) |
Preencher no início | string.pad_start("42", 5, "0") → "00042" |
string.pad_end(s, len, fill) |
Preencher no fim | string.pad_end("hi", 5, ".") → "hi..." |
string.is_empty(s) |
Verificar se está vazia | string.is_empty("") → true |
Funções de Array¶
Todas as funções de array estão no namespace Array:
Criação e Operações Básicas¶
| Função | Descrição |
|---|---|
Array.new(...) |
Criar array a partir de argumentos |
Array.len(arr) |
Obter comprimento do array |
Array.push(arr, val) |
Adicionar elemento ao final |
Array.pop(arr) |
Remover e retornar o último elemento |
Array.shift(arr) |
Remover e retornar o primeiro elemento |
Array.unshift(arr, val) |
Adicionar elemento ao início |
Array.slice(arr, from, to) |
Extrair sub-array |
Array.concat(a, b) |
Concatenar dois arrays |
Array.reverse(arr) |
Inverter array |
Array.sort(arr, cmp?) |
Ordenar array (comparador opcional) |
Array.flat(arr) |
Achatar arrays aninhados |
Array.join(arr, sep) |
Juntar elementos em string |
Operações Funcionais¶
| Função | Descrição | Exemplo |
|---|---|---|
Array.map(arr, fn) |
Transformar cada elemento | Array.map([1,2,3], |x| x * 2) → [2,4,6] |
Array.filter(arr, fn) |
Manter elementos correspondentes | Array.filter([1,2,3,4], |x| x > 2) → [3,4] |
Array.reduce(arr, fn, init) |
Reduzir a um único valor | Array.reduce([1,2,3], |a,b| a + b, 0) → 6 |
Array.each(arr, fn) |
Executar para cada elemento | Array.each(items, |x| print(x)) |
Array.find(arr, fn) |
Encontrar o primeiro correspondente | Array.find([1,2,3], |x| x > 1) → 2 |
Array.find_index(arr, fn) |
Encontrar índice do primeiro correspondente | Array.find_index([1,2,3], |x| x > 1) → 1 |
Array.contains(arr, val) |
Verificar se elemento existe | Array.contains([1,2,3], 2) → true |
Array.any(arr, fn) |
Verificar se algum corresponde | Array.any([1,2,3], |x| x > 2) → true |
Array.all(arr, fn) |
Verificar se todos correspondem | Array.all([1,2,3], |x| x > 0) → true |
Array.zip(a, b) |
Parear elementos de dois arrays | Array.zip([1,2], ["a","b"]) → [(1,"a"),(2,"b")] |
Array.enumerate(arr) |
Adicionar índices | Array.enumerate(["a","b"]) → [(0,"a"),(1,"b")] |
Usando com Pipe¶
let result = [1, 2, 3, 4, 5]
|> Array.map(|x| x * x)
|> Array.filter(|x| x > 5)
|> Array.reduce(|a, b| a + b, 0)
// result = 9 + 16 + 25 = 50Funções de Map¶
Todas as funções de map estão no namespace Map:
| Função | Descrição |
|---|---|
Map.new() |
Criar map vazio |
Map.from(tbl) |
Criar a partir de tabela |
Map.set(m, key, val) |
Definir par chave-valor |
Map.get(m, key) |
Obter valor pela chave |
Map.has(m, key) |
Verificar se a chave existe |
Map.remove(m, key) |
Remover par chave-valor |
Map.keys(m) |
Obter todas as chaves como array |
Map.values(m) |
Obter todos os valores como array |
Map.entries(m) |
Obter todos os pares chave-valor |
Map.len(m) |
Obter número de entradas |
Map.each(m, fn) |
Iterar sobre entradas |
Map.clear(m) |
Remover todas as entradas |
Exemplo¶
let scores = Map.new()
Map.set(scores, "Alice", 95)
Map.set(scores, "Bob", 87)
print(Map.get(scores, "Alice")) // 95
print(Map.has(scores, "Carol")) // false
Map.each(scores, |key, val| {
print("{key}: {val}")
})Funções de Set¶
Todas as funções de set estão no namespace Set:
| Função | Descrição |
|---|---|
Set.new() |
Criar set vazio |
Set.from(arr) |
Criar a partir de array |
Set.add(s, val) |
Adicionar elemento |
Set.has(s, val) |
Verificar pertinência |
Set.remove(s, val) |
Remover elemento |
Set.len(s) |
Obter tamanho |
Set.to_array(s) |
Converter para array |
Set.union(a, b) |
União de dois sets |
Set.intersect(a, b) |
Interseção de dois sets |
Set.difference(a, b) |
Elementos em a mas não em b |
Set.each(s, fn) |
Iterar sobre elementos |
Exemplo¶
let fruits = Set.from(["apple", "banana", "cherry"])
Set.add(fruits, "date")
print(Set.has(fruits, "apple")) // true
print(Set.len(fruits)) // 4
let tropical = Set.from(["banana", "mango", "papaya"])
let common = Set.intersect(fruits, tropical) // {"banana"}Funções de Option¶
O tipo Option representa um valor que pode ou não existir:
| Função | Descrição |
|---|---|
Option.Some(val) |
Criar Some com um valor |
Option.None() |
Criar None (sem valor) |
Option.is_some(opt) |
Verificar se tem um valor |
Option.is_none(opt) |
Verificar se está vazio |
Option.unwrap(opt) |
Extrair valor (erro se None) |
Option.unwrap_or(opt, default) |
Extrair valor ou usar padrão |
Option.map(opt, fn) |
Transformar o valor se presente |
Option.and_then(opt, fn) |
Flat map (encadear opcionais) |
Option.or_else(opt, fn) |
Fornecer alternativa se None |
Option.from(val) |
Criar a partir de valor (nil → None) |
Exemplo¶
let maybe = Option.Some(42)
let nothing = Option.None()
print(Option.is_some(maybe)) // true
print(Option.unwrap_or(nothing, 0)) // 0
let doubled = Option.map(maybe, |x| x * 2)
print(Option.unwrap(doubled)) // 84Funções de Result¶
O tipo Result representa sucesso ou falha:
| Função | Descrição |
|---|---|
Result.Ok(val) |
Criar sucesso |
Result.Err(err) |
Criar erro |
Result.is_ok(r) |
Verificar se é sucesso |
Result.is_err(r) |
Verificar se é erro |
Result.unwrap(r) |
Extrair valor (erro se Err) |
Result.unwrap_or(r, default) |
Extrair valor ou usar padrão |
Result.unwrap_err(r) |
Extrair valor do erro |
Result.map(r, fn) |
Transformar valor de sucesso |
Result.map_err(r, fn) |
Transformar valor de erro |
Result.and_then(r, fn) |
Encadear results |
Result.or_else(r, fn) |
Tratar caso de erro |
Result.from_pcall(fn, ...) |
Criar a partir de chamada protegida |
Exemplo¶
fn divide(a: int, b: int) -> Result<int, str> {
if b == 0 {
Result.Err("division by zero")
} else {
Result.Ok(a / b)
}
}
let result = divide(10, 2)
print(Result.unwrap(result)) // 5
let bad = divide(10, 0)
print(Result.is_err(bad)) // true
print(Result.unwrap_or(bad, -1)) // -1Funções de Iterator¶
Iteradores preguiçosos para processamento eficiente de dados:
| Função | Descrição |
|---|---|
Iter.from(arr) |
Criar a partir de array |
Iter.range(start, stop, step?) |
Criar iterador de intervalo |
Iter.map(iter, fn) |
Map preguiçoso |
Iter.filter(iter, fn) |
Filter preguiçoso |
Iter.take(iter, n) |
Tomar os primeiros n elementos |
Iter.skip(iter, n) |
Pular os primeiros n elementos |
Iter.zip(a, b) |
Zipar dois iteradores |
Iter.enumerate(iter) |
Adicionar índices |
Iter.fold(iter, init, fn) |
Reduzir a um único valor |
Iter.collect(iter) |
Coletar em array |
Iter.each(iter, fn) |
Executar para cada elemento |
Iter.count(iter) |
Contar elementos |
Iter.flat_map(iter, fn) |
Flat map preguiçoso |
Iter.chain(a, b) |
Concatenar iteradores |
Iter.find(iter, fn) |
Encontrar o primeiro correspondente |
Iter.any(iter, fn) |
Verificar se algum corresponde |
Iter.all(iter, fn) |
Verificar se todos correspondem |
Exemplo¶
let result = Iter.range(0, 100)
|> Iter.map(|x| x * x)
|> Iter.filter(|x| x % 2 == 0)
|> Iter.take(5)
|> Iter.collect()
// [0, 4, 16, 36, 64]Funções Embutidas¶
Estas funções estão disponíveis globalmente:
| Função | Descrição |
|---|---|
print(...) |
Imprimir no stdout |
type(val) |
Obter tipo como string |
tostring(val) |
Converter para string |
tonumber(val) |
Converter para número |
assert_eq(a, b, msg?) |
Afirmar igualdade |
assert_ne(a, b, msg?) |
Afirmar desigualdade |
Suporte a BigInt¶
Zolo tem suporte nativo a BigInt para inteiros arbitrariamente grandes:
let big = BigInt.from("99999999999999999999999")
let zero = BigInt.zero()
let one = BigInt.one()