Difference between revisions of "Qubot Script"

From QuData
Jump to navigation Jump to search
 
(2 intermediate revisions by the same user not shown)
Line 166: Line 166:
 
Dictionary array functions:
 
Dictionary array functions:
  
'''''find(EXPR)''''' - searche for array elements that satisfy the '''EXPR''' condition. Found elements are returned as an array.<br>
+
'''''find(EXPR)''''' - search for array elements that satisfy the '''EXPR''' condition. Found elements are returned as an array.<br>
 
For example:
 
For example:
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 176: Line 176:
  
 
local res = arr.find(price > 80)  // find all objects whose 'price' field is higher than 80 and return them in an array
 
local res = arr.find(price > 80)  // find all objects whose 'price' field is higher than 80 and return them in an array
print('found $res.length:')     // display the number of found objects
+
print('found $res.length:')       // display the number of found objects
print(res)                         // display objects that satisfy the condition
+
print(res)                       // display objects that satisfy the condition
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 202: Line 202:
 
]  
 
]  
  
local res = arr.count(price < 100)                                           // for each element of the array, multiply the price by the quantity and add the result
+
local res = arr.count(price < 100)   // for each element of the array, multiply the price by the quantity and add the result
print("The quantity of goods that is cheaper than 100 UAH: $res")           // display the number of goods: "The quantity of goods that is cheaper than 100 UAH: 1"
+
print("The quantity of goods that is cheaper than 100 UAH: $res") // display the number of goods: "The quantity of goods that is cheaper than 100 UAH: 1"
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 311: Line 311:
 
     res = 'a less or equal 7'
 
     res = 'a less or equal 7'
 
}</syntaxhighlight>
 
}</syntaxhighlight>
В данном примере проверяется условие <code>a &gt; 7</code> и если оно истинно, то выполняется первый блок скрипта, окруженный фигурными скобками, иначе выполняется блок после служебного слова '''else'''
+
In this example, the condition <code>a &gt; 7</code> is checked and if it is true, then the first block of the script is executed, that is surrounded by curly braces, otherwise the block after the keyword '''else''' is executed
  
<span id="цикл-while"></span>
+
<span id="while-loop"></span>
  
== Цикл '''while''' ==
+
== '''While''' loop ==
  
Оператор цикла проверяет условие и пока оно истинно, выполняет код окруженный фигурными скобками
+
The loop statement checks the condition and while it is true, executes the code surrounded by curly braces
  
 
<syntaxhighlight lang="js">a = 7
 
<syntaxhighlight lang="js">a = 7
Line 324: Line 324:
 
     a = a - 1
 
     a = a - 1
 
}</syntaxhighlight>
 
}</syntaxhighlight>
В данном примере скрипт <code>a = a - 1</code> будет выполнятся до тех пор пока значение слота <code>a</code> не станет равным нулю
+
In this example, the script <code>a = a - 1</code> will be executed until the value of the slot <code>a</code> becomes zero
  
<span id="итератор-for"></span>
+
<span id="iterator-for"></span>
== Итератор '''for''' ==
+
== Iterator '''for''' ==
  
Итератор используется для перебора всех значений массива, либо ключей из словаря
+
An iterator is used to loop through all values of an array, or keys from a dictionary
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 342: Line 342:
 
1
 
1
 
</syntaxhighlight>
 
</syntaxhighlight>
В данном примере цикл последовательно перебирает значения массива и заносит их во временную переменную '''val''' соответственно для каждого элемента массива выполняется окруженный фигурными скобками скрипт '''print(val)''' выводящий значение в отладочное окно
+
In this example, the loop sequentially iterates through the values of the array and puts them into the temporary variable '''val''',  respectively, for each element of the array, the script  '''print(val)''', surrounded by curly braces, is executed, displaying the value in the debug window
  
