Fix use statement in programs

This commit is contained in:
aNNiMON 2023-09-09 15:52:32 +03:00 committed by Victor Melnik
parent 59f8c4109e
commit 6d0886316c
101 changed files with 202 additions and 226 deletions

View File

@ -71,7 +71,7 @@ fizzbuzz()
Operate data in functional style. Operate data in functional style.
```scala ```scala
use ["std", "functional"] use std, functional
nums = [1,2,3,4,5,6,7,8,9,10] nums = [1,2,3,4,5,6,7,8,9,10]
nums = filter(nums, def(x) = x % 2 == 0) nums = filter(nums, def(x) = x % 2 == 0)
@ -93,7 +93,7 @@ println "Sum: " + stream(range(1, 11))
Why not? Why not?
```scala ```scala
use ["std", "types", "math"] use std, types, math
def `..`(a, b) = range(a, b) def `..`(a, b) = range(a, b)
def `**`(a, b) = int(pow(a, b)) def `**`(a, b) = int(pow(a, b))
@ -107,13 +107,11 @@ for y : 1 .. 10 {
Easy async HTTP requests with `http` module. Easy async HTTP requests with `http` module.
```scala ```scala
use "std" use std, http, functional
use "http"
use "functional"
// GET request // GET request
http("https://api.github.com/events", def(r) { http("https://api.github.com/events", def(r) {
use "json" use json
events = jsondecode(r) events = jsondecode(r)
println events[0] println events[0]
}) })

View File

@ -50,14 +50,14 @@
desc_ru: возвращает значение `a`, если оно не пустое, иначе возвращается значение `b` desc_ru: возвращает значение `a`, если оно не пустое, иначе возвращается значение `b`
since: 1.4.0 since: 1.4.0
example: |- example: |-
use "std" use std
user = {"name": "", "lastname": "Doe"} user = {"name": "", "lastname": "Doe"}
name = default(user.name, "Unknown") name = default(user.name, "Unknown")
lastname = default(user.lastname, "Unknown") lastname = default(user.lastname, "Unknown")
println name + " " + lastname // Unknown Doe println name + " " + lastname // Unknown Doe
example_ru: |- example_ru: |-
use "std" use std
user = {"name": "", "lastname": "Иванов"} user = {"name": "", "lastname": "Иванов"}
name = default(user.name, "Имя неизвестно") name = default(user.name, "Имя неизвестно")
@ -68,12 +68,12 @@
desc: "prints values to console, separate them by space and puts newline at the end. Takes variable number of arguments" desc: "prints values to console, separate them by space and puts newline at the end. Takes variable number of arguments"
desc_ru: "выводит значения в консоль, разделяя их пробелом, а потом ставит перенос строки. Может принимать переменное значение аргументов" desc_ru: "выводит значения в консоль, разделяя их пробелом, а потом ставит перенос строки. Может принимать переменное значение аргументов"
example: |- example: |-
use "std" use std
echo(1, "abc") // prints "1 abc" to console echo(1, "abc") // prints "1 abc" to console
echo(1, 2, 3, 4, 5, "a", "b") // prints "1 2 3 4 5 a b" echo(1, 2, 3, 4, 5, "a", "b") // prints "1 2 3 4 5 a b"
example_ru: |- example_ru: |-
use "std" use std
echo(1, "abc") // выведет строку "1 abc" в консоль echo(1, "abc") // выведет строку "1 abc" в консоль
echo(1, 2, 3, 4, 5, "a", "b") // выведет строку "1 2 3 4 5 a b" в консоль" echo(1, 2, 3, 4, 5, "a", "b") // выведет строку "1 2 3 4 5 a b" в консоль"
@ -103,7 +103,7 @@
desc: "creates array with `size`.\n`newarray(x)` - creates 1D array, `newarray(x,y)` - creates 2D array" desc: "creates array with `size`.\n`newarray(x)` - creates 1D array, `newarray(x,y)` - creates 2D array"
desc_ru: "оздаёт массив с размером size. Если указать 1 аргумент - создаётся одномерный массив, если 2 аргумента - двухмерный и т.д" desc_ru: "оздаёт массив с размером size. Если указать 1 аргумент - создаётся одномерный массив, если 2 аргумента - двухмерный и т.д"
example: |- example: |-
use "std" use std
println newarray(4) // [0, 0, 0, 0] println newarray(4) // [0, 0, 0, 0]
println newarray(2, 3) // [[0, 0, 0], [0, 0, 0]] println newarray(2, 3) // [[0, 0, 0], [0, 0, 0]]
@ -136,7 +136,7 @@
`range(from, to)` - создаёт промежуток от `from` до `to` (не включительно) с шагом 1 `range(from, to)` - создаёт промежуток от `from` до `to` (не включительно) с шагом 1
`range(from, to, step)` - создаёт промежуток от `from` до `to` (не включительно) с шагом `step` `range(from, to, step)` - создаёт промежуток от `from` до `to` (не включительно) с шагом `step`
example: |- example: |-
use "std" use std
println range(3) // [0, 1, 2] println range(3) // [0, 1, 2]
r = range(-5, 0) // [-5, -4, -3, -2, -1] r = range(-5, 0) // [-5, -4, -3, -2, -1]
@ -175,7 +175,7 @@
desc: "splits string `str` with regular expression `regex` into array. `limit` parameter affects the length of resulting array" desc: "splits string `str` with regular expression `regex` into array. `limit` parameter affects the length of resulting array"
desc_ru: "разделяет строку `str` по шаблону `regex` и помещает элементы в массив. Если указан параметр `limit`, то будет произведено не более limit разбиений, соответственно размер результирующего массива будет ограничен этим значением limit" desc_ru: "разделяет строку `str` по шаблону `regex` и помещает элементы в массив. Если указан параметр `limit`, то будет произведено не более limit разбиений, соответственно размер результирующего массива будет ограничен этим значением limit"
example: |- example: |-
use "std" use std
println split("a5b5c5d5e", "5") // ["a", "b", "c", "d", "e"] println split("a5b5c5d5e", "5") // ["a", "b", "c", "d", "e"]
println split("a5b5c5d5e", "5", 3) // ["a", "b", "c5d5e"] println split("a5b5c5d5e", "5", 3) // ["a", "b", "c5d5e"]
@ -194,7 +194,7 @@
desc_ru: обрезает начальные пробелы, сопровождаемые `marginPrefix` в каждой строке, и удаляет первую и последнюю строки, если они пустые desc_ru: обрезает начальные пробелы, сопровождаемые `marginPrefix` в каждой строке, и удаляет первую и последнюю строки, если они пустые
since: 1.5.0 since: 1.5.0
example: |- example: |-
use "std" use std
println " println "
|123 |123
@ -205,7 +205,7 @@
desc: "returns string from `startIndex` to `endIndex` or to end of string if `endIndex` is not set" desc: "returns string from `startIndex` to `endIndex` or to end of string if `endIndex` is not set"
desc_ru: "обрезает строку `str`, начиная от символа после позиции `startIndex` и по `endIndex`. Если `endIndex` не указан, обрезается до конца строки" desc_ru: "обрезает строку `str`, начиная от символа после позиции `startIndex` и по `endIndex`. Если `endIndex` не указан, обрезается до конца строки"
example: |- example: |-
use "std" use std
println substring("abcde", 1) // bcde println substring("abcde", 1) // bcde
println substring("abcde", 2, 4) // cd println substring("abcde", 2, 4) // cd
@ -214,7 +214,7 @@
desc: calls an asynchronous function synchronously desc: calls an asynchronous function synchronously
desc_ru: делает асинхронный вызов синхронным desc_ru: делает асинхронный вызов синхронным
example: |- example: |-
use ["std", "http"] use std, http
url = "https://whatthecommit.com/index.txt" url = "https://whatthecommit.com/index.txt"
result = sync(def(ret) { result = sync(def(ret) {
@ -231,7 +231,7 @@
`args` - 0 или более аргументов, которые необходимо передать в функцию func `args` - 0 или более аргументов, которые необходимо передать в функцию func
example: |- example: |-
use "std" use std
thread(def() { thread(def() {
println "New Thread" println "New Thread"
@ -252,7 +252,7 @@
desc: "converts char code to string" desc: "converts char code to string"
desc_ru: "переводит код символа в строку" desc_ru: "переводит код символа в строку"
example: |- example: |-
use "std" use std
println toChar(48) // "0" println toChar(48) // "0"
- name: toHexString - name: toHexString
@ -276,14 +276,14 @@
desc: suppress any error in `unsafeFunction` and returns the result of the `catchFunction` if any error occurs desc: suppress any error in `unsafeFunction` and returns the result of the `catchFunction` if any error occurs
desc_ru: подавляет любые ошибки в `unsafeFunction` и возрвщает результат функции `catchFunction`, если была ошибка desc_ru: подавляет любые ошибки в `unsafeFunction` и возрвщает результат функции `catchFunction`, если была ошибка
example: |- example: |-
use "std" use std
println try(def() = "success") // success println try(def() = "success") // success
println try(def() = try + 2) // -1 println try(def() = try + 2) // -1
println try(def() = try(), def(type, message) = sprintf("Error handled:\ntype: %s\nmessage: %s", type, message)) println try(def() = try(), def(type, message) = sprintf("Error handled:\ntype: %s\nmessage: %s", type, message))
println try(def() = try(), 42) // 42 println try(def() = try(), 42) // 42
example_ru: |- example_ru: |-
use "std" use std
println try(def() = "успех") // успех println try(def() = "успех") // успех
println try(def() = try + 2) // -1 println try(def() = try + 2) // -1
@ -356,7 +356,7 @@
desc: "converts value to number if possible" desc: "converts value to number if possible"
desc_ru: "преобразует значение к числу, если это возможно" desc_ru: "преобразует значение к числу, если это возможно"
example: |- example: |-
use "types" use types
println typeof(number("2.3")) // 1 (NUMBER) println typeof(number("2.3")) // 1 (NUMBER)
- -
@ -370,7 +370,7 @@
desc: "converts value to string" desc: "converts value to string"
desc_ru: "преобразует значение в строку" desc_ru: "преобразует значение в строку"
example: |- example: |-
use "types" use types
println typeof(string(1)) // 2 (STRING) println typeof(string(1)) // 2 (STRING)
- -
@ -379,7 +379,7 @@
desc: "returns the type of value" desc: "returns the type of value"
desc_ru: "возвращает тип переданного значения" desc_ru: "возвращает тип переданного значения"
example: |- example: |-
use "types" use types
println typeof(1) // 1 (NUMBER) println typeof(1) // 1 (NUMBER)
println typeof("text") // 2 (STRING) println typeof("text") // 2 (STRING)
@ -436,7 +436,7 @@
desc: "returns the ceiling of `x`" desc: "returns the ceiling of `x`"
desc_ru: "округляет вещественное число в большую сторону" desc_ru: "округляет вещественное число в большую сторону"
example: |- example: |-
use "math" use math
ceil(6.4) // 7 ceil(6.4) // 7
- -
@ -470,7 +470,7 @@
desc: "returns floor of `x`" desc: "returns floor of `x`"
desc_ru: "округляет вещественное число в меньшую сторону" desc_ru: "округляет вещественное число в меньшую сторону"
example: |- example: |-
use "math" use math
floor(3.8) // 3 floor(3.8) // 3
- -
@ -677,7 +677,7 @@
desc: formats date by given format and returns string desc: formats date by given format and returns string
desc_ru: форматирует дату в указанном формате и возвращает строку desc_ru: форматирует дату в указанном формате и возвращает строку
example: |- example: |-
use "date" use date
d = newDate(2016, 4, 8) d = newDate(2016, 4, 8)
println formatDate(d, newFormat("yyyy/MM/dd")) // "2016/05/08" println formatDate(d, newFormat("yyyy/MM/dd")) // "2016/05/08"
@ -687,7 +687,7 @@
desc: parses date from string by given pattern. Returns DateValue desc: parses date from string by given pattern. Returns DateValue
desc_ru: парсит дату из строки в указанном шаблоне. Возвращает DateValue desc_ru: парсит дату из строки в указанном шаблоне. Возвращает DateValue
example: |- example: |-
use "date" use date
println parseDate("2016/05/08", newFormat("yyyy/MM/dd")) println parseDate("2016/05/08", newFormat("yyyy/MM/dd"))
- -
@ -795,12 +795,12 @@
Возвращает дескриптор файла, который необходим для остальных функций. Возвращает дескриптор файла, который необходим для остальных функций.
example: |- example: |-
use "files" use files
f1 = fopen("text.txt") // opens file text.txt for read in text mode f1 = fopen("text.txt") // opens file text.txt for read in text mode
f2 = fopen("E:/1.dat", "rbwb") // opens file 1.dat on drive E for binary read and write" f2 = fopen("E:/1.dat", "rbwb") // opens file 1.dat on drive E for binary read and write"
example_ru: |- example_ru: |-
use "files" use files
f1 = fopen("text.txt") // открывает файл text.txt для текстового чтения f1 = fopen("text.txt") // открывает файл text.txt для текстового чтения
f2 = fopen("E:/1.dat", "rbwb") // открывает файл 1.dat на диске E для бинарного чтения и записи" f2 = fopen("E:/1.dat", "rbwb") // открывает файл 1.dat на диске E для бинарного чтения и записи"
@ -835,12 +835,12 @@
desc: "returns array with filenames in given directory.\n\n f - directory descriptor" desc: "returns array with filenames in given directory.\n\n f - directory descriptor"
desc_ru: "возвращает массив с именами файлов в указанной директории.\n\n f - дескриптор папки" desc_ru: "возвращает массив с именами файлов в указанной директории.\n\n f - дескриптор папки"
example: |- example: |-
use "files" use files
f1 = fopen("E:/examples", "") // opens directory examples for getting information f1 = fopen("E:/examples", "") // opens directory examples for getting information
list = listFiles(f1) // gets array with filenames in directory list = listFiles(f1) // gets array with filenames in directory
example_ru: |- example_ru: |-
use "files" use files
f1 = fopen("E:/examples", "") // открыть папку examples для получения информации f1 = fopen("E:/examples", "") // открыть папку examples для получения информации
list = listFiles(f1) // получить массив с именами файлов в этой папке list = listFiles(f1) // получить массив с именами файлов в этой папке
@ -860,7 +860,7 @@
desc: "reads all bytes from file. Returns array with bytes" desc: "reads all bytes from file. Returns array with bytes"
desc_ru: "чтение всех байт файла. Возвращает массив байт файла" desc_ru: "чтение всех байт файла. Возвращает массив байт файла"
example: |- example: |-
use ["std", "files"] use std, files
f1 = fopen("file.bin", "rb") f1 = fopen("file.bin", "rb")
array = readAllBytes(f1) array = readAllBytes(f1)
@ -881,7 +881,7 @@
desc: "reads `length` bytes of file `f` and stores to `array` starting from `offset+1` byte. Returns number of read bytes" desc: "reads `length` bytes of file `f` and stores to `array` starting from `offset+1` byte. Returns number of read bytes"
desc_ru: "чтение заданного количества байт в массив `array`. Возвращает число прочитанных байт. \nЕсли offset и length не указаны, то читается количество байт равное длине массива. \nЕсли offset и length указаны, то читается length байт в массив array, начиная с `offset+1` байта" desc_ru: "чтение заданного количества байт в массив `array`. Возвращает число прочитанных байт. \nЕсли offset и length не указаны, то читается количество байт равное длине массива. \nЕсли offset и length указаны, то читается length байт в массив array, начиная с `offset+1` байта"
example: |- example: |-
use "files" use files
f1 = fopen("file.bin", "rb") // file.bin must contain more than 5000 bytes f1 = fopen("file.bin", "rb") // file.bin must contain more than 5000 bytes
array = newarray(2048) array = newarray(2048)
@ -889,7 +889,7 @@
readCount = readBytes(f1, array, 10) // reads 2048 bytes starting from 11 byte readCount = readBytes(f1, array, 10) // reads 2048 bytes starting from 11 byte
readCount = readBytes(f1, array, 20, 10) // reads 10 bytes, starting from 21 byte readCount = readBytes(f1, array, 20, 10) // reads 10 bytes, starting from 21 byte
example_ru: |- example_ru: |-
use "files" use files
f1 = fopen("file.bin", "rb") // file.bin должен иметь больше 5000 байтов f1 = fopen("file.bin", "rb") // file.bin должен иметь больше 5000 байтов
array = newarray(2048) array = newarray(2048)
@ -947,7 +947,7 @@
desc: "renames (or moves) file" desc: "renames (or moves) file"
desc_ru: "переименование (или перемещение) файла" desc_ru: "переименование (или перемещение) файла"
example: |- example: |-
use "files" use files
f1 = fopen("C:/file1", "i") f1 = fopen("C:/file1", "i")
f2 = fopen("E:/file2", "i") f2 = fopen("E:/file2", "i")
@ -1103,7 +1103,7 @@
- `content_length` - Content-Length - `content_length` - Content-Length
- `content_type` - Content-Type - `content_type` - Content-Type
example: |- example: |-
use "http" use http
http("http://jsonplaceholder.typicode.com/users", "POST", {"name": "OwnLang", "versionCode": 10}, def(v) { http("http://jsonplaceholder.typicode.com/users", "POST", {"name": "OwnLang", "versionCode": 10}, def(v) {
println "Added: " + v println "Added: " + v
}) })
@ -1112,7 +1112,7 @@
desc: "downloads content by url as bytes array" desc: "downloads content by url as bytes array"
desc_ru: "получает содержимое по указанному адресу в виде массива байт" desc_ru: "получает содержимое по указанному адресу в виде массива байт"
example: |- example: |-
use ["http", "files"] use http, files
bytes = download("http://url") bytes = download("http://url")
f = fopen("file", "wb") f = fopen("file", "wb")
writeBytes(f, bytes) writeBytes(f, bytes)
@ -1297,7 +1297,7 @@
desc: 'downloads file from `downloadUrl` to `filePath`' desc: 'downloads file from `downloadUrl` to `filePath`'
desc_ru: 'скачивает файл по адресу `downloadUrl` и сохраняет в `filePath`' desc_ru: 'скачивает файл по адресу `downloadUrl` и сохраняет в `filePath`'
example: |- example: |-
use ["downloader", "std"] use downloader, std
MBYTES = 1048576.0 // 1024*1024 MBYTES = 1048576.0 // 1024*1024
url = "http://www.ovh.net/files/10Mb.dat" url = "http://www.ovh.net/files/10Mb.dat"
@ -1343,7 +1343,7 @@
desc: "converts data to json string" desc: "converts data to json string"
desc_ru: "преобразует переданные данные в строку в формате json" desc_ru: "преобразует переданные данные в строку в формате json"
example: |- example: |-
use "json" use json
print jsondecode("{\"key1\":1,\"key2\":[1,2,3],\"key3\":\"text\"}") // {key2=[1, 2, 3], key3=text, key1=1} print jsondecode("{\"key1\":1,\"key2\":[1,2,3],\"key3\":\"text\"}") // {key2=[1, 2, 3], key3=text, key1=1}
- -
name: "jsonencode" name: "jsonencode"
@ -1351,7 +1351,7 @@
desc: "converts string to data" desc: "converts string to data"
desc_ru: "преобразует строку в формате json в данные" desc_ru: "преобразует строку в формате json в данные"
example: |- example: |-
use "json" use json
data = { data = {
"key1": 1, "key1": 1,
"key2": [1, 2, 3], "key2": [1, 2, 3],
@ -1391,13 +1391,13 @@
`mapper` используется для задания имени конечного файла внутри архива, а также для фильтрации. Если в mapper вернуть пустую строку, то файл будет пропущен. `mapper` используется для задания имени конечного файла внутри архива, а также для фильтрации. Если в mapper вернуть пустую строку, то файл будет пропущен.
Возвращает количество заархивированных файлов, либо -1, если создать архив не удалось. Возвращает количество заархивированных файлов, либо -1, если создать архив не удалось.
example: |- example: |-
use "zip" use zip
// Zip all files in directory // Zip all files in directory
zip("/tmp/dir", "/tmp/1.zip") zip("/tmp/dir", "/tmp/1.zip")
// Zip .txt files // Zip .txt files
zip("/tmp/dir", "/tmp/2.zip", def(p) = p.endsWith(".txt") ? p : "") zip("/tmp/dir", "/tmp/2.zip", def(p) = p.endsWith(".txt") ? p : "")
example_ru: |- example_ru: |-
use "zip" use zip
// Архивировать все файлы в директории // Архивировать все файлы в директории
zip("/tmp/dir", "/tmp/1.zip") zip("/tmp/dir", "/tmp/1.zip")
// Архивировать .txt файлы // Архивировать .txt файлы
@ -1418,7 +1418,7 @@
Если `input` — ассоциативный массив, то архивируются файлы и папки перечисленные в ключах, а именами внутри архива будут служить значения. Если `input` — ассоциативный массив, то архивируются файлы и папки перечисленные в ключах, а именами внутри архива будут служить значения.
Возвращает количество заархивированных файлов, либо -1, если создать архив не удалось. Возвращает количество заархивированных файлов, либо -1, если создать архив не удалось.
example: |- example: |-
use "zip" use zip
zipFiles("/tmp/dir/file.txt", "/tmp/1.zip") zipFiles("/tmp/dir/file.txt", "/tmp/1.zip")
zipFiles(["/tmp/dir/file.txt", "/tmp/dir/readme.md"], "/tmp/2.zip") zipFiles(["/tmp/dir/file.txt", "/tmp/dir/readme.md"], "/tmp/2.zip")
zipFiles({"/tmp/dir/file.txt" : "docs/1.md", "/tmp/dir/readme.md" : "docs/2.md"}, "/tmp/3.zip") zipFiles({"/tmp/dir/file.txt" : "docs/1.md", "/tmp/dir/readme.md" : "docs/2.md"}, "/tmp/3.zip")
@ -1434,13 +1434,13 @@
`mapper` используется для задания имени конечного файла, а также для фильтрации. Если в mapper вернуть пустую строку, то файл будет пропущен. `mapper` используется для задания имени конечного файла, а также для фильтрации. Если в mapper вернуть пустую строку, то файл будет пропущен.
Возвращает количество разархивированных файлов, либо -1, если разархивировать архив не удалось. Возвращает количество разархивированных файлов, либо -1, если разархивировать архив не удалось.
example: |- example: |-
use "zip" use zip
// Unzip all files in directory // Unzip all files in directory
unzip("/tmp/1.zip", "/tmp/dir") unzip("/tmp/1.zip", "/tmp/dir")
// Unzip .txt files // Unzip .txt files
unzip("/tmp/2.zip", "/tmp/dir", def(p) = p.endsWith(".txt") ? p : "") unzip("/tmp/2.zip", "/tmp/dir", def(p) = p.endsWith(".txt") ? p : "")
example_ru: |- example_ru: |-
use "zip" use zip
// Распаковать все файлы в директории // Распаковать все файлы в директории
unzip("/tmp/1.zip", "/tmp/dir") unzip("/tmp/1.zip", "/tmp/dir")
// Распаковать .txt файлы // Распаковать .txt файлы
@ -1461,7 +1461,7 @@
Если `output` — ассоциативный массив, то разархивируются файлы перечисленные в ключах, а именами файлов будут служить значения. Если `output` — ассоциативный массив, то разархивируются файлы перечисленные в ключах, а именами файлов будут служить значения.
Возвращает количество разархивированных файлов, либо -1, если разархивировать архив не удалось. Возвращает количество разархивированных файлов, либо -1, если разархивировать архив не удалось.
example: |- example: |-
use "zip" use zip
unzipFiles("/tmp/1.zip", "file.txt") unzipFiles("/tmp/1.zip", "file.txt")
unzipFiles("/tmp/2.zip", ["file.txt", "readme.md"]) unzipFiles("/tmp/2.zip", ["file.txt", "readme.md"])
unzipFiles("/tmp/3.zip", {"docs/1.md" : "/tmp/dir/file.txt", "docs/2.md" : "/tmp/dir/readme.md"}) unzipFiles("/tmp/3.zip", {"docs/1.md" : "/tmp/dir/file.txt", "docs/2.md" : "/tmp/dir/readme.md"})
@ -1487,7 +1487,7 @@
создаёт gzip архив с файлом `inputFile` и сохраняет в `outputFile`. создаёт gzip архив с файлом `inputFile` и сохраняет в `outputFile`.
Возвращает 1 если компрессия завершилась успешно, и -1 в противном случае. Возвращает 1 если компрессия завершилась успешно, и -1 в противном случае.
example: |- example: |-
use "gzip" use gzip
gzip("/tmp/readme.md", "/tmp/readme.md.gz") gzip("/tmp/readme.md", "/tmp/readme.md.gz")
- -
name: gzipBytes name: gzipBytes
@ -1495,7 +1495,7 @@
desc: returns gzip-compressed input bytes. desc: returns gzip-compressed input bytes.
desc_ru: возвращает сжатый в gzip массив байт. desc_ru: возвращает сжатый в gzip массив байт.
example: |- example: |-
use "gzip" use gzip
bytes = gzipBytes([0, 119, 87, 80/* ... */]) bytes = gzipBytes([0, 119, 87, 80/* ... */])
- -
name: ungzip name: ungzip
@ -1507,7 +1507,7 @@
распаковывает gzip архив в файл `outputFile`. распаковывает gzip архив в файл `outputFile`.
Возвращает 1 если операция завершилась успешно, и -1 в противном случае. Возвращает 1 если операция завершилась успешно, и -1 в противном случае.
example: |- example: |-
use "gzip" use gzip
gzip("/tmp/readme.md.gz", "/tmp/readme.md") gzip("/tmp/readme.md.gz", "/tmp/readme.md")
- -
name: ungzipBytes name: ungzipBytes
@ -1515,7 +1515,7 @@
desc: returns uncompressed bytes. desc: returns uncompressed bytes.
desc_ru: возвращает распакованный gzip массив байт. desc_ru: возвращает распакованный gzip массив байт.
example: |- example: |-
use "gzip" use gzip
bytes = ungzipBytes([0, 119, 87, 80/* ... */]) bytes = ungzipBytes([0, 119, 87, 80/* ... */])
- name: functional - name: functional
scope: "both" scope: "both"
@ -1539,7 +1539,7 @@
desc: "combines functions" desc: "combines functions"
desc_ru: "комбинирует функции (композиция)" desc_ru: "комбинирует функции (композиция)"
example: |- example: |-
use "functional" use functional
def f1() = 2 def f1() = 2
def f2(a) = a*2 def f2(a) = a*2
@ -1551,7 +1551,7 @@
f = def() = f3(f2(f1())) f = def() = f3(f2(f1()))
println f() // 1 println f() // 1
example_ru: |- example_ru: |-
use "functional" use functional
def f1() = 2 def f1() = 2
def f2(a) = a*2 def f2(a) = a*2
@ -1571,7 +1571,7 @@
desc: "filters array or object.\n\n`predicate` is a function which takes one argument for arrays or two arguments for objects" desc: "filters array or object.\n\n`predicate` is a function which takes one argument for arrays or two arguments for objects"
desc_ru: "фильтрует массив или объект и возвращает массив только с теми элементами, которые удовлетворяют предикату `predicate`.\n\n`predicate` - функция которая принимает один (для массивов) и два (для объектов) аргумента" desc_ru: "фильтрует массив или объект и возвращает массив только с теми элементами, которые удовлетворяют предикату `predicate`.\n\n`predicate` - функция которая принимает один (для массивов) и два (для объектов) аргумента"
example: |- example: |-
use "functional" use functional
nums = [1,2,3,4,5] nums = [1,2,3,4,5]
print filter(nums, def(x) = x % 2 == 0) // [2, 4] print filter(nums, def(x) = x % 2 == 0) // [2, 4]
@ -1580,7 +1580,7 @@
desc: "converts each element of an array to other array" desc: "converts each element of an array to other array"
desc_ru: "преобразует каждый элемент массива в массив элементов" desc_ru: "преобразует каждый элемент массива в массив элементов"
example: |- example: |-
use "functional" use functional
nums = [1,2,3,4] nums = [1,2,3,4]
print flatmap(nums, def(x) { print flatmap(nums, def(x) {
@ -1594,7 +1594,7 @@
desc: "invokes function `consumer` for each element of array or map `data`\n\nIf `data` - массив, то в функции consumer необходим один параметр, если объект - два (ключ и значение)." desc: "invokes function `consumer` for each element of array or map `data`\n\nIf `data` - массив, то в функции consumer необходим один параметр, если объект - два (ключ и значение)."
desc_ru: "для каждого элемента в массиве или объекте `data` вызывает функцию `consumer`\n\nЕсли `data` - массив, то в функции `consumer` необходим один параметр, если объект - два (ключ и значение)." desc_ru: "для каждого элемента в массиве или объекте `data` вызывает функцию `consumer`\n\nЕсли `data` - массив, то в функции `consumer` необходим один параметр, если объект - два (ключ и значение)."
example: |- example: |-
use "functional" use functional
foreach([1, 2, 3], def(v) { print v }) foreach([1, 2, 3], def(v) { print v })
foreach({"key": 1, "key2": "text"}, def(key, value) { foreach({"key": 1, "key2": "text"}, def(key, value) {
@ -1605,7 +1605,7 @@
desc: "converts elements of array or map. If `data` is array - `mapper` converts his elements, if `data` is object - you need to pass `keyMapper` - converts keys and `valueMapper` - converts values" desc: "converts elements of array or map. If `data` is array - `mapper` converts his elements, if `data` is object - you need to pass `keyMapper` - converts keys and `valueMapper` - converts values"
desc_ru: "преобразует элементы массива или объекта.\n\nЕсли `data` - массив, то функция `mapper` преобразует значения, если объект - необходимо передать две функции: `keyMapper` - преобразует ключи и `valueMapper` - преобразует значения" desc_ru: "преобразует элементы массива или объекта.\n\nЕсли `data` - массив, то функция `mapper` преобразует значения, если объект - необходимо передать две функции: `keyMapper` - преобразует ключи и `valueMapper` - преобразует значения"
example: |- example: |-
use "functional" use functional
nums = [3,4,5] nums = [3,4,5]
print map(nums, def(x) = x * x) // [9, 16, 25] print map(nums, def(x) = x * x) // [9, 16, 25]
@ -1614,7 +1614,7 @@
desc: "converts elements of an array or a map to one value, e.g. sum of elements or concatenation string. `accumulator` takes one argument for array and two arguments for object (key and value)." desc: "converts elements of an array or a map to one value, e.g. sum of elements or concatenation string. `accumulator` takes one argument for array and two arguments for object (key and value)."
desc_ru: "преобразует элементы массива или объекта в одно значение, например сумма элементов или объединение в строку.\n\nЕсли `data` - массив, то в функции `accumulator` необходим один параметр, если объект - два (ключ и значение)" desc_ru: "преобразует элементы массива или объекта в одно значение, например сумма элементов или объединение в строку.\n\nЕсли `data` - массив, то в функции `accumulator` необходим один параметр, если объект - два (ключ и значение)"
example: |- example: |-
use "functional" use functional
nums = [1,2,3,4,5] nums = [1,2,3,4,5]
print reduce(nums, 0, def(x, y) = x + y) // 15 print reduce(nums, 0, def(x, y) = x + y) // 15
@ -1623,7 +1623,7 @@
desc: "sorts elements of an array or an object by `function` result" desc: "sorts elements of an array or an object by `function` result"
desc_ru: "сортирует элементы массива по данным в функции `function`" desc_ru: "сортирует элементы массива по данным в функции `function`"
example: |- example: |-
use "functional" use functional
data = [ data = [
{"k1": 2, "k2": "x"}, {"k1": 2, "k2": "x"},
@ -1748,11 +1748,11 @@
desc: "performs click with given mouse buttons" desc: "performs click with given mouse buttons"
desc_ru: "осуществляет клик мышью с заданными клавишами" desc_ru: "осуществляет клик мышью с заданными клавишами"
example: |- example: |-
use "robot" use robot
click(BUTTON3) // right mouse button click click(BUTTON3) // right mouse button click
example_ru: |- example_ru: |-
use "robot" use robot
click(BUTTON3) // клик правой кнопкой мыши click(BUTTON3) // клик правой кнопкой мыши
- -
@ -1767,7 +1767,7 @@
desc: "executes the process with parameters" desc: "executes the process with parameters"
desc_ru: "запускает процесс с параметрами\n\n Если функции переданы несколько аргументов, то они все передаются как параметры.\n Если функции передан только один параметр - массив, то его элементы передаются как параметры.\n Если функции передан только один параметр, то он служит единственным параметром." desc_ru: "запускает процесс с параметрами\n\n Если функции переданы несколько аргументов, то они все передаются как параметры.\n Если функции передан только один параметр - массив, то его элементы передаются как параметры.\n Если функции передан только один параметр, то он служит единственным параметром."
example: |- example: |-
use "robot" use robot
execProcess("mkdir", "Test") execProcess("mkdir", "Test")
execProcess("mkdir Test") execProcess("mkdir Test")
@ -1878,7 +1878,7 @@
desc: "executes tests and returns information about it's results" desc: "executes tests and returns information about it's results"
desc_ru: "запускает тесты и возвращает информацию о них по завершению работы в виде строки" desc_ru: "запускает тесты и возвращает информацию о них по завершению работы в виде строки"
example: |- example: |-
use "ounit" use ounit
def testAdditionOnNumbers() { def testAdditionOnNumbers() {
assertEquals(6, 0 + 1 + 2 + 3) assertEquals(6, 0 + 1 + 2 + 3)
@ -2191,7 +2191,7 @@
Возвращает ImageFXValue. Возвращает ImageFXValue.
example: |- example: |-
use "canvasfx" use canvasfx
g = showcanvas() g = showcanvas()
url = "http://lorempixel.com/640/480/nature" url = "http://lorempixel.com/640/480/nature"
@ -3608,12 +3608,12 @@
desc: "replaces input with the result of the given callback" desc: "replaces input with the result of the given callback"
desc_ru: "заменяет строку результатом заданной функции" desc_ru: "заменяет строку результатом заданной функции"
example: |- example: |-
use "regex" use regex
in = "dog cat" in = "dog cat"
pattern = regex("(\w+)\s(\w+)", Pattern.I) pattern = regex("(\w+)\s(\w+)", Pattern.I)
println pattern.replaceCallback(in, def(m) = m.group(2) + "" + m.group(1)) println pattern.replaceCallback(in, def(m) = m.group(2) + "" + m.group(1))
example_ru: |- example_ru: |-
use "regex" use regex
in = "пёс кот" in = "пёс кот"
pattern = regex("(\w+)\s(\w+)", Pattern.U | Pattern.I) pattern = regex("(\w+)\s(\w+)", Pattern.U | Pattern.I)
println pattern.replaceCallback(in, def(m) = m.group(2) + "о" + m.group(1)) println pattern.replaceCallback(in, def(m) = m.group(2) + "о" + m.group(1))
@ -3656,13 +3656,13 @@
desc: "replaces input with the result of the given callback" desc: "replaces input with the result of the given callback"
desc_ru: "заменяет строку результатом заданной функции" desc_ru: "заменяет строку результатом заданной функции"
example: |- example: |-
use "regex" use regex
in = "dog cat" in = "dog cat"
pattern = regex("(\w+)\s(\w+)", Pattern.I) pattern = regex("(\w+)\s(\w+)", Pattern.I)
matcher = pattern.matcher(in) matcher = pattern.matcher(in)
println matcher.replaceCallback(def(m) = m.group(2) + m.group(1)) println matcher.replaceCallback(def(m) = m.group(2) + m.group(1))
example_ru: |- example_ru: |-
use "regex" use regex
in = "пёс кот" in = "пёс кот"
pattern = regex("(\w+)\s(\w+)", Pattern.U | Pattern.I) pattern = regex("(\w+)\s(\w+)", Pattern.U | Pattern.I)
matcher = pattern.matcher(in) matcher = pattern.matcher(in)
@ -3872,7 +3872,7 @@
Возвращает BitmapValue. Возвращает BitmapValue.
example: |- example: |-
use ["http", "canvas"] use http, canvas
g = showcanvas() g = showcanvas()
url = "http://lorempixel.com/640/480/nature" url = "http://lorempixel.com/640/480/nature"
@ -3952,7 +3952,7 @@
desc: "shows canvas screen and returns GraphicsValue" desc: "shows canvas screen and returns GraphicsValue"
desc_ru: "показывает экран канваса и возвращает GraphicsValue" desc_ru: "показывает экран канваса и возвращает GraphicsValue"
example: |- example: |-
use "canvas" use canvas
g = showcanvas() g = showcanvas()
types: types:
- name: "BitmapValue" - name: "BitmapValue"
@ -4599,7 +4599,7 @@
desc: '' desc: ''
desc_ru: '' desc_ru: ''
example: |- example: |-
use ["std", "android", "forms"] use std, android, forms
img1 = assetBitmap("ownlang.png") img1 = assetBitmap("ownlang.png")
img2 = img1 img2 = img1
@ -4679,7 +4679,7 @@
desc: 'creates ProgressBar' desc: 'creates ProgressBar'
desc_ru: 'создаёт ProgressBar' desc_ru: 'создаёт ProgressBar'
example: |- example: |-
use ["android", "forms"] use android, forms
pb1 = newProgressBar(R.attr.progressBarStyleHorizontal) pb1 = newProgressBar(R.attr.progressBarStyleHorizontal)
pb1.setMax(100) pb1.setMax(100)
pb1.setProgress(10) pb1.setProgress(10)
@ -6730,7 +6730,7 @@
desc_ru: |- desc_ru: |-
подписывается на обработчик получения местоположения подписывается на обработчик получения местоположения
example: |- example: |-
use ["std", "gps"] use std, gps
provider = "gps" // or passive, network if exists provider = "gps" // or passive, network if exists
// requestUpdates(provider, 0, 25, def(loc) = echo("location changed: ", loc)) // requestUpdates(provider, 0, 25, def(loc) = echo("location changed: ", loc))

View File

@ -5,7 +5,7 @@
* *
*/ */
use ["date", "files", "robot", "std"] use date, files, robot, std
DEBUG = true DEBUG = true
EXAMPLES_DIR = "examples" EXAMPLES_DIR = "examples"

View File

@ -3,7 +3,7 @@ println arr1[0]
println arr1[1] println arr1[1]
println arr1 println arr1
use "std" use std
arr2 = newarray(5) arr2 = newarray(5)
arr2[2] = 9 arr2[2] = 9
arr2 = arr2 :: 4 arr2 = arr2 :: 4

View File

@ -1,4 +1,4 @@
use "std" use std
echo(#ABCDEF - #12345) echo(#ABCDEF - #12345)
echo(-8 << 2) echo(-8 << 2)

View File

@ -1,4 +1,4 @@
use ["std"] use std
class Point { class Point {
def Point(x = 0, y = 0) { def Point(x = 0, y = 0) {

View File

@ -1,4 +1,4 @@
use "std" use std
println "Destructuring assignment" println "Destructuring assignment"
arr = ["a", "b", "c"] arr = ["a", "b", "c"]

View File

@ -28,14 +28,14 @@ arr = [1, 2, 3, 4, 5]
for a : arr for a : arr
print a print a
use "std" use std
println "\n\nForeach loop on map" println "\n\nForeach loop on map"
object = {"key1": "value1", "key2": 100, "arr": [0, 1]} object = {"key1": "value1", "key2": 100, "arr": [0, 1]}
for key, value : object for key, value : object
echo(key, ":", value) echo(key, ":", value)
use "functional" use functional
// Functional loop // Functional loop
println "\n\nFunctional loop on array" println "\n\nFunctional loop on array"

View File

@ -1,4 +1,4 @@
use ["std", "types", "math"] use std, types, math
println "Operator overloading" println "Operator overloading"
def `::`(v1, v2) = string(v1) + string(v2) def `::`(v1, v2) = string(v1) + string(v2)

View File

@ -1,5 +1,4 @@
use "std" use std, types
use "types"
v = rand(10) v = rand(10)
println match v { println match v {

View File

@ -1,4 +1,4 @@
use "std" use std
def thread1() { def thread1() {
i = 0 i = 0

View File

@ -1,5 +1,4 @@
use "std" use std, types
use "types"
println typeof(1) println typeof(1)
println typeof("1") println typeof("1")

View File

@ -1,4 +1,4 @@
use "canvas" use canvas
w = 800 h = 600 w = 800 h = 600
window("canvas example", w, h); window("canvas example", w, h);

View File

@ -1,5 +1,4 @@
use "std" use std, canvas
use "canvas"
w = 800 h = 600 w = 800 h = 600
window("canvas example 2", w, h); window("canvas example 2", w, h);

View File

@ -1,5 +1,4 @@
use "canvas" use canvas, std
use "std"
w = 800 h = 600 w = 800 h = 600
window("Animate line", w, h) window("Animate line", w, h)

View File

@ -1,5 +1,4 @@
use "canvas" use canvas, std
use "std"
w = 800 h = 600 w = 800 h = 600
window("Animate line with thread", w, h) window("Animate line with thread", w, h)

View File

@ -1,5 +1,4 @@
use "canvas" use canvas, std
use "std"
w = 640 h = 480 w = 640 h = 480
window("Управление точкой", w, h) window("Управление точкой", w, h)

View File

@ -1,6 +1,4 @@
use "canvas" use canvas, math, std
use "math"
use "std"
msg = "" msg = ""
NUM_POINTS = 0 NUM_POINTS = 0

View File

@ -1,4 +1,4 @@
use "canvas" use canvas
w = 800 h = 600 w = 800 h = 600
window("Fractal rectangle demo", w, h) window("Fractal rectangle demo", w, h)

View File

@ -1,4 +1,4 @@
use "canvasfx" use canvasfx
// https://docs.oracle.com/javafx/2/canvas/jfxpub-canvas.htm // https://docs.oracle.com/javafx/2/canvas/jfxpub-canvas.htm

View File

@ -1,5 +1,4 @@
use "canvasfx" use canvasfx, std
use "std"
w = 800 h = 600 w = 800 h = 600
g = window("JavaFX Event handler example", w, h) g = window("JavaFX Event handler example", w, h)

View File

@ -1,4 +1,4 @@
use "canvasfx" use canvasfx
steps = 20 steps = 20
size = 25 size = 25

View File

@ -1,4 +1,4 @@
use "canvasfx" use canvasfx
g = window("JavaFX Image demo", 400, 200) g = window("JavaFX Image demo", 400, 200)
img = createImage("https://picsum.photos/400/200/") img = createImage("https://picsum.photos/400/200/")

View File

@ -1,5 +1,4 @@
use "std" use std, canvasfx
use "canvasfx"
graphics = window("JavaFX Image negation demo", 400, 400) graphics = window("JavaFX Image negation demo", 400, 400)
imgSource = createImage("https://picsum.photos/400/200/") imgSource = createImage("https://picsum.photos/400/200/")

View File

@ -1,6 +1,4 @@
use "canvasfx" use canvasfx, math, functional
use "math"
use "functional"
// https://github.com/SeTSeR/KochSnowflake // https://github.com/SeTSeR/KochSnowflake

View File

@ -1,5 +1,4 @@
use "canvasfx" use canvasfx, std
use "std"
// http://www.developer.com/java/data/using-graphics-in-javafx.html // http://www.developer.com/java/data/using-graphics-in-javafx.html

View File

@ -1,4 +1,4 @@
use "std" use std
// header // header
print " " * 4 print " " * 4

View File

@ -1,4 +1,4 @@
use ["std", "jdbc"] use std, jdbc
connection = getConnection("jdbc:hsqldb:file:hsql.db", "", "", "org.hsqldb.jdbcDriver") connection = getConnection("jdbc:hsqldb:file:hsql.db", "", "", "org.hsqldb.jdbcDriver")
statement = connection.createStatement() statement = connection.createStatement()

View File

@ -1,4 +1,4 @@
use ["std", "jdbc"] use std, jdbc
// Example from https://github.com/xerial/sqlite-jdbc // Example from https://github.com/xerial/sqlite-jdbc

View File

@ -1,4 +1,4 @@
use ["std", "gzip"] use std, gzip
// println "Gzip single file" // println "Gzip single file"
// gzip("absolute path to file", "example.gz") // gzip("absolute path to file", "example.gz")

View File

@ -1,4 +1,4 @@
use "json" use json
data = { data = {
"name": "Json Example", "name": "Json Example",

View File

@ -1,4 +1,4 @@
use "yaml" use yaml
data = { data = {
"name": "Yaml Example", "name": "Yaml Example",

View File

@ -1,4 +1,4 @@
use "zip" use zip
// println "Zip single file" // println "Zip single file"
// zip("absolute path to file", "example.zip") // zip("absolute path to file", "example.zip")

View File

@ -1,4 +1,4 @@
use "forms" use forms
window = newWindow("Basic form example") window = newWindow("Basic form example")
window.add("Hello, world") window.add("Hello, world")

View File

@ -1,4 +1,4 @@
use "forms" use forms
button = newButton("Click me") button = newButton("Click me")
button.onClick(def() { button.onClick(def() {

View File

@ -1,5 +1,4 @@
use "std" use std, forms
use "forms"
actionsPanel = newPanel() actionsPanel = newPanel()
actionsPanel.setLayout(boxLayout(actionsPanel, BoxLayout.PAGE_AXIS)) actionsPanel.setLayout(boxLayout(actionsPanel, BoxLayout.PAGE_AXIS))

View File

@ -1,4 +1,4 @@
use ["java", "forms"] use java, forms
UIManager = newClass("javax.swing.UIManager") UIManager = newClass("javax.swing.UIManager")
// UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel") // UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel")

View File

@ -1,4 +1,4 @@
use "forms" use forms
// Create Panel with BoxLayout // Create Panel with BoxLayout
panel = newPanel() panel = newPanel()

View File

@ -1,4 +1,4 @@
use "forms" use forms
label = newLabel("Current value: 50") label = newLabel("Current value: 50")
progressBar = newProgressBar() progressBar = newProgressBar()

View File

@ -1,4 +1,4 @@
use ["std", "http", "forms"] use std, http, forms
chatHistory = newLabel("<html>Чат с самоботом<br>") chatHistory = newLabel("<html>Чат с самоботом<br>")
messageField = newTextField() messageField = newTextField()

View File

@ -1,4 +1,4 @@
use ["std", "forms", "functional"] use std, forms, functional
text = map(range(1, 16), def(x) = "line " + x).joinToString("\n") text = map(range(1, 16), def(x) = "line " + x).joinToString("\n")
label = newLabel() label = newLabel()

View File

@ -1,5 +1,4 @@
use "std" use std, forms
use "forms"
textField = newTextField("Some text") textField = newTextField("Some text")

View File

@ -1,4 +1,4 @@
use "forms" use forms
textArea = newTextArea("Window logs:") textArea = newTextArea("Window logs:")

View File

@ -1,6 +1,4 @@
use "std" use std, math, functional
use "math"
use "functional"
add = def(a,b) = a + b add = def(a,b) = a + b
sub = def(a,b) = a - b sub = def(a,b) = a - b

View File

@ -1,6 +1,5 @@
// Simple parser example // Simple parser example
use "std" use std, types
use "types"
operations = { operations = {
"+" : def(a,b) = a+b, "+" : def(a,b) = a+b,

View File

@ -1,5 +1,4 @@
use "std" use std, functional
use "functional"
data = [1,2,3,4,5,6,7,8,9] data = [1,2,3,4,5,6,7,8,9]
chain(data, chain(data,

View File

@ -1,5 +1,4 @@
use "std" use std, functional
use "functional"
nums = [1,2,3,4,5,6,7,8,9,10] nums = [1,2,3,4,5,6,7,8,9,10]
nums = filter(nums, def(x) = x % 2 == 0) nums = filter(nums, def(x) = x % 2 == 0)

View File

@ -1,5 +1,4 @@
use "std" use std, functional
use "functional"
nums = [[1, 2], [3], [], [4, 5]] nums = [[1, 2], [3], [], [4, 5]]
nums = flatmap(nums, IDENTITY) nums = flatmap(nums, IDENTITY)

View File

@ -1,4 +1,4 @@
use "functional" use functional
nums = [1,2,3,4,5] nums = [1,2,3,4,5]
println "Sum: " + reduce(nums, 0, def(x, y) = x + y) println "Sum: " + reduce(nums, 0, def(x, y) = x + y)

View File

@ -1,5 +1,4 @@
use "std" use std, functional
use "functional"
nums = [1,2,3,4,5] nums = [1,2,3,4,5]
println "Sort numbers in descending order" println "Sort numbers in descending order"

View File

@ -1,4 +1,4 @@
use ["std", "functional"] use std, functional
println "x, square(x), cube(x) for even numbers" println "x, square(x), cube(x) for even numbers"
data = [1,2,3,4,5,6,7,8,9] data = [1,2,3,4,5,6,7,8,9]

View File

@ -1,6 +1,4 @@
use "canvas" use canvas, math, std
use "math"
use "std"
w = 800 h = 600 w = 800 h = 600
w2 = w/2 h2 = h/2 w2 = w/2 h2 = h/2

View File

@ -1,7 +1,4 @@
use "std" use std, math, types, canvasfx
use "math"
use "types"
use "canvasfx"
// Constants // Constants
CELL_NONE = -100 CELL_NONE = -100

View File

@ -1,6 +1,4 @@
use "std" use std, canvas, socket
use "canvas"
use "socket"
/// --- PIPES CELL --- /// --- PIPES CELL ---
CELL_START = 0 CELL_START = 0

View File

@ -1,5 +1,4 @@
use "std" use std, canvas
use "canvas"
/// --- PIPES CELL --- /// --- PIPES CELL ---
CELL_START = 0 CELL_START = 0

View File

@ -1,6 +1,4 @@
use "std" use std, canvas, socket
use "canvas"
use "socket"
/// --- PIPES CELL --- /// --- PIPES CELL ---
CELL_START = 0 CELL_START = 0

View File

@ -1,4 +1,4 @@
use "java" use java
System = newClass("java.lang.System") System = newClass("java.lang.System")
println "OS name: " + System.getProperty("os.name") println "OS name: " + System.getProperty("os.name")
println "OS version: " + System.getProperty("os.version") println "OS version: " + System.getProperty("os.version")

View File

@ -1,5 +1,4 @@
use "std" use std, http
use "http"
http("http://jsonplaceholder.typicode.com/users", "POST", {"name": "OwnLang", "versionCode": 10}, def(v) { http("http://jsonplaceholder.typicode.com/users", "POST", {"name": "OwnLang", "versionCode": 10}, def(v) {
println "Added: " + v println "Added: " + v

View File

@ -1,4 +1,4 @@
use ["std", "http", "json", "functional", "date"] use std, http, json, functional, date
header = "* Prints current GitHub timeline *" header = "* Prints current GitHub timeline *"
println "*" * header.length println "*" * header.length

View File

@ -1,4 +1,4 @@
use ["std", "okhttp"] use std, okhttp
// https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/PostMultipart.java // https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/PostMultipart.java

View File

@ -1,4 +1,4 @@
use ["std", "okhttp"] use std, okhttp
TOKEN = "your bot token" TOKEN = "your bot token"

View File

@ -1,4 +1,4 @@
use ["std", "okhttp"] use std, okhttp
// https://github.com/square/okhttp/blob/b21ed68c08c2a5c1eb0bbe93a6f720d1aa2820da/samples/guide/src/main/java/okhttp3/recipes/WebSocketEcho.java // https://github.com/square/okhttp/blob/b21ed68c08c2a5c1eb0bbe93a6f720d1aa2820da/samples/guide/src/main/java/okhttp3/recipes/WebSocketEcho.java

View File

@ -1,7 +1,4 @@
use "std" use std, http, json, functional
use "http"
use "json"
use "functional"
// Telegram API example // Telegram API example

View File

@ -1,11 +1,5 @@
// Twitch Tools // Twitch Tools
use "std" use std, math, http, json, date, types, functional
use "math"
use "http"
use "json"
use "date"
use "types"
use "functional"
match ARGS { match ARGS {
case (): usage() case (): usage()

View File

@ -1,4 +1,4 @@
use "robot" use robot
pause = 5 pause = 5
xstep = 50 ystep = 5 xstep = 50 ystep = 5

View File

@ -1,4 +1,4 @@
use ["std", "functional", "gzip", "json", "java"] use std, functional, gzip, json, java
title("Added std::getBytes, std::stringFromBytes") title("Added std::getBytes, std::stringFromBytes")
arr = [119, 111, 114, 108, 100] arr = [119, 111, 114, 108, 100]

View File

@ -1,5 +1,5 @@
for i = 0, i < 50, i++ { for i = 0, i < 50, i++ {
use "std" use std
use "files" use files
use ["math", "functional"] use math, functional
} }

View File

@ -1,4 +1,4 @@
use "std" use std
def testArrayIterate() { def testArrayIterate() {
sum = 0 sum = 0

View File

@ -1,4 +1,4 @@
use "std" use std
def testIncludeClass() { def testIncludeClass() {
include "src/test/resources/expressions/includeClass.own.txt" include "src/test/resources/expressions/includeClass.own.txt"

View File

@ -1,4 +1,4 @@
use "types" use types
def testMatchValue() { def testMatchValue() {
value = 20 value = 20

View File

@ -1,4 +1,4 @@
use ["base64", "functional", "types"] use base64, functional, types
base64Example = [0x42, 0x61, 0x73, 0x65, 0x36, 0x34, 0x20, 0x45, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65] base64Example = [0x42, 0x61, 0x73, 0x65, 0x36, 0x34, 0x20, 0x45, 0x78, 0x61, 0x6D, 0x70, 0x6C, 0x65]
base64Example_enc = [0x51, 0x6D, 0x46, 0x7A, 0x5A, 0x54, 0x59, 0x30, base64Example_enc = [0x51, 0x6D, 0x46, 0x7A, 0x5A, 0x54, 0x59, 0x30,

View File

@ -1,4 +1,4 @@
use "date" use date
def testCompareDates() { def testCompareDates() {
assertTrue(newDate(2016, 04, 10) > newDate(2015, 03, 11)) assertTrue(newDate(2016, 04, 10) > newDate(2015, 03, 11))

View File

@ -1,4 +1,4 @@
use "date" use date
def testDateFormat() { def testDateFormat() {
d = formatDate(newDate(2016, 04, 10), newFormat("yyyy/MM/dd HH:mm:ss")) d = formatDate(newDate(2016, 04, 10), newFormat("yyyy/MM/dd HH:mm:ss"))

View File

@ -1,4 +1,4 @@
use "date" use date
def testDateParse() { def testDateParse() {
d = parseDate("2016/05/10", newFormat("yyyy/MM/dd")) d = parseDate("2016/05/10", newFormat("yyyy/MM/dd"))

View File

@ -1,4 +1,4 @@
use "date" use date
def testNewDate() { def testNewDate() {
d = newDate(2016, 04, 10) d = newDate(2016, 04, 10)

View File

@ -1,4 +1,4 @@
use ["files", "types"] use files, types
def testFiles() { def testFiles() {
// writeLong // writeLong

View File

@ -1,4 +1,4 @@
use "functional" use functional
def testFunctionalChain() { def testFunctionalChain() {
data = [1,2,3,4,5,6,7] data = [1,2,3,4,5,6,7]

View File

@ -1,4 +1,4 @@
use ["std", "functional"] use std, functional
def testArrayForeach1Arg() { def testArrayForeach1Arg() {
sum = 0 sum = 0

View File

@ -1,4 +1,4 @@
use ["std", "functional", "math"] use std, functional, math
def testStream() { def testStream() {
data = [1,2,3,4,5,6,7] data = [1,2,3,4,5,6,7]

View File

@ -1,4 +1,4 @@
use ["std", "gzip"] use std, gzip
def testGzipText() { def testGzipText() {
text = trim(" text = trim("

View File

@ -1,4 +1,4 @@
use ["std", "java"] use std, java
def testCheckNull() { def testCheckNull() {
assertTrue(isNull(null)) assertTrue(isNull(null))

View File

@ -1,4 +1,4 @@
use ["regex", "types"] use regex, types
def testMatchGitUrl() { def testMatchGitUrl() {
pattern = Pattern.compile("https?://((git(hu|la)b\.com)|bitbucket\.org)/?") pattern = Pattern.compile("https?://((git(hu|la)b\.com)|bitbucket\.org)/?")

View File

@ -1,4 +1,4 @@
use ["regex", "types"] use regex, types
def testReplaceCallback() { def testReplaceCallback() {
in = "[1-2-3-4]" in = "[1-2-3-4]"

View File

@ -1,4 +1,4 @@
use "std" use std
def testArraySpliceFromStart() { def testArraySpliceFromStart() {
arr = [1,2,3,4,5] arr = [1,2,3,4,5]

View File

@ -1,4 +1,4 @@
use "std" use std
def testDefaultNumber() { def testDefaultNumber() {
assertEquals(123, default(0, 123)) assertEquals(123, default(0, 123))
@ -9,7 +9,7 @@ def testDefaultString() {
} }
def testDefaultNull() { def testDefaultNull() {
use "java" use java
assertEquals("not null", default(null, "not null")) assertEquals("not null", default(null, "not null"))
} }

View File

@ -1,4 +1,4 @@
use "std" use std
def testGetBytes() { def testGetBytes() {
assertEquals([111, 119, 110, 108, 97, 110, 103], getBytes("ownlang")) assertEquals([111, 119, 110, 108, 97, 110, 103], getBytes("ownlang"))

View File

@ -1,4 +1,4 @@
use "std" use std
def testIndexOf() { def testIndexOf() {
assertEquals(3, indexOf("123/456/789", "/")) assertEquals(3, indexOf("123/456/789", "/"))

View File

@ -1,4 +1,4 @@
use "std" use std
def testLastIndexOf() { def testLastIndexOf() {
assertEquals(8, lastIndexOf("/123/456/789", "/")) assertEquals(8, lastIndexOf("/123/456/789", "/"))

View File

@ -1,4 +1,4 @@
use "std" use std
def testParseInt() { def testParseInt() {
assertEquals(141, parseInt("141")) assertEquals(141, parseInt("141"))

View File

@ -1,4 +1,4 @@
use "std" use std
def testParseInt() { def testParseInt() {
assertEquals(12345654321, parseLong("12345654321")) assertEquals(12345654321, parseLong("12345654321"))

View File

@ -1,4 +1,4 @@
use ["std", "types", "functional"] use std, types, functional
def testRangeParams() { def testRangeParams() {
x = range(10) x = range(10)

View File

@ -1,4 +1,4 @@
use "std" use std
def testStringFromBytes() { def testStringFromBytes() {
assertEquals("ownlang", stringFromBytes([111, 119, 110, 108, 97, 110, 103])) assertEquals("ownlang", stringFromBytes([111, 119, 110, 108, 97, 110, 103]))

View File

@ -1,4 +1,4 @@
use "std" use std
def testStripMargin() { def testStripMargin() {
testCases = [ testCases = [

View File

@ -1,4 +1,4 @@
use "std" use std
def testToHexString() { def testToHexString() {
assertEquals("8d", toHexString(141)) assertEquals("8d", toHexString(141))

View File

@ -1,4 +1,4 @@
use "std" use std
def testTryOnly() { def testTryOnly() {
assertEquals(1, try(def() = 1)) assertEquals(1, try(def() = 1))

View File

@ -1,4 +1,4 @@
use ["std", "yaml", "ounit"] use std, yaml, ounit
x = yamldecode(" x = yamldecode("
name: \"std\" name: \"std\"

View File

@ -1,4 +1,4 @@
use ["std", "yaml", "ounit"] use std, yaml, ounit
yml = yamlencode({ yml = yamlencode({
"name": "Yaml Example", "name": "Yaml Example",

View File

@ -45,7 +45,7 @@ def testIsEmpty() {
} }
def testExtensionFunction() { def testExtensionFunction() {
use "std" use std
s = "1es1" s = "1es1"
assertEquals("test", s.replace("1", "t")) assertEquals("test", s.replace("1", "t"))
} }

View File

@ -0,0 +1,26 @@
use std
def testRegular() {
assertEquals("7f", "127".toHexString())
}
def testInCondition() {
if (true) {
use date
}
assertNotEquals("", newDate())
}
def testInScope() {
PI = "fallback"
assertEquals("fallback", PI)
useMath()
assertEquals("fallback", PI)
assertEquals(3, abs(-3))
}
def useMath() {
use math
}

View File

@ -1,6 +1,4 @@
use "math" use math, std, functional
use "std"
use "functional"
word = 2 + 2 word = 2 + 2
word2 = PI + word word2 = PI + word
@ -105,7 +103,7 @@ for (v : arr1 << arr2) print "" + v + ", "
print "\n" print "\n"
for v : [1,2,3,4,5,6,7,8,9] print "" + v + ", " for v : [1,2,3,4,5,6,7,8,9] print "" + v + ", "
use "types" use types
println typeof(1) println typeof(1)
println typeof("1") println typeof("1")
println typeof(arr1) println typeof(arr1)
@ -133,7 +131,7 @@ foreach(nums, ::echo)
println "sort" println "sort"
foreach(sort(nums, def(a,b) = b - a), ::echo) foreach(sort(nums, def(a,b) = b - a), ::echo)
use "http" use http
/*http("http://jsonplaceholder.typicode.com/users", "POST", {"name": "OwnLang", "versionCode": 10}, def(v) { /*http("http://jsonplaceholder.typicode.com/users", "POST", {"name": "OwnLang", "versionCode": 10}, def(v) {
println "Added: " + v println "Added: " + v
@ -144,7 +142,7 @@ def http_get_demo(v) {
http("http://jsonplaceholder.typicode.com/users", ::echo) http("http://jsonplaceholder.typicode.com/users", ::echo)
}*/ }*/
use "json" use json
println "json" println "json"
println jsonencode({ println jsonencode({
"name": "JSON Example", "name": "JSON Example",
@ -242,7 +240,7 @@ println 1 :: 2 :: 3
println "\u042a" println "\u042a"
use "date" use date
d = newDate(); d = newDate();
println d println d
println formatDate(d) println formatDate(d)

Some files were not shown because too many files have changed in this diff Show More