Qubot Script

From QuData
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

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