Иногда удобно в цикле иметь и индекс массива, для этого перед переменной значения добавляем имя переменной индекса:
+
Sometimes it is convenient to have an array index in the loop. For this we add the name of the index variable before the value variable:
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 358: Line 358:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Для перебора ключей и значений словаря используется аналогичная конструкция:
+
To iterate over the keys and values of a dictionary, a similar construction is used:
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
 
arr = {pizza: 100, milk: 20, wine: 120}
 
arr = {pizza: 100, milk: 20, wine: 120}
Line 371: Line 371:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
<span id="оператор-switch"></span>
+
<span id="operator-switch"></span>
  
== Оператор выбора '''switch''' ==
+
== '''Switch''' case operator ==
  
Конструкция '''switch''' заменяет собой сразу несколько '''if'''. Она представляет собой более наглядный способ сравнить выражение сразу с несколькими вариантами.
+
The '''switch''' construct replaces several '''ifs''' at once. It is a more visual way to compare an expression against several options at once.
Имеет один или более блок '''case''' и необязательный блок '''default'''.
+
It has one or more '''case''' block and optional '''default''' block.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 388: Line 388:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Переменная проверяется на строгое соответствие значению справа от '''case''' и если оно совпадает, то выполняется код до тех пор пока не встретится
+
The variable is checked for a strict match to the value to the right of '''case''' and if it matches, then the code is executed until it meets '''break''' operator.
оператор '''break'''
 
  
Если ни одно из '''case''' не подошло, выполняется код справа от '''default'''
+
If none of the '''case''' matches, the code to the right of '''default''' is executed.
  
<span id="оператор-in"></span>
+
<span id="operator-in"></span>
  
== Оператор '''in''' ==
+
== '''In''' operator ==
  
Оператор '''in''' проверяет есть ли значение в массиве либо является ключём в словаре.
+
The '''in''' operator checks whether the value is in an array or is a key in a dictionary.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
sArr = [7, 7.3, "hello"]            // массив
+
sArr = [7, 7.3, "hello"]            // array
print("hello" in sArr)              // вернет true, т.к. значение "hello" присутствует в массиве sArr  
+
print("hello" in sArr)              // return true, because the value "hello" is present in the array sArr  
sDic = { price: 100, food: "Wine"}  // словарь
+
sDic = { price: 100, food: "Wine"}  // dictionary
print("food" in sDic)                // вернет true, т.к. ключ "food" присутствует в словаре sDic
+
print("food" in sDic)                // return true, because the key "food" is present in the dictionary sDic
  
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Переменная проверяется на строгое соответствие значению справа от '''case''' и если оно совпадает, то выполняется код до тех пор пока не встретится
+
The variable is checked for a strict match to the value to the right of '''case''' and if it matches, then the code is executed until it meets '''break''' operator.
оператор '''break'''
 
  
Если ни одно из '''case''' не подошло, выполняется код справа от '''default'''
+
If none of the '''case''' matches, the code to the right of '''default''' is executed.
  
<span id="оператор-button"></span>
+
<span id="operator-button"></span>
  
== Оператор '''button''' ==
+
== '''Button''' operator ==
  
 
'''''button(caption){ SCRIPT }'''''<br>
 
'''''button(caption){ SCRIPT }'''''<br>
Данный оператор добавляет в интерфейс кнопку с текстом '''caption''' в текущее сообщение. После нажатия на кнопку выполняется логика '''SCRIPT'''.
+
This operator adds a button to the interface with the text '''caption''' in the current message. After pressing the button, the '''SCRIPT''' logic is executed.
Если '''caption''' - объект, то он должен состоять из двухбуквенных ключей (идентификаторов языка: en, ru,…) со строковыми значения на этих языках.
+
If '''caption''' is an object, then it must consist of two-letter keys (language identifiers: en, ru,…) with string values in these languages.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
button('click me')      // текст в кнопке
+
button('click me')      // button text
 
