Qubot Script

From QuData
Revision as of 10:57, 30 June 2022 by Tkachenko (talk | contribs)
Jump to navigation Jump to search

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

Boolean 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"]          // accessing a field named "n" via an access statement
dic["food"] = "milk"  // adding a key-value pair to a dictionary

Working with arrays

Array declaration:

arr = [1,2,3]         // creates 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) - returns a part of the array starting from the position start and if the variable endis specified, then up to it

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

clear() - clear the array

Dictionary array functions:

find(EXPR) - searches 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('найдено $res.length:')      // will display the number of found objects
print(res)                         // will 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")            // will 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")            // will 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

Объявление строковых слотов:

str = "hello"           // используя двойные кавычки 
str = 'hello'           // используя одинарные кавычки

Операции со строками:

base = 'http://imgs/'
url = base + 'img1.png' // сложение строк

Подстановка слотов в строки:

a = 5
str = "a = $a"          // вместо $a будет подставлено значение слота a
print(str)              // выведет: "a = 5"

Вставка выражений в строки:

Выражения можно вставлять в строки, обрамляя их фигурными скобками:

str = "2 + 3 = {2+3}"   // вычислит выражение и вставит результат в строку
print(str)              // выведет: "2 + 3 = 5"

Экранирование спецсимволов '$','{','}' происходит путем добавления наклонной черты '\'

str = "price: 4.99\$ \{sale\}"   // вычислит выражение и вставит результат в строку
print(str)                       // выведет: "price: 4.99$ {sale}"

Функции работы со строками:

length - получить длинну строки

str = "hello"
len = str.length           // вернет 5 - число символов строки "hello"

substring(start,end) - получить подстроку начиная с позиции start и до позиции end не включая

str = "http://server/im.png"
substr = str.substring(7,13)  // вернет строку "server"

search(pattern) - найти позицию первого вхождения pattern, иначе вернуть -1. Аргумент pattern может быть как строкой так и регулярным выражением:

str = "apple orange juice"
res = str.search('orange')          // вернет позицию строки 'orange': 6
res = str.search(/(orange|juice)/)  // вернет позицию строки 'orange' или 'juice'
res = str.search('pizza')           // не найдет 'pizza' и вернет -1


Условный оператор

Оператор if используется, если необходимо ветвление логики в зависимости от условия

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

В данном примере проверяется условие a > 7 и если оно истинно, то выполняется первый блок скрипта, окруженный фигурными скобками, иначе выполняется блок после служебного слова else

Цикл while

Оператор цикла проверяет условие и пока оно истинно, выполняет код окруженный фигурными скобками

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

В данном примере скрипт a = a - 1 будет выполнятся до тех пор пока значение слота a не станет равным нулю

Итератор for

Итератор используется для перебора всех значений массива, либо ключей из словаря

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

В данном примере цикл последовательно перебирает значения массива и заносит их во временную переменную val соответственно для каждого элемента массива выполняется окруженный фигурными скобками скрипт print(val) выводящий значение в отладочное окно

Иногда удобно в цикле иметь и индекс массива, для этого перед переменной значения добавляем имя переменной индекса:

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

Для перебора ключей и значений словаря используется аналогичная конструкция:

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

Оператор выбора switch

Конструкция switch заменяет собой сразу несколько if. Она представляет собой более наглядный способ сравнить выражение сразу с несколькими вариантами. Имеет один или более блок case и необязательный блок default.

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

Переменная проверяется на строгое соответствие значению справа от case и если оно совпадает, то выполняется код до тех пор пока не встретится оператор break

Если ни одно из case не подошло, выполняется код справа от default

Оператор in

Оператор in проверяет есть ли значение в массиве либо является ключём в словаре.

sArr = [7, 7.3, "hello"]             // массив
print("hello" in sArr)               // вернет true, т.к. значение "hello" присутствует в массиве sArr 
sDic = { price: 100, food: "Wine"}   // словарь
print("food" in sDic)                // вернет true, т.к. ключ "food" присутствует в словаре sDic

Переменная проверяется на строгое соответствие значению справа от case и если оно совпадает, то выполняется код до тех пор пока не встретится оператор break

Если ни одно из case не подошло, выполняется код справа от default

Оператор button

button(caption){ SCRIPT }
Данный оператор добавляет в интерфейс кнопку с текстом caption в текущее сообщение. После нажатия на кнопку выполняется логика SCRIPT. Если caption - объект, то он должен состоять из двухбуквенных ключей (идентификаторов языка: en, ru,…) со строковыми значения на этих языках.

button('click me')      // текст в кнопке
{
    // скрипт, который выполнится после нажатия 
    print('button was clicked!')
    step('STATE_AFTER_CLICK')
}

При нажатии на кнопку скрипт будет выполнен в контексте локальных переменных на момент добавления данной кнопки, а также в контексте значений слотов на момент нажатия на кнопку!

Функции перехода

run(state) - выполнить логику шага state

step(state) - установка шага перехода по умолчанию в значение state

goto(state) - мгновенный переход в шаг state

Функции работы с контентом

text(obj) - вывести в текущее сообщение текст. Если obj - это сторока, то она выводится не зависимо от текущего языка. Если obj - объект, то он должен состоять из двухбуквенных ключей (идентификаторов языка: en, ru,…) со строковыми значения на этих языках.

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

images() - создать новую строку картинок. Каждый последующий вызов image будет добавляться в эту строку, пока снова не будет вызван images().

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

image(url, width) - вывести в текущее сообщение картинку. Если url - это строка, то он используется не зависимо от текущего языка. Если url - объект, то он должен состоять из двухбуквенных ключей (идентификаторов языка: en, ru,…) со строковыми значения на этих языках.. Необязательный параметр width указывает насколько в процентах нужно сжать изображение

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

buttons() - создать новую строку кнопок. Каждый последующий вызов button будет добавляться в эту строку, пока снова не будет вызван buttons().

get_check() - получить массив значений кнопок типа check (1 - нажата, 0 - отжата)

set_check(list) - задать значения кнопок типа check из массива list.

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

get_radio() - получить массив значений кнопок типа radio (1 - нажата, 0 - отжата). Единица будет одна.

set_radio(list) - задать значения кнопок типа radio из массива list.

Отладчные функции

print(args) - вывод информации в окно отладки

Округление

floor(val) - округление чисел в меньшую сторону:

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

trunc(val) - отбрасывание дробной части:

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

ceil(val) - округление чисел в большую сторону:

ceil(5.15)    // 6

round(val, num) - округление val до num чисел после запятой:

round(3.14159265, 2)  // 3.14

Случайные числа

randint(min,max) - возвращает целое случайное число в диапазоне [min,max].

random() - возвращает случайное вещественное число в диапазоне [0,1].

Дата и время

date(format) - возвращает текущую дату и время в указанном формате. По умолчанию аргумент format принимает значение: %d/%m/%Y %H:%M:%S

Поддерживаемые коды форматирования:

  • %y - год без столетия ('22')
  • %Y - год ('2022')
  • %m - месяц
  • %d - день
  • %H - часы
  • %M - минуты
  • %S - секунды

Например:

date()  // 17/05/2022 18:16:31 т.е. сейчас
date('%Y.%m.%d %H:%M:%S')  // 2022.05.17 18:16:31