{
 
{
     // скрипт, который выполнится после нажатия
+
     // script that is executed after clicking
 
     print('button was clicked!')
 
     print('button was clicked!')
 
     step('STATE_AFTER_CLICK')
 
     step('STATE_AFTER_CLICK')
Line 429: Line 427:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
При нажатии на кнопку скрипт будет выполнен в контексте локальных переменных на момент добавления данной кнопки, а также в контексте
+
When the button is clicked, the script will be executed in the context of local variables at the time the button was added, as well as in the context of the slot values at the moment the button was clicked!
значений слотов на момент нажатия на кнопку!
 
  
<span id="функции-перехода"></span>
+
<span id="transition-function"></span>
  
== Функции перехода ==
+
== Transition functions ==
  
'''''run(state)''''' - выполнить логику шага '''state'''
+
'''''run(state)''''' - execute '''state''' step logic
  
'''''step(state)''''' - установка шага перехода по умолчанию в значение '''state'''
+
'''''step(state)''''' - set default transition step to '''state'''
  
'''''goto(state)''''' - мгновенный переход в шаг '''state'''
+
'''''goto(state)''''' - instant jump to '''state''' step
  
<span id="функции-работы-с-контентом"></span>
+
<span id="content-functions"></span>
  
== Функции работы с контентом ==
+
== Content functions ==
  
'''''text(obj)''''' - вывести в текущее сообщение текст. Если '''obj''' - это сторока, то она выводится не зависимо от текущего языка. Если '''obj''' - объект, то он должен состоять из двухбуквенных ключей (идентификаторов языка: en, ru,…) со строковыми значения на этих языках.
+
'''''text(obj)''''' - display text in current message. If '''obj''' is a string, then it is output regardless of the current language. If '''obj''' is an object, then it must consist of two-letter keys (language identifiers: en, ru,…) with string values in these languages.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 453: Line 450:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
'''''images()''''' - создать новую строку картинок. Каждый последующий вызов image будет добавляться в эту строку, пока снова не будет вызван images().
+
'''''images()''''' - create a new line of images. Every following call to image will be added to this line until images() is called again.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 461: Line 458:
 
image(URL + "owl_b.png") </syntaxhighlight>
 
image(URL + "owl_b.png") </syntaxhighlight>
  
'''''image(url, width)''''' - вывести в текущее сообщение картинку. Если '''url''' - это строка, то он используется не зависимо от текущего языка. Если '''url''' - объект, то он должен состоять из двухбуквенных ключей (идентификаторов языка: en, ru,…) со строковыми значения на этих языках.. Необязательный параметр '''width''' указывает насколько в процентах нужно сжать изображение
+
'''''image(url, width)''''' - add an image to the current message. If '''url''' is a string, then it is used regardless of the current language. If '''url''' is an object, then it must consist of two-letter keys (language identifiers: en, ru,…) with string values in these languages. The optional parameter '''width''' specifies how much to compress the image as a percentage.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 469: Line 466:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
'''''buttons()''''' - создать новую строку кнопок. Каждый последующий вызов button будет добавляться в эту строку, пока снова не будет вызван buttons().
+
'''''buttons()''''' - create a new row of buttons. Every following call to button will be added to this line until buttons() is called again.  
  
'''''get_check()''''' - получить массив значений кнопок типа check (1 - нажата, 0 - отжата)
+
'''''get_check()''''' - get an array of button values of the check type (1 - pressed, 0 - released)
  
'''''set_check(list)''''' - задать значения кнопок типа check из массива list.
+
'''''set_check(list)''''' - set the values of check type buttons from the list array.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 480: Line 477:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
'''''get_radio()''''' - получить массив значений кнопок типа radio (1 - нажата, 0 - отжата). Единица будет одна.
+
'''''get_radio()''''' - get an array of radio button values (1 - pressed, 0 - released). The unit will be one.
  
'''''set_radio(list)''''' - задать значения кнопок типа radio из массива list.
+
'''''set_radio(list)''''' - set the values of radio type buttons from the list array.
  
<span id="отладчные-функции"></span>
+
<span id="debug-functions"></span>
  
== Отладчные функции ==
+
== Debugging functions ==
  
'''''print(args)''''' - вывод информации в окно отладки
+
'''''print(args)''''' - display information in the debug window
  
<span id="округление"></span>
+
<span id="rounding"></span>
  
== Округление ==
+
== Rounding ==
  
'''''floor(val)''''' - округление чисел в меньшую сторону:
+
'''''floor(val)''''' - round numbers down:
  
 
<syntaxhighlight lang="js">floor(5.8)    //  5
 
<syntaxhighlight lang="js">floor(5.8)    //  5
 
floor(-6.1)  // -7</syntaxhighlight>
 
floor(-6.1)  // -7</syntaxhighlight>
'''''trunc(val)''''' - отбрасывание дробной части:
+
'''''trunc(val)''''' - discard the fractional part:
  
 
<syntaxhighlight lang="js">trunc(5.51)  //  5
 
<syntaxhighlight lang="js">trunc(5.51)  //  5
 
trunc(-6.99)  // -6</syntaxhighlight>
 
trunc(-6.99)  // -6</syntaxhighlight>
'''''ceil(val)''''' - округление чисел в большую сторону:
+
'''''ceil(val)''''' - round numbers up:
  
 
<syntaxhighlight lang="js">ceil(5.15)    // 6</syntaxhighlight>
 
<syntaxhighlight lang="js">ceil(5.15)    // 6</syntaxhighlight>
'''''round(val, num)''''' - округление '''val''' до '''num''' чисел после запятой:
+
'''''round(val, num)''''' - round '''val''' to '''num''' numbers after the decimal point:
  
 
<syntaxhighlight lang="js">round(3.14159265, 2)  // 3.14</syntaxhighlight>
 
<syntaxhighlight lang="js">round(3.14159265, 2)  // 3.14</syntaxhighlight>
  
<span id="случайные-числа"></span>
+
<span id="random-numbers"></span>
== Случайные числа ==
+
== Random numbers ==
  
'''''randint(min,max)''''' - возвращает целое случайное число в диапазоне [min,max].
+
'''''randint(min,max)''''' - return an integer random number in the range [min,max].
  
'''''random()''''' - возвращает случайное вещественное число в диапазоне [0,1].
+
'''''random()''''' - return an integer random number in the range [0,1].
  
<span id="дата-и-время"></span>
+
<span id="date-and-time"></span>
== Дата и время ==
+
== Date and time ==
  
'''''date(format)''''' - возвращает текущую дату и время в указанном формате. По умолчанию аргумент '''format''' принимает значение: '''%d/%m/%Y %H:%M:%S'''
+
'''''date(format)''''' - return the current date and time in the specified format. By default, the '''format''' argument takes the value: '''%d/%m/%Y %H:%M:%S'''
  
Поддерживаемые коды форматирования:
+
Supported format codes:
  
* '''%y''' - год без столетия ('22')
+
* '''%y''' - year without a century ('22')
* '''%Y''' - год ('2022')
+
* '''%Y''' - year ('2022')
* '''%m''' - месяц
+
* '''%m''' - month
* '''%d''' - день
+
* '''%d''' - day
* '''%H''' - часы
+
* '''%H''' - hours 
* '''%M''' - минуты
+
* '''%M''' - minutes
* '''%S''' - секунды
+
* '''%S''' - seconds
  
Например:
+
For example:
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
date()  // 17/05/2022 18:16:31 т.е. сейчас
+
date()  // 17/05/2022 18:16:31 it means now
 
date('%Y.%m.%d %H:%M:%S')  // 2022.05.17 18:16:31
 
date('%Y.%m.%d %H:%M:%S')  // 2022.05.17 18:16:31
 
</syntaxhighlight>
 
</syntaxhighlight>

Latest revision as of 17:04, 1 July 2022

Qubot Script

Qubot Script - is a programming language used to perform logical and mathematical operations while solving bot tasks

Slots

Slot - is a variable whose value is available in all states of the bot. Also, the value of the slot is saved if the bot is closed and then the work is continued after a while.

A slot is declared for the first time when values are assigned to it.
For example:

a = 7

A slot named a is declared and the value 7 is assigned to it

Local variables

Unlike slots, local variables are stored only within the script where they are declared.
The declaration is made by adding the keyword local before the name:

local b = 8    // local variable

If a local variable is declared inside curly braces {}, then its value is only available there:

local b = 8    // local variable of the current script

if (b == 8)
{
   local c = 9 // local variable of 'if' statement block
   print(c)    // will output 9
}

print(b)       // will output 8
print(c)       // will give an error, because the variable 'с' is unavailable here

Variable types

sInt = 7                             // Integer
sFloat = 7.3                         // Float 
sStr = "hello"                       // String
sArr = [7, 7.3, "hello", sStr]       // Array
sDic = { n: 1, s: "Wine"  }          // Dictionary
sBool = true                         // Boolean
sRegExp = /[abc]/                    // Regular expression
sNone = none                         // Undefined value

Logical operations

  • and - logical ‘AND’
  • or - logical ‘OR’
  • not - negation ‘NO’


For example:

a = true
b = false
c = true
res = not((a and b) or c)

Arithmetic operations

  • + - addition
  • - - subtraction
  • * - multiplication
  • / - division

For example:

res = 2+3-4*5+(1.5-0.2/2)

Comments

Comments are used to document script fragments. They can be multi-line and single-line:

/*
Example of
    multi-line
        comment
*/

a = 2253 // example of single-line comment

Python style comments are also allowed:

a = 2253 # example of single-line comment


Working with a dictionary (object)

Dictionary declaration:

dic = { n: 1, s: "Wine"  }

Accessing dictionary values:

a = dic.n             // access to field named "n" through dot  
a = dic["n"]          // access a field named "n" via an access statement
dic["food"] = "milk"  // add a key-value pair to a dictionary

Working with arrays

Array declaration:

arr = [1,2,3]         // create an array with three elements with values 1,2,3

Accessing array elements:

first  = arr[0]       // get the first element of array
last   = arr[-1]      // get the last element of an array
last   = arr[-2]      // get the penultimate element of an array
arr[0] = 7            // change the value of the first element

Array Functions:

push(val1,val2...) - add elements with values val1, val2... to the end of the array

arr.push(4) // add the value '4' to the end of the array

unshift(val1,val2...) - add elements with values val1, val2... to the beginning of the array

arr.unshift(0) // add the value '0' to the beginning

pop() - remove the last element of an array and return its value

shift() - remove the first element of an array and return its value

slice(start,end) - return a part of the array starting from the position start and if the variable endis specified, then up to it

splice(start, deleteCount) - delete deleteCount elements from the position start

clear() - clear the array

Dictionary array functions:

find(EXPR) - search for array elements that satisfy the EXPR condition. Found elements are returned as an array.
For example:

arr = [                            // array of three objects with products
  {title: "Wine", price: 120},
  {title: "Cheese", price: 100},
  {title: "Cola", price: 40},
] 

local res = arr.find(price > 80)   // find all objects whose 'price' field is higher than 80 and return them in an array
print('found $res.length:')       // display the number of found objects
print(res)                       // display objects that satisfy the condition


total(EXPR) - apply the expression EXPR to each element of the array and sum all the values.
For example, let's calculate the amount of items in the cart:

arr = [                                 // array of three objects with products
  {title: "Wine", price: 120, amount: 3},
  {title: "Pizza", price: 100, amount: 2},
  {title: "Cola", price: 40, amount: 3},
] 

local res = arr.total(price * amount)   // for each element of the array, multiply the price by the quantity and add the result
print("To pay: $res UAH")               // display the cost of goods: "To pay: 680 UAH"

count(EXPR) - find the number of array elements for which the expression EXPR is true

arr = [                                 // array of three objects with products
  {title: "Wine", price: 120, amount: 3},
  {title: "Pizza", price: 100, amount: 2},
  {title: "Cola", price: 40, amount: 3},
] 

local res = arr.count(price < 100)    // for each element of the array, multiply the price by the quantity and add the result
print("The quantity of goods that is cheaper than 100 UAH: $res")  // display the number of goods: "The quantity of goods that is cheaper than 100 UAH: 1"

sort(KEY) - sort array

Only arrays are supported where all values are of the same type: a number or string for sort() and a dictionary for sort(key)

list = [1, 3, 2] // array of numbers
str  = ["a", "hi", "banana"] // string array
arr  = [         // array of dictionaries with products
  {title: "Wine", price: 120, amount: 3},
  {title: "Pizza", price: 100, amount: 2},
] 

list.sort()        // sort array in ascending order
 str.sort()        // sort array in ascending order
 arr.sort(price)   // sort array of objects by key 'price'
// TODO

reverse() - flip array

list = [1, 3, 2]  // array 

list.reverse()    // [2, 3, 1]


Working with strings

Declaration of string slots:

str = "hello"           // using double quotes
str = 'hello'           // using single quotes

String operations:

base = 'http://imgs/'
url = base + 'img1.png' // string addition

Substitution of slots in strings:

a = 5
str = "a = $a"          // instead of $a the value of slot a will be substituted
print(str)              // will output: "a = 5"

Inserting expressions into strings:

Expressions can be inserted into strings by framing them with curly braces:

str = "2 + 3 = {2+3}"   // evaluate the expression and insert the result into a string
print(str)              // will output: "2 + 3 = 5"

Shielding special characters '$','{','}' is done by adding a slash '\'

str = "price: 4.99\$ \{sale\}"   // evaluate the expression and insert the result into a string
print(str)                       // will output: "price: 4.99$ {sale}"

String Functions:

length - get string length

str = "hello"
len = str.length           // return 5 - the number of characters in the string "hello"

substring(start,end) - get a substring starting from position start up to end position, not including it

str = "http://server/im.png"
substr = str.substring(7,13)  // return the string "server"

search(pattern) - find the position of the first occurrence of pattern, otherwise return -1. Argument pattern can be either a string or a regular expression:

str = "apple orange juice"
res = str.search('orange')          // return the position of the string 'orange': 6
res = str.search(/(orange|juice)/)  // return the position of the string 'orange' or 'juice'
res = str.search('pizza')           // will not find 'pizza' and will return -1


Conditional operator

The if statement is used to branch the logic depending on the condition

a = 9
if (a > 7) 
{
    res = 'a more than 7'
}
else
{
    res = 'a less or equal 7'
}

In this example, the condition a > 7 is checked and if it is true, then the first block of the script is executed, that is surrounded by curly braces, otherwise the block after the keyword else is executed

While loop

The loop statement checks the condition and while it is true, executes the code surrounded by curly braces

a = 7
while (a > 0) 
{
    a = a - 1
}

In this example, the script a = a - 1 will be executed until the value of the slot a becomes zero

Iterator for

An iterator is used to loop through all values of an array, or keys from a dictionary

arr = [3,2,1]
for(val in arr)
{
    print(val)
}
output:
3
2
1

In this example, the loop sequentially iterates through the values of the array and puts them into the temporary variable val, respectively, for each element of the array, the script print(val), surrounded by curly braces, is executed, displaying the value in the debug window

Sometimes it is convenient to have an array index in the loop. For this we add the name of the index variable before the value variable:

arr = [3,2,1]
for(i, val in arr)
{
    print("$i: $val")
}
output:
0: 3
1: 2
2: 1

To iterate over the keys and values of a dictionary, a similar construction is used:

arr = {pizza: 100, milk: 20, wine: 120}
for(key, val in arr)
{
    print("$key: $val")
}
output:
pizza: 100
milk: 20
wine: 120

Switch case operator

The switch construct replaces several ifs at once. It is a more visual way to compare an expression against several options at once. It has one or more case block and optional default block.

a = 'one'
switch(a)
{
   case 'one': print('one'); break;
   case 'two': print('two'); break;
   default: print('def')
}

The variable is checked for a strict match to the value to the right of case and if it matches, then the code is executed until it meets break operator.

If none of the case matches, the code to the right of default is executed.

In operator

The in operator checks whether the value is in an array or is a key in a dictionary.

sArr = [7, 7.3, "hello"]             // array
print("hello" in sArr)               // return true, because the value "hello" is present in the array sArr 
sDic = { price: 100, food: "Wine"}   // dictionary
print("food" in sDic)                // return true, because the key "food" is present in the dictionary sDic

The variable is checked for a strict match to the value to the right of case and if it matches, then the code is executed until it meets break operator.

If none of the case matches, the code to the right of default is executed.

Button operator

button(caption){ SCRIPT }
This operator adds a button to the interface with the text caption in the current message. After pressing the button, the SCRIPT logic is executed. If caption is an object, then it must consist of two-letter keys (language identifiers: en, ru,…) with string values in these languages.

button('click me')      // button text
{
    // script that is executed after clicking 
    print('button was clicked!')
    step('STATE_AFTER_CLICK')
}

When the button is clicked, the script will be executed in the context of local variables at the time the button was added, as well as in the context of the slot values at the moment the button was clicked!

Transition functions

run(state) - execute state step logic

step(state) - set default transition step to state

goto(state) - instant jump to state step

Content functions

text(obj) - display text in current message. If obj is a string, then it is output regardless of the current language. If obj is an object, then it must consist of two-letter keys (language identifiers: en, ru,…) with string values in these languages.

text("Hi world!")     
text({ en: "Hi world!", ru: "Привет мир!", es: "¡Hola mundo!"})

images() - create a new line of images. Every following call to image will be added to this line until images() is called again.

URL = "https://qudata.com/qubot/im/"  
images()     
image(URL + "owl_a.png")     
image(URL + "owl_b.png")

image(url, width) - add an image to the current message. If url is a string, then it is used regardless of the current language. If url is an object, then it must consist of two-letter keys (language identifiers: en, ru,…) with string values in these languages. The optional parameter width specifies how much to compress the image as a percentage.

URL = "https://qudata.com/qubot/im/"     
image(URL + "owl_a.png")  
image({ en: URL + "en.png", ru: URL + "ru.png"})

buttons() - create a new row of buttons. Every following call to button will be added to this line until buttons() is called again.

get_check() - get an array of button values of the check type (1 - pressed, 0 - released)

set_check(list) - set the values of check type buttons from the list array.

CHECK = [0,1,0]
set_check(CHECK)

get_radio() - get an array of radio button values (1 - pressed, 0 - released). The unit will be one.

set_radio(list) - set the values of radio type buttons from the list array.

Debugging functions

print(args) - display information in the debug window

Rounding

floor(val) - round numbers down:

floor(5.8)    //  5
floor(-6.1)   // -7

trunc(val) - discard the fractional part:

trunc(5.51)   //  5
trunc(-6.99)  // -6

ceil(val) - round numbers up:

ceil(5.15)    // 6

round(val, num) - round val to num numbers after the decimal point:

round(3.14159265, 2)  // 3.14

Random numbers

randint(min,max) - return an integer random number in the range [min,max].

random() - return an integer random number in the range [0,1].

Date and time

date(format) - return the current date and time in the specified format. By default, the format argument takes the value: %d/%m/%Y %H:%M:%S

Supported format codes:

  • %y - year without a century ('22')
  • %Y - year ('2022')
  • %m - month
  • %d - day
  • %H - hours
  • %M - minutes
  • %S - seconds

For example:

date()  // 17/05/2022 18:16:31 it means now
date('%Y.%m.%d %H:%M:%S')  // 2022.05.17 18:16:31