From 29890e1cd7440a81609a6fbb481b3ee4c5e4cf2f Mon Sep 17 00:00:00 2001 From: aleksversus Date: Sat, 16 Aug 2025 11:17:08 +0500 Subject: [PATCH 01/12] docs(lang/kwrds/syntaxemes): fix unused markdown directive "tips" --- docs/language/qsp-keywords/qsp-keyword-syntaxems.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/language/qsp-keywords/qsp-keyword-syntaxems.md b/docs/language/qsp-keywords/qsp-keyword-syntaxems.md index 469dd47..5ede7fd 100644 --- a/docs/language/qsp-keywords/qsp-keyword-syntaxems.md +++ b/docs/language/qsp-keywords/qsp-keyword-syntaxems.md @@ -4,7 +4,7 @@ sidebar_position: 5 # Синтаксемы и спецсимволы -:::tips[Определение] +:::tip[Определение] В контексте программирования синтаксема может рассматриваться как **минимальная единица синтаксиса**, которая определяет структуру и правила написания кода. From 3718f0270d8939b0823ad6681c7fdb14c1a8d062 Mon Sep 17 00:00:00 2001 From: aleksversus Date: Sat, 16 Aug 2025 11:18:11 +0500 Subject: [PATCH 02/12] docs(lang/kwrds): replace non-breaking spaces --- .../qsp-keywords/qsp-keyword-functions.md | 8 +-- .../qsp-keywords/qsp-keyword-operators.md | 52 +++++++++---------- .../qsp-keywords/qsp-keyword-syntaxems.md | 2 +- 3 files changed, 31 insertions(+), 31 deletions(-) diff --git a/docs/language/qsp-keywords/qsp-keyword-functions.md b/docs/language/qsp-keywords/qsp-keyword-functions.md index a14842a..001bdc5 100644 --- a/docs/language/qsp-keywords/qsp-keyword-functions.md +++ b/docs/language/qsp-keywords/qsp-keyword-functions.md @@ -526,7 +526,7 @@ $qspver('platform') $REPLACE([$строка], [$поиск], [$замена], [#число_замен]) ``` -Данная функция заменяет в строке `[$строка]` несколько вхождений строки `[$поиск]` строкой `[$замена]` и возвращает результат. Замена производится слева-направо и только для непересекающихся вхождений. Параметр `[#число_замен]` показывает, сколько вхождений должно быть заменено. Если параметр не указан, производится замена всех вхождений. Если `[$замена]` отсутствует или указана пустая строка, то удаляет в исходной строке все вхождения искомой строки. Примеры: +Данная функция заменяет в строке `[$строка]` несколько вхождений строки `[$поиск]` строкой `[$замена]` и возвращает результат. Замена производится слева-направо и только для непересекающихся вхождений. Параметр `[#число_замен]` показывает, сколько вхождений должно быть заменено. Если параметр не указан, производится замена всех вхождений. Если `[$замена]` отсутствует или указана пустая строка, то удаляет в исходной строке все вхождения искомой строки. Примеры: ```qsp $replace('test', '12', '4') & ! выведет на экран 'test' @@ -731,7 +731,7 @@ ARRCOMP([$имя_массива], [$шаблон], [#начало]) , где `[#начало]` — номер элемента массива, с которого следует начать поиск, `[$имя_массива]` — название массива, по которому нужно произвести поиск, `[$шаблон]` — регулярное выражение, с которым будет сравниваться искомый элемент. - Параметр `[#начало]` может отсутствовать, при этом его значение принимается равным 0. -- Поиск работает только по текстовым массивам (символ `$` в названии массива можно опустить). +- Поиск работает только по текстовым массивам (символ `$` в названии массива можно опустить). Для примера возьмём вот такой массив: @@ -966,7 +966,7 @@ ARRSIZE([$имя_массива]) , где `[$имя_массива]` — название массива, размер которого хотим получить. -Не имеет значения, указываете ли вы **`$`** перед названием массива или нет. Подсчитывается общее число ячеек и со строковыми, и с числовыми значениями. Для примера: +Не имеет значения, указываете ли вы **`$`** перед названием массива или нет. Подсчитывается общее число ячеек и со строковыми, и с числовыми значениями. Для примера: ```qsp n = ARRSIZE('a') @@ -1121,7 +1121,7 @@ RAND([#выражение 1], [#выражение 2], [#мода]) , где `[#выражение 1]` и `[#выражение 2]` — два любых числа или числовых выражения. -Параметр `[#мода]` позволяет указать число, которое должно выпадать более часто, чем остальные. При этом распределение частоты выпадения будет плавно изменяться для всех остальных чисел, уменьшаясь от моды к пределам выбранного интервала. Если 3й параметр не указан, то функция возвращает случайное число в заданном диапазоне с равномерным/равновероятным распределением чисел. +Параметр `[#мода]` позволяет указать число, которое должно выпадать более часто, чем остальные. При этом распределение частоты выпадения будет плавно изменяться для всех остальных чисел, уменьшаясь от моды к пределам выбранного интервала. Если 3й параметр не указан, то функция возвращает случайное число в заданном диапазоне с равномерным/равновероятным распределением чисел. Параметр `[#выражение 2]` может отсутствовать, при этом он принимается равным `1`. diff --git a/docs/language/qsp-keywords/qsp-keyword-operators.md b/docs/language/qsp-keywords/qsp-keyword-operators.md index e2ceed4..fe14277 100644 --- a/docs/language/qsp-keywords/qsp-keyword-operators.md +++ b/docs/language/qsp-keywords/qsp-keyword-operators.md @@ -581,16 +581,16 @@ IF [#выражение]: END ``` -В данном случае, если верно условие `[#выражение]`, выполняются команды `{команда 1}`, `{команда 2}` и т.д. +В данном случае, если верно условие `[#выражение]`, выполняются команды `{команда 1}`, `{команда 2}` и т.д. -- Для **однострочной формы** записи это будут только те команды, которые идут в той же строке, что и оператор `IF` до конца строки; -- а для **многострочной формы** записи это будут те команды, которые идут в последующих строках после двоеточия и до специального ключевого слова `END`. +- Для **однострочной формы** записи это будут только те команды, которые идут в той же строке, что и оператор `IF` до конца строки; +- а для **многострочной формы** записи это будут те команды, которые идут в последующих строках после двоеточия и до специального ключевого слова `END`. В качестве условия могут выступать операции сравнения, логические операции и иные выражения, возвращающие числовые значения. -Ключевое слово `END` при многострочной форме записи должно стоять отдельной строкой. +Ключевое слово `END` при многострочной форме записи должно стоять отдельной строкой. -Если условие `[#выражение]` не верно, команды выполнены не будут. +Если условие `[#выражение]` не верно, команды выполнены не будут. Примеры однострочной формы записи условий: @@ -703,10 +703,10 @@ if abcd=3: k1=34 else k1=25 end ## ELSE -`ELSE` — ключевое слово, использующееся совместно с оператором `IF`, и которое служит для предоставления альтернативы, если условие не выполнено. Ключевое слово `ELSE` так же имеет две формы записи: однострочную и многострочную. +`ELSE` — ключевое слово, использующееся совместно с оператором `IF`, и которое служит для предоставления альтернативы, если условие не выполнено. Ключевое слово `ELSE` так же имеет две формы записи: однострочную и многострочную. -- Многострочную форму записи `ELSE` можно использовать только в многострочной конструкции оператора `IF`, -- однострочную форму записи можно использовать как в однострочной, так и в многострочной, конструкции оператора `IF`. Общая форма записи: +- Многострочную форму записи `ELSE` можно использовать только в многострочной конструкции оператора `IF`, +- однострочную форму записи можно использовать как в однострочной, так и в многострочной, конструкции оператора `IF`. Общая форма записи: ```qsp ! однострочная форма записи @@ -736,15 +736,15 @@ ELSE {команда н1} & {команда н2} & ... END ``` -Здесь, если условие`[#выражение]` верно, выполняются команды от двоеточия до ключевого слова `ELSE`, а если условие `[#выражение]` не верно, выполняются команды от ключевого слова `ELSE` и до конца конструкции условия. +Здесь, если условие`[#выражение]` верно, выполняются команды от двоеточия до ключевого слова `ELSE`, а если условие `[#выражение]` не верно, выполняются команды от ключевого слова `ELSE` и до конца конструкции условия. -После `ELSE` можно ставить, а можно не ставить двоеточие. +После `ELSE` можно ставить, а можно не ставить двоеточие. **При однострочной форме записи:** -- и команды и ключевое слово `ELSE` должны быть записаны в одной строке +- и команды и ключевое слово `ELSE` должны быть записаны в одной строке - окончанием альтернативного списка команд является конец строки. -- если однострочная форма записи `ELSE` используется в многострочной форме записи `IF`, все команды, которые идут в последующих строках после `ELSE` до `END` игнорируются. +- если однострочная форма записи `ELSE` используется в многострочной форме записи `IF`, все команды, которые идут в последующих строках после `ELSE` до `END` игнорируются. Примеры однострочной записи: @@ -769,7 +769,7 @@ end **При многострочной форме записи:** -- все команды должны идти в последующих строках после `ELSE`; +- все команды должны идти в последующих строках после `ELSE`; Примеры многострочной записи: @@ -795,10 +795,10 @@ end ## ELSEIF -`ELSEIF` — ключевое слово, которое используется совместно с оператором `IF` и позволяет определять на одном уровне вложенности последовательно-исключающие условия. Имеет однострочную и многострочную формы записи. +`ELSEIF` — ключевое слово, которое используется совместно с оператором `IF` и позволяет определять на одном уровне вложенности последовательно-исключающие условия. Имеет однострочную и многострочную формы записи. -- Многострочную форму записи можно использовать только в многострочных конструкциях с оператором `IF`, -- однострочную — как в многострочных, так и в однострочных конструкциях с оператором `IF`. +- Многострочную форму записи можно использовать только в многострочных конструкциях с оператором `IF`, +- однострочную — как в многострочных, так и в однострочных конструкциях с оператором `IF`. Общие формы записи: @@ -830,13 +830,13 @@ ELSE {последний набор команд} END ``` -Работает это следующим образом. Если `[#выражение 1]` верно, выполняются команды `{набор команд 1}`. Если `[#выражение 1]` неверно, но верно `[#выражение 2]`, выполняются команды `{набор команд 2}`, и т.д. И только если неверны все выражения в текущей конструкции условия, выполнятся команды после `ELSE`. Верность выражения `[#выражение 1]` не исключает верности выражения `[#выражение 2]`, однако верность выражения `[#выражение 2]` исключает верность выражения `[#выражение 1]`. +Работает это следующим образом. Если `[#выражение 1]` верно, выполняются команды `{набор команд 1}`. Если `[#выражение 1]` неверно, но верно `[#выражение 2]`, выполняются команды `{набор команд 2}`, и т.д. И только если неверны все выражения в текущей конструкции условия, выполнятся команды после `ELSE`. Верность выражения `[#выражение 1]` не исключает верности выражения `[#выражение 2]`, однако верность выражения `[#выражение 2]` исключает верность выражения `[#выражение 1]`. -Особенности записи `ELSEIF`: +Особенности записи `ELSEIF`: -- Может использоваться вариант написания `ELSE IF`. Работает точно так же. -- Если в многострочной конструкции `IF` после `ELSEIF` операторы идут в той же самой строке (однострочная форма), то все последующие строки игнорируются до следующего `ELSEIF`, либо до `ELSE` или `END`. -- В конструкции `IF` c `ELSEIF` может как присутствовать, так и отсутствовать часть с `ELSE`. +- Может использоваться вариант написания `ELSE IF`. Работает точно так же. +- Если в многострочной конструкции `IF` после `ELSEIF` операторы идут в той же самой строке (однострочная форма), то все последующие строки игнорируются до следующего `ELSEIF`, либо до `ELSE` или `END`. +- В конструкции `IF` c `ELSEIF` может как присутствовать, так и отсутствовать часть с `ELSE`. Примеры: @@ -860,7 +860,7 @@ elseif money mod 10=0 or money mod 10>4 or (money mod 100>10 and money mod 100<2 end ``` -Пример записи `ELSEIF` с операторами в той же строке: +Пример записи `ELSEIF` с операторами в той же строке: ```qsp ! реализация switch/case на QSP @@ -1118,7 +1118,7 @@ local arr Собственные локальные переменные можно создавать в следующих блоках кода: - Локации сами по себе. -- Код, передаваемый оператору `DYNAMIC`, или функции `DYNEVAL`, в виде текста. +- Код, передаваемый оператору `DYNAMIC`, или функции `DYNEVAL`, в виде текста. - Код, выполняемый при нажатии на гиперссылку. - Код каждого отдельного Действия ([ACT](qsp-keyword-operators.md#act)). - Код каждого отдельного Цикла ([LOOP](qsp-keyword-operators.md#loop)) @@ -1307,7 +1307,7 @@ MENU [$название массива] Здесь название массива (`%stone`) - это название меню, а кортежи - действия, для которых указаны названия пунктов и названия локаций-обработчиков выбора пунктов меню. При выборе пункта "Взять камень" произойдёт вызов локации с названием "takestone". Аналогично будет происходить с другими пунктами. -Чтобы вывести меню на экран, нужно воспользоваться оператором `MENU`: +Чтобы вывести меню на экран, нужно воспользоваться оператором `MENU`: ```qsp menu '%stone' @@ -1866,11 +1866,11 @@ showstat off & ! скрывает окно дополнительного опи SORTARR [$имя_массива], [#порядок] ``` - Здесь `[$имя_массива]` — название массива, который нужно отсортировать. Параметр `[#порядок]` можно не указывать. Если не указан или равен `0`, то сортирует массив по возрастанию (от меньшего к большему). Если равен `1`, то сортирует массив по убыванию (от большего к меньшему). + Здесь `[$имя_массива]` — название массива, который нужно отсортировать. Параметр `[#порядок]` можно не указывать. Если не указан или равен `0`, то сортирует массив по возрастанию (от меньшего к большему). Если равен `1`, то сортирует массив по убыванию (от большего к меньшему). Может сортировать массивы любых типов (числа, строки, кортежи), но не допускается смешивать значения разных типов в одном массиве. -Для указания типа сортируемых значений нужно указать префикс типа как часть имени массива (`$`, `%`). +Для указания типа сортируемых значений нужно указать префикс типа как часть имени массива (`$`, `%`). Пример сортировки текстового массива: diff --git a/docs/language/qsp-keywords/qsp-keyword-syntaxems.md b/docs/language/qsp-keywords/qsp-keyword-syntaxems.md index 5ede7fd..7190207 100644 --- a/docs/language/qsp-keywords/qsp-keyword-syntaxems.md +++ b/docs/language/qsp-keywords/qsp-keyword-syntaxems.md @@ -6,7 +6,7 @@ sidebar_position: 5 :::tip[Определение] -В контексте программирования синтаксема может рассматриваться как **минимальная единица синтаксиса**, которая определяет структуру и правила написания кода. +В контексте программирования синтаксема может рассматриваться как **минимальная единица синтаксиса**, которая определяет структуру и правила написания кода. Так синтаксемой может быть переменная, оператор, функция, ключевое слово объявления, или специальные символы, с помощью которых мы структурируем код. From ed71faae62be27f7b6bf3879a895c3de40946982 Mon Sep 17 00:00:00 2001 From: aleksversus Date: Sat, 16 Aug 2025 11:36:24 +0500 Subject: [PATCH 03/12] docs(lang/kwrds/operators): fill miss info of set/let-multiple assign --- .../qsp-keywords/qsp-keyword-operators.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/docs/language/qsp-keywords/qsp-keyword-operators.md b/docs/language/qsp-keywords/qsp-keyword-operators.md index fe14277..fdbf33b 100644 --- a/docs/language/qsp-keywords/qsp-keyword-operators.md +++ b/docs/language/qsp-keywords/qsp-keyword-operators.md @@ -1043,10 +1043,11 @@ KILLVAR 'a', 1 ## LET -`LET` — устаревший оператор для установки значения переменной. Общая запись: +`LET` — устаревший оператор для установки значения переменных. Общая запись: ```qsp LET [название переменной] = [выражение] +LET [переменная 1], [переменная 2], ... = [значение 1], [значение 2], ... ``` , где `[название переменной]` — это допустимое имя переменной, `[выражение]` — это допустимое для данной переменной значение. @@ -1064,13 +1065,17 @@ let $text = "text string" let abs = 123 ! задаём кортеж let %tuple = [123, "text string"] +! множественное присваивание +let unit_power, $unit_name = 1300, 'DiggerBull' +! распаковка кортежа +let $name, age, height = %npc_fields ``` :::tip Данный оператор считается устаревшим. Используйте вместо него оператор `set`, и только в тех случаях, когда это улучшит читаемость кода. ```qsp -! присвоение можно проводить без операторов set или let: +! присвоение можно проводить без операторов `set` или `let`: $text = "text string" ``` @@ -1661,10 +1666,11 @@ scanstr '$words', $text, '\[(.*?)\]', 1 ## SET -`SET` — оператор для установки значения переменной. Общая запись: +`SET` — оператор для установки значения переменных. Общая запись: ```qsp SET [название переменной] = [выражение] +SET [переменная 1], [переменная 2], ... = [значение 1], [значение 2], ... ``` , где `[название переменной]` — это допустимое имя переменной, `[выражение]` — это допустимое для данной переменной значение. @@ -1678,6 +1684,10 @@ set $text = "text string" set abs = 123 ! задаём кортеж set %tuple = [27, 184, 'steel'] +! множественное присваивание +set unit_power, $unit_name = 1300, 'DiggerBull' +! распаковка кортежа +set $name, age, height = %npc_fields ``` :::note[Рекомендация:] From 5a8ced0a2a59ad30fefd7de1704e8064fe41d695 Mon Sep 17 00:00:00 2001 From: aleksversus Date: Sat, 16 Aug 2025 12:35:38 +0500 Subject: [PATCH 04/12] docs(EN:lang/kwrds): replace header of contents, fix md-alarms --- .../qsp-keywords/qsp-keyword-functions.md | 1 + .../qsp-keywords/qsp-keyword-functions.md | 1147 +++++++---------- .../qsp-keywords/qsp-keyword-operacion.md | 2 +- .../qsp-keywords/qsp-keyword-operators.md | 2 +- .../qsp-keywords/qsp-keyword-syntaxems.md | 4 +- 5 files changed, 464 insertions(+), 692 deletions(-) diff --git a/docs/language/qsp-keywords/qsp-keyword-functions.md b/docs/language/qsp-keywords/qsp-keyword-functions.md index 001bdc5..b154a4b 100644 --- a/docs/language/qsp-keywords/qsp-keyword-functions.md +++ b/docs/language/qsp-keywords/qsp-keyword-functions.md @@ -927,6 +927,7 @@ ARRPOS([#начало], [$имя_массива], [$шаблон]) ## ARRTYPE `ARRTYPE` — возвращает тип значения, хранящегося в переменной, или указанной ячейке массива. Тип возвращается в виде одного из следующих значений: + - `''` (пустая строка) — значение не определено (например, для неинициализированных переменных); - `'#'` — переменная содержит число; - `'$'` — переменная содержит строку; diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md index ceda974..1ee94f8 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md @@ -239,123 +239,6 @@ loop local i = 1 while i <= countobj step i += 1: end ``` -## `$QSPVER` - -`$QSPVER` - returns the interpreter version in the format "X.Y.Z Player". For example, classic player version 5.8.0 returns the value "5.8.0 (classic)", and qSpider simply "5.8.0". Usage example: - -```qsp -if $qspver < "5.8.0": - *pl "Your player version is not suitable for this game." - *pl "Install player version 5.8.0 or higher." -end -``` - -This function can also return the platform on which the game is running if you specify "platform" as an argument: - -```qsp -$qspver('platform') -``` - -:::note[5.7.0] - -In older player versions, the function returned only the interpreter version (libqsp library). - -::: - -## `$SELACT` - -`$SELACT` — returns the name of the selected action anywhere in the game. - -Remember that action selection occurs when hovering the mouse pointer over it, not when directly clicking. - -Most often this function is used to remove the current action: - -```qsp -act "Eat apple": - *pl "It was a very tasty apple. Too bad it was wormy." - health += 100 - delact $selact -end -``` - -Also see usage examples in the [`$onactsel`](qsp-keyword-sys-var.md#onactsel) section - -## `$SELOBJ` - -`$SELOBJ` — returns the name of the selected object anywhere in the game. Object selection occurs when clicking (mouse click on object) and is not removed until the `unselect` command is applied. - -Usage examples can be found in the [`$onobjsel`](qsp-keyword-sys-var.md#onobjsel) section - -## `$STATTXT` - -`$STATTXT` — returns text output to the additional description window. Can be useful for replacing part of text in the additional description window. - -Example: - -```qsp -p 'The Ship Carried Caramel' -nl 'The Ship Hit a Shoal' -$string = $stattxt -``` - -## `$USER_TEXT` - -`$USER_TEXT` — anywhere in the game returns text that is in the input line (input field). Has the short form `$usrtxt`. - -Example of an action that will output text entered in the input line to the additional description window when clicked: - -```qsp -act "What did I write?": pl 'I wrote: "<<$user_text>>".' -``` - -A more common example is presented in the [`$usercom`](qsp-keyword-sys-var.md#usercom) section. - -## COUNTOBJ - -`COUNTOBJ` — returns the number of items in inventory. - -The number of the last item in the list numerically matches the number of items, so you can always get the name of the last item like this: - -```qsp -$getobj(countobj) -``` - -## MSECSCOUNT - -`MSECSCOUNT` — returns the number of milliseconds elapsed since the game started. This function, when used at the counter location, allows organizing various events occurring in real time. Also, with this function you can measure performance of various code sections in your game: - -```qsp -i = 0 -old_time = msecscount -:for -if i < 100000: - d[i] = i - i += 1 - jump 'for' -end -new_time = msecscount -pl "Old loop performance: " + $str(new_time - old_time) - -old_time = msecscount -loop i = 0 while i < 100000 step i += 1: - b[i] = i -end -new_time = msecscount -pl "New loop performance: " + $str(new_time - old_time) -``` - -:::note -The maximum number this function can return is `2147483647`. It's not hard to calculate that this is enough for more than **550** hours of gameplay. -::: - -## RND - -`RND` - returns a random value from `1` to `1000`. Analogous to the command: - -```qsp -rand(1, 1000) -``` - ## `$IIF` `IIF` — returns a value depending on expression truth. @@ -507,6 +390,46 @@ $text_new = $replace($text, " and in this string there's a piece we want to remo *p $text_new ``` +## `$MAX` + +`MAX` — returns the maximum of expression-argument values. You can pass from one to twenty values/arguments. If one argument is passed, it's considered that an array name is specified. General syntax: + +```qsp +MAX([#expression 1], [#expression 2], ... , [#expression 20]) +$MAX([$expression 1], [$expression 2], ... , [$expression 20]) + +MAX([$array_name]) +$MAX([$array_name]) +``` + +Note, when passing one argument, the search for maximum element occurs among string (if array name is specified with `$` sign) or among numeric values of array elements. For example: + +```qsp +max('a') & ! returns maximum of numeric values of "a" array elements +$max('$b') & ! returns maximum of string values of "b" array elements +``` + +You can't write like this and expect search among array `a` values: + +```qsp +max(a) +``` + +You can do this: + +```qsp +$b = 'a' +max($b) & ! search for maximum value among elements of "a" array will occur +``` + +Other examples: + +```qsp +max(1, 2, 5, 2, 0) &! returns 5 +max(a, b, c) &! returns maximum of variable values a,b,c +$max('aa', 'ab', 'zz') &! returns 'zz' +``` + ## `$MID` `$MID` — allows cutting a part from a string. General syntax: @@ -530,6 +453,71 @@ $mid('abcdef', 0) & ! 'abcdef' $mid('abcdef', 8) & ! '' ``` +## `$MIN` + +`MIN` — returns the minimum of expression-argument values. You can pass from one to twenty values/arguments. If one argument is passed, it's considered that an array name is specified. General syntax: + +```qsp +MIN([#expression 1], [#expression 2], ... , [#expression 20]) +$MIN([$expression 1], [$expression 2], ... , [$expression 20]) +``` + +```qsp +MIN([$array_name]) +$MIN([$array_name]) +``` + +Note, when passing one argument, the search for minimum element occurs among string (if array name is specified with `$` sign) or among numeric values of array elements. For example: + +```qsp +min('a') & ! returns minimum of numeric values of "a" array elements +$min('$b') & ! returns minimum of string values of "b" array elements +``` + +You can't write like this: + +```qsp +min(a) +``` + +You can do this: + +```qsp +$b = 'a' +min($b) & ! search for maximum value among elements of "a" array will occur +``` + +Other examples: + +```qsp +min(1, 2, 5, 2, 0) & ! returns 0 +min(a, b, c) & ! returns minimum of variable values a,b,c +$min('aa', 'ab', 'zz') & ! returns 'aa' +``` + +## `$QSPVER` + +`$QSPVER` - returns the interpreter version in the format "X.Y.Z Player". For example, classic player version 5.8.0 returns the value "5.8.0 (classic)", and qSpider simply "5.8.0". Usage example: + +```qsp +if $qspver < "5.8.0": + *pl "Your player version is not suitable for this game." + *pl "Install player version 5.8.0 or higher." +end +``` + +This function can also return the platform on which the game is running if you specify "platform" as an argument: + +```qsp +$qspver('platform') +``` + +:::note[5.7.0] + +In older player versions, the function returned only the interpreter version (libqsp library). + +::: + ## `$REPLACE` `$REPLACE` — general syntax: @@ -559,78 +547,73 @@ $text_new = $replace($text, "st", "st") *pl $text_new ``` -## `$STR` +## `$SELACT` -`$STR` — returns a text string obtained by converting a number to string. General syntax: +`$SELACT` — returns the name of the selected action anywhere in the game. -```qsp -$STR([#number]) -``` +Remember that action selection occurs when hovering the mouse pointer over it, not when directly clicking. -Example: +Most often this function is used to remove the current action: ```qsp -$str(56) & ! converts number 56 to string "56" and outputs to screen +act "Eat apple": + *pl "It was a very tasty apple. Too bad it was wormy." + health += 100 + delact $selact +end ``` -## `$STRFIND` +Also see usage examples in the [`$onactsel`](qsp-keyword-sys-var.md#onactsel) section -`$STRFIND` — returns a substring matching a regular expression from the specified string. General syntax: +## `$SELOBJ` -```qsp -$STRFIND([$string], [$pattern], [#number]) -``` +`$SELOBJ` — returns the name of the selected object anywhere in the game. Object selection occurs when clicking (mouse click on object) and is not removed until the `unselect` command is applied. -, where `[$string]` — source string in which we search for an occurrence matching regular expression `[$pattern]`, or group number `[#number]` in the regular expression. If substring with specified number is absent, an empty string is returned. Group numbering starts from 1. If parameter `[#number]` is absent or equals 0, the substring matching the entire regular expression `[$pattern]` is returned. +Usage examples can be found in the [`$onobjsel`](qsp-keyword-sys-var.md#onobjsel) section -For example, let's take the regular expression: +## `$STATTXT` -```regex -^(\S+)\s(\S+)\s(\S+)$ -``` +`$STATTXT` — returns text output to the additional description window. Can be useful for replacing part of text in the additional description window. -The `\S` metacharacter means any non-whitespace character, and the `+` quantifier indicates that non-whitespace characters must be present one or more times. Thus the notation `\S+` can be conditionally matched to a word. Each word is enclosed in separate groups using parentheses `()`, and whitespace characters `\s` are present between groups. The `^` and `## `$IIF` - -`IIF` — returns a value depending on expression truth. - -General syntax: +Example: ```qsp -IIF([#expression], [#expression_yes], [#expression_no]) -$IIF([#expression], [$expression_yes], [$expression_no]) +p 'The Ship Carried Caramel' +nl 'The Ship Hit a Shoal' +$string = $stattxt ``` -If `[#expression]` is true, returns the value of expression `[expression_yes]`, otherwise returns the value of expression `[expression_no]`. - -Only one of the expressions `[expression_yes]` and `[expression_no]` will be calculated, depending on whether the condition is met. +## `$STR` -Examples: +`$STR` — returns a text string obtained by converting a number to string. General syntax: ```qsp -!Absolute value of number -abs_x = iif(x>0, x, -x) +$STR([#number]) +``` -!And the following construct will NOT cause division by zero error: -x = 0 -y = iif(x = 0, 0, 1/x) +Example: -! typical solution for outputting time so as not to lose zero on hours: -$iif(hour>9, $str(hour), "0"+$str(hour)) + ":"+$iif(minute>9, $str(minute), "0"+$str(minute)) +```qsp +$str(56) & ! converts number 56 to string "56" and outputs to screen ``` -Equivalence of conditional constructs with `IF` operator and `IIF` function: +## `$STRFIND` + +`$STRFIND` — returns a substring matching a regular expression from the specified string. General syntax: ```qsp -if number mod 2 = 0: - *pl "Number is even" -else - *pl "Number is odd" -end -! equivalent to -*pl $iif(number mod 2 = 0,"Number is even","Number is odd") +$STRFIND([$string], [$pattern], [#number]) +``` + +, where `[$string]` — source string in which we search for an occurrence matching regular expression `[$pattern]`, or group number `[#number]` in the regular expression. If substring with specified number is absent, an empty string is returned. Group numbering starts from 1. If parameter `[#number]` is absent or equals 0, the substring matching the entire regular expression `[$pattern]` is returned. + +For example, let's take the regular expression: + +```regex +^(\S+)\s(\S+)\s(\S+)$ ``` - metacharacters mean the beginning and end of string respectively. Thus our regular expression matches any string of three words separated by spaces. +The `\S` metacharacter means any non-whitespace character, and the `+` quantifier indicates that non-whitespace characters must be present one or more times. Thus the notation `\S+` can be conditionally matched to a word. Each word is enclosed in separate groups using parentheses `()`, and whitespace characters `\s` are present between groups. The `^` and `$` metacharacters mean the beginning and end of string respectively. Thus our regular expression matches any string of three words separated by spaces. Then: @@ -725,549 +708,196 @@ $ucase('Hello, Alice!') & ! returns 'HELLO, ALICE!' $ucase('I want to shout at you.') & ! returns 'I WANT TO SHOUT AT YOU.' ``` -## INSTR +## `$USER_TEXT` -`INSTR` — returns the character number from which the substring occurrence begins in the string. General syntax: +`$USER_TEXT` — anywhere in the game returns text that is in the input line (input field). Has the short form `$usrtxt`. + +Example of an action that will output text entered in the input line to the additional description window when clicked: ```qsp -INSTR([$string], [$substring], [#start]) +act "What did I write?": pl 'I wrote: "<<$user_text>>".' ``` -, where `[#start]` — the character number from which to start the search, `[$string]` — text value (string) in which to search, and `[$substring]` — value we're looking for in the specified string. Character numbering starts from `1`. The `[#start]` parameter can be absent, in which case it's taken as 1. +A more common example is presented in the [`$usercom`](qsp-keyword-sys-var.md#usercom) section. -Examples: +## ARRCOMP + +`ARRCOMP` — returns the index of array element matching a regular expression. Search starts from element with specified number; array element indexing starts from zero. If the specified value is not found, the function returns -1. General syntax: ```qsp -instr('abcdefabcdef', 'bc', 3) & ! returns number 8 -instr('abcdefghijklm', 'abc') & ! returns number 1 +ARRCOMP([$array_name], [$pattern], [#start]) ``` -If no occurrence of the specified substring is found in the string, `instr` returns `0`. - -Example: +, where `[#start]` — array element number from which to start search, `[$array_name]` — array name to search in, `[$pattern]` — regular expression to compare the searched element with. -```qsp -instr('Vasya left the house.', 'go') & ! returns 0 -``` +- The `[#start]` parameter can be absent, in which case its value is taken as 0. +- Search works only on text arrays (the `$` symbol in array name can be omitted). -:::note[5.7.0] -In older player versions, the `[#start]` parameter was specified first: +For example, let's take this array: ```qsp -INSTR([#start], [$string], [$substring]) +$mass[0] = "stomp forward" +$mass[1] = " go to cave" +$mass[2] = "don't go to cave" +$mass[3] = "stomp to house" ``` -::: +We need to find an element whose value consists of three words. Roughly speaking, a word is a set of one or more non-whitespace characters `\S+`, which can be surrounded by whitespace characters `\s`, so we can compose this regular expression: -## ISNUM +```regex +\s?\S+\s\S+\s\S+\s? +``` -`ISNUM` — function returns `1` (true) if the passed string is a number, and `0` if the string is not a number. General syntax: +Now we just need to find out which array element matches the pattern: ```qsp -ISNUM([$string]) +arrcomp('$mass', '\s?\S+\s\S+\s\S+\s?') & ! the first element matches this expression ``` -, where `[$string]` — any text string. +If we want to ignore the first element and start search from the second: -The check takes into account the `-` sign at the beginning, adjacent spaces and tab characters, but if at least one character turns out not to be a digit, the function will return `0` (false). +```qsp +arrcomp('$mass', '\s?\S+\s\S+\s\S+\s?', 2) & ! the third element matches this expression +``` -Examples: +And this is how we can output all element values containing the word "go": ```qsp -isnum(' 9999 ') & ! returns 1 -isnum(' -888') & ! returns 1 -isnum('777a6') & ! returns 0 -isnum('') & ! returns 0, since empty string contains no number +loop local pos, index = 0, 0 while 1: + index = arrcomp('$mass', '(.*\s|^)go(\s.*|$)', pos) + if index <> -1: + $mass[index] + pos = index + 1 + else: + jump 'break' + end +end +:break ``` -## ISPLAY - -`ISPLAY` — function checks if a file with the specified name is currently playing, and if it is, returns `1`. Otherwise the function returns `0`. General syntax: +Other examples: ```qsp -ISPLAY([$file_path]) +! Search for string 'This' among elements of array "$A" +arrcomp('$A', 'This', 0) +! Search for string matching regular expression "abc\d+" +! (first two array elements are ignored) +arrcomp('$A', 'abc\d+', 2) +! similar to previous example, +! but search is performed on all array elements +arrcomp('$A', '.*string.*', 0) + +arrcomp('$A', 'This') & ! equivalent to 1st variant ``` -, where `[$file_path]` — path to sound file relative to game file. +:::warning[Attention!] +The function returns only the numeric index of the element. String or multi-dimensional index cannot be obtained with this function. +::: -Example: +## ARRITEM + +`ARRITEM` — returns the value of array element at specified index. General syntax: ```qsp -if isplay('music/mountsound.mp3'): - *pl 'Music is playing.' -else - *pl 'Music is not playing.' -end +ARRITEM([$array_name], [element_index]) ``` -## LEN +, where `[$array_name]` — the name of the array whose element we want to get, and `[element_index]` — numeric, text, or multi-dimensional index. -`LEN` — returns the length of the specified text string (number of characters). General syntax: +In other words, the function extracts a value from the specified array cell. Examples: ```qsp -LEN([$text]) +! output value of element with index 3 +*pl $arritem('$mass', 3) +! output value of element with text index +*pl $arritem('$mass', 'Pete') +! output value of element with multi-dimensional index +*pl $arritem('$mass', [-2, 9, 0]) ``` -, where `[$text]` — any text value. - -Examples: +This function can be useful for extracting values when the array name is not known in advance. Example: -```qsp -len("abc") & ! returns value 3 -len("thousand-nine-hundred-eighty-nine-millimeter") & ! returns value 46 -len("") & ! returns value 0 +```qsp title="Output contents of several arrays without using DYNAMIC" +$array_name[] = 'mass_1' +$array_name[] = 'mass_2' +$array_name[] = 'mass_3' +$array_name[] = 'mass_4' +$array_name[] = 'mass_5' +! outer loop iterates through array names +loop local j = 0 while j < arrsize('$array_name') step j += 1: + ! inner loop outputs array contents + loop local i = 0 while i < arrsize($array_name[j]) step i += 1: + *pl arritem($array_name[j], i) + end +end ``` -## STRCOMP +## %ARRPACK -`STRCOMP` — compares a string with a regular expression and, if the string matches the regular expression, returns `1` (true), and if it doesn't match — `0` (false). General syntax: +`ARRPACK` — returns a tuple into which values from the specified array are packed. + +General syntax: ```qsp -STRCOMP([$string], [$pattern]) +%ARRPACK([$array_name], [#start_index], [#count]) ``` -, where `[$string]` — any text value, `[$pattern]` — regular expression to compare with. +, where `[#start_index]` - the number of array element `[$array_name]` from which to start selecting elements for packing; `[#count]` — the number of elements to be packed into the tuple. -For example, we need to check if the specified string consists of three words. Each word, roughly speaking, is a set of non-whitespace characters, so we can use the `\S` metacharacter with the `+` quantifier. Words are usually separated by whitespace characters, for which we use the `\s` metacharacter. We get this regular expression: +This function allows shortening the command for extracting arguments from `args`: -```regex -\s?\S+\s+\S+\s+\S+\s? +```qsp +! instead of: +local type, name = args[0], args[1] +! you can write like this: +local type, name = arrpack('args') ``` -Now we can check which strings match this regular expression: +It can also be convenient if you need to quickly view array contents or part of it: ```qsp -strcomp('go along road', '\s?\S+\s+\S+\s+\S+\s?') & ! returns 1 -strcomp(' go home', '\s?\S+\s+\S+\s+\S+\s?') & ! returns 0 -strcomp(' go to forest ', '\s?\S+\s+\S+\s+\S+\s?') & ! returns 1 -strcomp('oneword', '\s?\S+\s+\S+\s+\S+\s?') & ! returns 0 +! view values in array without using loop: +*pl %arrpack('massive', 11, 10) & ! we'll see ten elements starting from 11th, as a tuple on screen ``` -## STRPOS +## ARRPOS -`STRPOS` — returns the position of the character from which the substring occurrence matching the regular expression begins in the specified string. General syntax: +`ARRPOS` — returns the index of array element equal to specified value. Search starts from element with specified number; array element indexing starts from zero. If the specified value is not found, the function returns -1. + +General syntax: ```qsp -STRPOS([$string], [$pattern], [#number]) +ARRPOS([$array_name], [value], [#start]) ``` -, where `[$string]` — source string in which we search for an occurrence matching regular expression `[$pattern]`, or group number `[#number]` in the regular expression. Group numbering in regular expression starts from 1. If substring with specified number is absent, `0` is returned. - -If parameter `[#number]` is absent or equals `0`, the position of the character from which the substring occurrence matching the entire regular expression begins is returned. - -For example, we need to find out in which part of the text the phrase "green apple" occurs, but the case of this adjective shouldn't matter. +, where `[#start]` — array element number from which to start search, `[$array_name]` — array name to search in, `[value]` — number or string (depending on array type) to find in the array. -To write a regular expression for this task, we need to account for all cases: +For example, let's take this array: -```plain -green apple -green apple -green apple -green apple -green apple -green apple +```qsp +$color[0] = 'red' +$color[1] = 'yellow' +$color[2] = 'green' +$color[3] = 'blue' +$color[4] = 'yellow' ``` -As we can see, only word endings change in all forms. Therefore we can compose this regular expression: +We need to find element with value "yellow": -```regex -green(oe|ogo|omu|ym|om)\s+apple(o|a|u|om|e) +```qsp +arrpos('$color', 'yellow') & ! returns value 1 ``` -Possible ending variants are listed through a vertical bar in parentheses. And now let's find out from which character in the string the possible phrase "green apple" begins: +If we want to ignore the first two elements: ```qsp -! for convenience we put the regular expression in a variable -$regexp = "green(oe|ogo|omu|ym|om)\s+apple(o|a|u|om|e)" -strpos("I have a green apple", $regexp) & ! returns 13 -strpos("You threw a green apple at him!", $regexp) & ! returns 19 -strpos("full box of green apples", $regexp) & ! returns 0, because we didn't account for this form +arrpos('$color', 'yellow', 2) & ! returns value 4 ``` -If we don't just want to know from which character the phrase occurrence begins in the string, but specifically where the word "apple" from this phrase begins, we need to put the word "apple" with ending variants in a separate group and use the `[#number]` parameter: +If we want to find element with value that doesn't exist in the array: ```qsp -$regexp = "green(oe|ogo|omu|ym|om)\s+(apple(o|a|u|om|e))" -strpos("I have a green apple", $regexp, 2) & ! returns 21 -strpos("You threw a green apple at him!", $regexp, 2) & ! returns 27 -strpos("full box of green apples", $regexp, 2) & ! returns 0, because we didn't account for the form -``` - -Other examples: - -```qsp title="Working with groups" -!------'----5--8------15--' -STRPOS('+33-671-190-23-999', '\+\d{1,2}-(\d{3})((-\d+)+)',1) &! we'll see 5 on screen -STRPOS('+33-671-190-23-999', '\+\d{1,2}-(\d{3})((-\d+)+)',2) &! we'll see 8 on screen -STRPOS('+33-671-190-23-999', '\+\d{1,2}-(\d{3})((-\d+)+)',3) &! we'll see 15 on screen -``` - -```qsp title="Searching for number in string without number" -STRPOS('Eight green apples in basket','\d+') &! 0 will be on screen -``` - -```qsp -STRPOS('go to cave', '^(\S+)\s(\S+)\s(\S+), 0) &! 1 -STRPOS(' go to cave', '^(\S+)\s(\S+)\s(\S+), 0) &! 0 -STRPOS('go to cave', '^(\S+)\s(\S+)\s(\S+), 1) &! 1 -STRPOS('go to cave', '^(\S+)\s(\S+)\s(\S+), 2) &! 6 -STRPOS('go to cave', '^(\S+)\s(\S+)\s(\S+), 3) &! 8 -STRPOS('go to cave', '^(\S+)\s(\S+)(\s(\S+))?, 4) &! 8 -STRPOS('go to house', 'to\s(\S+)', 0) &! 6 -STRPOS('go to house', 'to\s(\S+)') &! 6 -STRPOS('go to house', 'to\s(\S+)', 1) &! 8 -STRPOS('go to my house', 'to\s(\S+)', 1) &! 8 -``` - -## VAL - -`VAL` — converts the specified digit string to corresponding number. General syntax: - -```qsp -VAL([$expression]) -``` - -, where `[$expression]` — any text string. - -The check takes into account the `-` sign at the beginning, adjacent spaces and tab characters, but if at least one character turns out not to be a digit, the function will return `0`. Also if `[$expression]` equals `''` (empty string), `0` is returned. - -Examples: - -```qsp -apples = val($apples) - -val('123') & ! we'll see 123 -val('') & ! we'll see 0 -val('sand') & ! we'll see 0 -``` - -## `$MAX` - -`MAX` — returns the maximum of expression-argument values. You can pass from one to twenty values/arguments. If one argument is passed, it's considered that an array name is specified. General syntax: - -```qsp -MAX([#expression 1], [#expression 2], ... , [#expression 20]) -$MAX([$expression 1], [$expression 2], ... , [$expression 20]) - -MAX([$array_name]) -$MAX([$array_name]) -``` - -Note, when passing one argument, the search for maximum element occurs among string (if array name is specified with `$` sign) or among numeric values of array elements. For example: - -```qsp -max('a') & ! returns maximum of numeric values of "a" array elements -$max('$b') & ! returns maximum of string values of "b" array elements -``` - -You can't write like this and expect search among array `a` values: - -```qsp -max(a) -``` - -You can do this: - -```qsp -$b = 'a' -max($b) & ! search for maximum value among elements of "a" array will occur -``` - -Other examples: - -```qsp -max(1, 2, 5, 2, 0) &! returns 5 -max(a, b, c) &! returns maximum of variable values a,b,c -$max('aa', 'ab', 'zz') &! returns 'zz' -``` - -## `$MIN` - -`MIN` — returns the minimum of expression-argument values. You can pass from one to twenty values/arguments. If one argument is passed, it's considered that an array name is specified. General syntax: - -```qsp -MIN([#expression 1], [#expression 2], ... , [#expression 20]) -$MIN([$expression 1], [$expression 2], ... , [$expression 20]) -``` - -```qsp -MIN([$array_name]) -$MIN([$array_name]) -``` - -Note, when passing one argument, the search for minimum element occurs among string (if array name is specified with `$` sign) or among numeric values of array elements. For example: - -```qsp -min('a') & ! returns minimum of numeric values of "a" array elements -$min('$b') & ! returns minimum of string values of "b" array elements -``` - -You can't write like this: - -```qsp -min(a) -``` - -You can do this: - -```qsp -$b = 'a' -min($b) & ! search for maximum value among elements of "a" array will occur -``` - -Other examples: - -```qsp -min(1, 2, 5, 2, 0) & ! returns 0 -min(a, b, c) & ! returns minimum of variable values a,b,c -$min('aa', 'ab', 'zz') & ! returns 'aa' -``` - -## RAND - -`RAND` — returns a random number between two specified numbers. General syntax: - -```qsp -RAND([#expression 1], [#expression 2], [#mode]) -``` - -, where `[#expression 1]` and `[#expression 2]` — any two numbers or numeric expressions. - -The `[#mode]` parameter allows specifying a number that should occur more frequently than others. The frequency distribution will smoothly change for all other numbers, decreasing from mode to the limits of the selected interval. If the 3rd parameter is not specified, the function returns a random number in the specified range with uniform/equiprobable number distribution. - -The `[#expression 2]` parameter can be absent, in which case it's taken as `1`. - -:::note[5.7.0] -In older player versions, this parameter defaults to zero. -::: - -Examples: - -```qsp -rand(1, 4) &! returns random value from 1 to 4 -rand(4, 1) &! returns random value from 1 to 4 -rand(1000) &! returns random value from 1 to 1000 -rand 1000 &! returns random value from 1 to 1000 - -x = RAND(1, 1000, 500) & ! 500 will occur more often -x = RAND(1, 1000, 1) & ! 1 will occur more often -x = RAND(1, 1000, 1000) & ! 1000 will occur more often -x = RAND(-1000, 0, -500) & ! -500 will occur more often -x = RAND(1, 1000, 5000) & ! 1000 will occur more often -x = RAND(-1000, -100, -5000) & ! -1000 will occur more often -``` - -## RGB - -`RGB` — returns the numeric color code based on three numeric arguments, each corresponding to a component of the required color. General syntax: - -```qsp -RGB([#red], [#green], [#blue], [#alpha]) -``` - -, where `[#red]`, `[#green]` and `[#blue]` — numeric expression of three color components respectively red, green and blue; `[#alpha]` — transparency component; should take values from 0 to 255. - -This function is usually used together with system variables `bcolor`, `fcolor`, `lcolor`. Example: - -```qsp -! light yellow hyperlinks -lcolor = rgb(255, 255, 100) -! dark gray background -bcolor = rgb(25, 25, 25) -! light green text -fcolor = rgb(100, 255, 100) -``` - -Example of semi-transparent link color: - -```qsp -lcolor = rgb(0, 255, 255, 128) -``` - -:::note[Note.] - -Don't rely on the `[#alpha]` parameter as many players don't support it. - -::: - -## ARRCOMP - -`ARRCOMP` — returns the index of array element matching a regular expression. Search starts from element with specified number; array element indexing starts from zero. If the specified value is not found, the function returns -1. General syntax: - -```qsp -ARRCOMP([$array_name], [$pattern], [#start]) -``` - -, where `[#start]` — array element number from which to start search, `[$array_name]` — array name to search in, `[$pattern]` — regular expression to compare the searched element with. - -- The `[#start]` parameter can be absent, in which case its value is taken as 0. -- Search works only on text arrays (the `$` symbol in array name can be omitted). - -For example, let's take this array: - -```qsp -$mass[0] = "stomp forward" -$mass[1] = " go to cave" -$mass[2] = "don't go to cave" -$mass[3] = "stomp to house" -``` - -We need to find an element whose value consists of three words. Roughly speaking, a word is a set of one or more non-whitespace characters `\S+`, which can be surrounded by whitespace characters `\s`, so we can compose this regular expression: - -```regex -\s?\S+\s\S+\s\S+\s? -``` - -Now we just need to find out which array element matches the pattern: - -```qsp -arrcomp('$mass', '\s?\S+\s\S+\s\S+\s?') & ! the first element matches this expression -``` - -If we want to ignore the first element and start search from the second: - -```qsp -arrcomp('$mass', '\s?\S+\s\S+\s\S+\s?', 2) & ! the third element matches this expression -``` - -And this is how we can output all element values containing the word "go": - -```qsp -loop local pos, index = 0, 0 while 1: - index = arrcomp('$mass', '(.*\s|^)go(\s.*|$)', pos) - if index <> -1: - $mass[index] - pos = index + 1 - else: - jump 'break' - end -end -:break -``` - -Other examples: - -```qsp -! Search for string 'This' among elements of array "$A" -arrcomp('$A', 'This', 0) -! Search for string matching regular expression "abc\d+" -! (first two array elements are ignored) -arrcomp('$A', 'abc\d+', 2) -! similar to previous example, -! but search is performed on all array elements -arrcomp('$A', '.*string.*', 0) - -arrcomp('$A', 'This') & ! equivalent to 1st variant -``` - -:::warning[Attention!] -The function returns only the numeric index of the element. String or multi-dimensional index cannot be obtained with this function. -::: - -## ARRITEM - -`ARRITEM` — returns the value of array element at specified index. General syntax: - -```qsp -ARRITEM([$array_name], [element_index]) -``` - -, where `[$array_name]` — the name of the array whose element we want to get, and `[element_index]` — numeric, text, or multi-dimensional index. - -In other words, the function extracts a value from the specified array cell. Examples: - -```qsp -! output value of element with index 3 -*pl $arritem('$mass', 3) -! output value of element with text index -*pl $arritem('$mass', 'Pete') -! output value of element with multi-dimensional index -*pl $arritem('$mass', [-2, 9, 0]) -``` - -This function can be useful for extracting values when the array name is not known in advance. Example: - -```qsp title="Output contents of several arrays without using DYNAMIC" -$array_name[] = 'mass_1' -$array_name[] = 'mass_2' -$array_name[] = 'mass_3' -$array_name[] = 'mass_4' -$array_name[] = 'mass_5' -! outer loop iterates through array names -loop local j = 0 while j < arrsize('$array_name') step j += 1: - ! inner loop outputs array contents - loop local i = 0 while i < arrsize($array_name[j]) step i += 1: - *pl arritem($array_name[j], i) - end -end -``` - -## %ARRPACK - -`ARRPACK` — returns a tuple into which values from the specified array are packed. - -General syntax: - -```qsp -%ARRPACK([$array_name], [#start_index], [#count]) -``` - -, where `[#start_index]` - the number of array element `[$array_name]` from which to start selecting elements for packing; `[#count]` — the number of elements to be packed into the tuple. - -This function allows shortening the command for extracting arguments from `args`: - -```qsp -! instead of: -local type, name = args[0], args[1] -! you can write like this: -local type, name = arrpack('args') -``` - -It can also be convenient if you need to quickly view array contents or part of it: - -```qsp -! view values in array without using loop: -*pl %arrpack('massive', 11, 10) & ! we'll see ten elements starting from 11th, as a tuple on screen -``` - -## ARRPOS - -`ARRPOS` — returns the index of array element equal to specified value. Search starts from element with specified number; array element indexing starts from zero. If the specified value is not found, the function returns -1. - -General syntax: - -```qsp -ARRPOS([$array_name], [value], [#start]) -``` - -, where `[#start]` — array element number from which to start search, `[$array_name]` — array name to search in, `[value]` — number or string (depending on array type) to find in the array. - -For example, let's take this array: - -```qsp -$color[0] = 'red' -$color[1] = 'yellow' -$color[2] = 'green' -$color[3] = 'blue' -$color[4] = 'yellow' -``` - -We need to find element with value "yellow": - -```qsp -arrpos('$color', 'yellow') & ! returns value 1 -``` - -If we want to ignore the first two elements: - -```qsp -arrpos('$color', 'yellow', 2) & ! returns value 4 -``` - -If we want to find element with value that doesn't exist in the array: - -```qsp -arrpos('$color','light blue') & ! returns value -1 +arrpos('$color','light blue') & ! returns value -1 ``` Other examples: @@ -1297,6 +927,7 @@ ARRPOS([#start], [$array_name], [$pattern]) ## ARRTYPE `ARRTYPE` — returns the type of value stored in a variable or specified array cell. The type is returned as one of the following values: + - `''` (empty string) — value not defined (for example, for uninitialized variables); - `'#'` — variable contains number; - `'` — variable contains string; @@ -1336,88 +967,151 @@ ARRSIZE([$array_name]) , where `[$array_name]` — the name of the array whose size we want to get. -It doesn't matter whether you specify **`## `$MAX` +It doesn't matter whether you specify **`$`** before the array name or not. The total number of cells with both string and numeric values is counted. For example: -`MAX` — returns the maximum of expression-argument values. You can pass from one to twenty values/arguments. If one argument is passed, it's considered that an array name is specified. General syntax: +```qsp +n = ARRSIZE('a') +n = ARRSIZE('$a') +! The result will be the same +``` + +:::warning[Attention!] + +If an array was declared using the `LOCAL` operator, but no value was assigned to any array element, `ARRSIZE` of such array will return `0`. + +::: + +## COUNTOBJ + +`COUNTOBJ` — returns the number of items in inventory. + +The number of the last item in the list numerically matches the number of items, so you can always get the name of the last item like this: ```qsp -MAX([#expression 1], [#expression 2], ... , [#expression 20]) -$MAX([$expression 1], [$expression 2], ... , [$expression 20]) +$getobj(countobj) +``` -MAX([$array_name]) -$MAX([$array_name]) +## INSTR + +`INSTR` — returns the character number from which the substring occurrence begins in the string. General syntax: + +```qsp +INSTR([$string], [$substring], [#start]) ``` -Note, when passing one argument, the search for maximum element occurs among string (if array name is specified with `$` sign) or among numeric values of array elements. For example: +, where `[#start]` — the character number from which to start the search, `[$string]` — text value (string) in which to search, and `[$substring]` — value we're looking for in the specified string. Character numbering starts from `1`. The `[#start]` parameter can be absent, in which case it's taken as 1. + +Examples: ```qsp -max('a') & ! returns maximum of numeric values of "a" array elements -$max('$b') & ! returns maximum of string values of "b" array elements +instr('abcdefabcdef', 'bc', 3) & ! returns number 8 +instr('abcdefghijklm', 'abc') & ! returns number 1 ``` -You can't write like this and expect search among array `a` values: +If no occurrence of the specified substring is found in the string, `instr` returns `0`. + +Example: ```qsp -max(a) +instr('Vasya left the house.', 'go') & ! returns 0 ``` -You can do this: +:::note[5.7.0] +In older player versions, the `[#start]` parameter was specified first: ```qsp -$b = 'a' -max($b) & ! search for maximum value among elements of "a" array will occur +INSTR([#start], [$string], [$substring]) ``` -Other examples: +::: + +## ISNUM + +`ISNUM` — function returns `1` (true) if the passed string is a number, and `0` if the string is not a number. General syntax: ```qsp -max(1, 2, 5, 2, 0) &! returns 5 -max(a, b, c) &! returns maximum of variable values a,b,c -$max('aa', 'ab', 'zz') &! returns 'zz' +ISNUM([$string]) ``` -## `$MIN` +, where `[$string]` — any text string. -`MIN` — returns the minimum of expression-argument values. You can pass from one to twenty values/arguments. If one argument is passed, it's considered that an array name is specified. General syntax: +The check takes into account the `-` sign at the beginning, adjacent spaces and tab characters, but if at least one character turns out not to be a digit, the function will return `0` (false). + +Examples: ```qsp -MIN([#expression 1], [#expression 2], ... , [#expression 20]) -$MIN([$expression 1], [$expression 2], ... , [$expression 20]) +isnum(' 9999 ') & ! returns 1 +isnum(' -888') & ! returns 1 +isnum('777a6') & ! returns 0 +isnum('') & ! returns 0, since empty string contains no number ``` +## ISPLAY + +`ISPLAY` — function checks if a file with the specified name is currently playing, and if it is, returns `1`. Otherwise the function returns `0`. General syntax: + ```qsp -MIN([$array_name]) -$MIN([$array_name]) +ISPLAY([$file_path]) ``` -Note, when passing one argument, the search for minimum element occurs among string (if array name is specified with `$` sign) or among numeric values of array elements. For example: +, where `[$file_path]` — path to sound file relative to game file. + +Example: ```qsp -min('a') & ! returns minimum of numeric values of "a" array elements -$min('$b') & ! returns minimum of string values of "b" array elements +if isplay('music/mountsound.mp3'): + *pl 'Music is playing.' +else + *pl 'Music is not playing.' +end ``` -You can't write like this: +## LEN + +`LEN` — returns the length of the specified text string (number of characters). General syntax: ```qsp -min(a) +LEN([$text]) ``` -You can do this: +, where `[$text]` — any text value. + +Examples: ```qsp -$b = 'a' -min($b) & ! search for maximum value among elements of "a" array will occur +len("abc") & ! returns value 3 +len("thousand-nine-hundred-eighty-nine-millimeter") & ! returns value 46 +len("") & ! returns value 0 ``` -Other examples: +## MSECSCOUNT + +`MSECSCOUNT` — returns the number of milliseconds elapsed since the game started. This function, when used at the counter location, allows organizing various events occurring in real time. Also, with this function you can measure performance of various code sections in your game: ```qsp -min(1, 2, 5, 2, 0) & ! returns 0 -min(a, b, c) & ! returns minimum of variable values a,b,c -$min('aa', 'ab', 'zz') & ! returns 'aa' +i = 0 +old_time = msecscount +:for +if i < 100000: + d[i] = i + i += 1 + jump 'for' +end +new_time = msecscount +pl "Old loop performance: " + $str(new_time - old_time) + +old_time = msecscount +loop i = 0 while i < 100000 step i += 1: + b[i] = i +end +new_time = msecscount +pl "New loop performance: " + $str(new_time - old_time) ``` +:::note +The maximum number this function can return is `2147483647`. It's not hard to calculate that this is enough for more than **550** hours of gameplay. +::: + ## RAND `RAND` — returns a random number between two specified numbers. General syntax: @@ -1485,56 +1179,133 @@ Don't rely on the `[#alpha]` parameter as many players don't support it. ::: -## ARRCOMP +## RND -`ARRCOMP` — returns the index of array element matching a regular expression. Search starts from element with specified number; array element indexing starts from zero. If the specified value is not found, the function returns -1. General syntax: +`RND` - returns a random value from `1` to `1000`. Analogous to the command: ```qsp -ARRCOMP([$array_name], [$pattern], [#start]) +rand(1, 1000) ``` -, where `[#start]` — array element number from which to start search, `[$array_name]` — array name to search in, `[$pattern]` — regular expression to compare the searched element with. +## STRCOMP -- The `[#start]` parameter can be absent, in which case its value is taken as 0. -- Search works only on text arrays (the `$` symbol in array name can be omitted). +`STRCOMP` — compares a string with a regular expression and, if the string matches the regular expression, returns `1` (true), and if it doesn't match — `0` (false). General syntax: -For example, let's take this array: +```qsp +STRCOMP([$string], [$pattern]) +``` + +, where `[$string]` — any text value, `[$pattern]` — regular expression to compare with. + +For example, we need to check if the specified string consists of three words. Each word, roughly speaking, is a set of non-whitespace characters, so we can use the `\S` metacharacter with the `+` quantifier. Words are usually separated by whitespace characters, for which we use the `\s` metacharacter. We get this regular expression: + +```regex +\s?\S+\s+\S+\s+\S+\s? +``` + +Now we can check which strings match this regular expression: ```qsp -$mass[0] = "stomp forward" -$mass[1] = " go to cave" -$mass[2] = "don't go to cave" -$mass[3] = "stomp to house" +strcomp('go along road', '\s?\S+\s+\S+\s+\S+\s?') & ! returns 1 +strcomp(' go home', '\s?\S+\s+\S+\s+\S+\s?') & ! returns 0 +strcomp(' go to forest ', '\s?\S+\s+\S+\s+\S+\s?') & ! returns 1 +strcomp('oneword', '\s?\S+\s+\S+\s+\S+\s?') & ! returns 0 ``` -We need to find an element whose value consists of three words. Roughly speaking, a word is a set of one or more non-whitespace characters `\S+`, which can be surrounded by whitespace characters `\s`, so we can compose this regular expression: +## STRPOS + +`STRPOS` — returns the position of the character from which the substring occurrence matching the regular expression begins in the specified string. General syntax: + +```qsp +STRPOS([$string], [$pattern], [#number]) +``` + +, where `[$string]` — source string in which we search for an occurrence matching regular expression `[$pattern]`, or group number `[#number]` in the regular expression. Group numbering in regular expression starts from 1. If substring with specified number is absent, `0` is returned. + +If parameter `[#number]` is absent or equals `0`, the position of the character from which the substring occurrence matching the entire regular expression begins is returned. + +For example, we need to find out in which part of the text the phrase "green apple" occurs, but the case of this adjective shouldn't matter. + +To write a regular expression for this task, we need to account for all cases: + +```plain +green apple +green apple +green apple +green apple +green apple +green apple +``` + +As we can see, only word endings change in all forms. Therefore we can compose this regular expression: ```regex -\s?\S+\s\S+\s\S+\s? +green(oe|ogo|omu|ym|om)\s+apple(o|a|u|om|e) ``` -Now we just need to find out which array element matches the pattern: +Possible ending variants are listed through a vertical bar in parentheses. And now let's find out from which character in the string the possible phrase "green apple" begins: ```qsp -arrcomp('$mass', '\s?\S+\s\S+\s\S+\s?') & ! the first element matches this expression +! for convenience we put the regular expression in a variable +$regexp = "green(oe|ogo|omu|ym|om)\s+apple(o|a|u|om|e)" +strpos("I have a green apple", $regexp) & ! returns 13 +strpos("You threw a green apple at him!", $regexp) & ! returns 19 +strpos("full box of green apples", $regexp) & ! returns 0, because we didn't account for this form ``` -If we want to ignore the first element and start search from the second: +If we don't just want to know from which character the phrase occurrence begins in the string, but specifically where the word "apple" from this phrase begins, we need to put the word "apple" with ending variants in a separate group and use the `[#number]` parameter: ```qsp -arrcomp('$mass', '\s?\S+\s\S+\s\S+\s?', 2) & ! the third element matches this expression +$regexp = "green(oe|ogo|omu|ym|om)\s+(apple(o|a|u|om|e))" +strpos("I have a green apple", $regexp, 2) & ! returns 21 +strpos("You threw a green apple at him!", $regexp, 2) & ! returns 27 +strpos("full box of green apples", $regexp, 2) & ! returns 0, because we didn't account for the form +``` + +Other examples: + +```qsp title="Working with groups" +!------'----5--8------15--' +STRPOS('+33-671-190-23-999', '\+\d{1,2}-(\d{3})((-\d+)+)',1) &! we'll see 5 on screen +STRPOS('+33-671-190-23-999', '\+\d{1,2}-(\d{3})((-\d+)+)',2) &! we'll see 8 on screen +STRPOS('+33-671-190-23-999', '\+\d{1,2}-(\d{3})((-\d+)+)',3) &! we'll see 15 on screen ``` -** before the array name or not. The total number of cells with both string and numeric values is counted. For example: +```qsp title="Searching for number in string without number" +STRPOS('Eight green apples in basket','\d+') &! 0 will be on screen +``` ```qsp -n = ARRSIZE('a') -n = ARRSIZE('$a') -! The result will be the same +STRPOS('go to cave', '^(\S+)\s(\S+)\s(\S+), 0) &! 1 +STRPOS(' go to cave', '^(\S+)\s(\S+)\s(\S+), 0) &! 0 +STRPOS('go to cave', '^(\S+)\s(\S+)\s(\S+), 1) &! 1 +STRPOS('go to cave', '^(\S+)\s(\S+)\s(\S+), 2) &! 6 +STRPOS('go to cave', '^(\S+)\s(\S+)\s(\S+), 3) &! 8 +STRPOS('go to cave', '^(\S+)\s(\S+)(\s(\S+))?, 4) &! 8 +STRPOS('go to house', 'to\s(\S+)', 0) &! 6 +STRPOS('go to house', 'to\s(\S+)') &! 6 +STRPOS('go to house', 'to\s(\S+)', 1) &! 8 +STRPOS('go to my house', 'to\s(\S+)', 1) &! 8 ``` -:::warning[Attention!] +## VAL -If an array was declared using the `LOCAL` operator, but no value was assigned to any array element, `ARRSIZE` of such array will return `0`. +`VAL` — converts the specified digit string to corresponding number. General syntax: + +```qsp +VAL([$expression]) +``` + +, where `[$expression]` — any text string. + +The check takes into account the `-` sign at the beginning, adjacent spaces and tab characters, but if at least one character turns out not to be a digit, the function will return `0`. Also if `[$expression]` equals `''` (empty string), `0` is returned. + +Examples: + +```qsp +apples = val($apples) -::: \ No newline at end of file +val('123') & ! we'll see 123 +val('') & ! we'll see 0 +val('sand') & ! we'll see 0 +``` diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operacion.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operacion.md index 6fe3d5a..2e0457e 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operacion.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operacion.md @@ -1258,4 +1258,4 @@ Examples: :::note[5.7.0] In older player versions, the operation was bitwise. -::: \ No newline at end of file +::: diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md index 12d436d..2756191 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md @@ -2020,4 +2020,4 @@ The operator has a short form `xgt`: ```qsp XGT [$location], [argument 0], [argument 1], ... , [argument 18] -``` \ No newline at end of file +``` diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-syntaxems.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-syntaxems.md index babcfac..efd7f79 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-syntaxems.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-syntaxems.md @@ -4,7 +4,7 @@ sidebar_position: 5 # Syntaxemes and Special Characters -:::tips[Definition] +:::tip[Definition] In the context of programming, a syntaxeme can be considered as a **minimal unit of syntax** that defines the structure and rules for writing code. @@ -502,4 +502,4 @@ number = 123 $var[0], $var[1] = %number *pl '[<<$var[0]>>,<<$var[1]>>]' ! We'll see '[,]' on screen -``` \ No newline at end of file +``` From 28dbb6e48ba9840a5aff68904187949e3d6d45cc Mon Sep 17 00:00:00 2001 From: aleksversus Date: Sat, 16 Aug 2025 12:46:15 +0500 Subject: [PATCH 05/12] docs(EN:lang/kwrds/operators): fill miss info of set/let-multiple assign --- .../language/qsp-keywords/qsp-keyword-operators.md | 4 ++-- .../language/qsp-keywords/qsp-keyword-operators.md | 14 ++++++++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/language/qsp-keywords/qsp-keyword-operators.md b/docs/language/qsp-keywords/qsp-keyword-operators.md index fdbf33b..c42aff2 100644 --- a/docs/language/qsp-keywords/qsp-keyword-operators.md +++ b/docs/language/qsp-keywords/qsp-keyword-operators.md @@ -1043,7 +1043,7 @@ KILLVAR 'a', 1 ## LET -`LET` — устаревший оператор для установки значения переменных. Общая запись: +`LET` — устаревший оператор для установки значений переменных. Общая запись: ```qsp LET [название переменной] = [выражение] @@ -1666,7 +1666,7 @@ scanstr '$words', $text, '\[(.*?)\]', 1 ## SET -`SET` — оператор для установки значения переменных. Общая запись: +`SET` — оператор для установки значений переменных. Общая запись: ```qsp SET [название переменной] = [выражение] diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md index 2756191..ff1c8a8 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md @@ -1043,10 +1043,11 @@ KILLVAR 'a', 1 ## LET -`LET` — deprecated operator for setting variable value. General syntax: +`LET` — deprecated operator for setting variables values. General syntax: ```qsp LET [variable name] = [expression] +LET [variable 1], [variable 2], ... = [value 1], [value 2], ... ``` where `[variable name]` is a valid variable name, `[expression]` is a valid value for this variable. @@ -1064,6 +1065,10 @@ let $text = "text string" let abs = 123 ! set tuple let %tuple = [123, "text string"] +! multiple assignment +let unit_power, $unit_name = 1300, 'DiggerBull' +! unpack the tuple +let $name, age, height = %npc_fields ``` :::tip @@ -1660,10 +1665,11 @@ scanstr '$words', $text, '\[(.*?)\]', 1 ## SET -`SET` — operator for setting variable value. General syntax: +`SET` — operator for setting variables values. General syntax: ```qsp SET [variable name] = [expression] +SET [variable 1], [variable 2], ... = [value 1], [value 2], ... ``` where `[variable name]` is a valid variable name, `[expression]` is a valid value for this variable. @@ -1677,6 +1683,10 @@ set $text = "text string" set abs = 123 ! set tuple set %tuple = [27, 184, 'steel'] +! multiple assignment +set unit_power, $unit_name = 1300, 'DiggerBull' +! unpack the tuple +set $name, age, height = %npc_fields ``` :::note[Recommendation:] From 0dd5e5b45672ce10530b80452a2c08724f1e3310 Mon Sep 17 00:00:00 2001 From: aleksversus Date: Sat, 16 Aug 2025 11:17:08 +0500 Subject: [PATCH 06/12] docs(lang/kwrds/syntaxemes): fix unused markdown directive "tips" --- docs/language/qsp-keywords/qsp-keyword-syntaxems.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/language/qsp-keywords/qsp-keyword-syntaxems.md b/docs/language/qsp-keywords/qsp-keyword-syntaxems.md index 469dd47..5ede7fd 100644 --- a/docs/language/qsp-keywords/qsp-keyword-syntaxems.md +++ b/docs/language/qsp-keywords/qsp-keyword-syntaxems.md @@ -4,7 +4,7 @@ sidebar_position: 5 # Синтаксемы и спецсимволы -:::tips[Определение] +:::tip[Определение] В контексте программирования синтаксема может рассматриваться как **минимальная единица синтаксиса**, которая определяет структуру и правила написания кода. From 79b0c8a8ca454a994519e5aee06ac9f8b53d5608 Mon Sep 17 00:00:00 2001 From: aleksversus Date: Sat, 16 Aug 2025 11:18:11 +0500 Subject: [PATCH 07/12] docs(lang/kwrds): replace non-breaking spaces --- .../qsp-keywords/qsp-keyword-functions.md | 8 +-- .../qsp-keywords/qsp-keyword-operators.md | 52 +++++++++---------- .../qsp-keywords/qsp-keyword-syntaxems.md | 2 +- 3 files changed, 31 insertions(+), 31 deletions(-) diff --git a/docs/language/qsp-keywords/qsp-keyword-functions.md b/docs/language/qsp-keywords/qsp-keyword-functions.md index a14842a..001bdc5 100644 --- a/docs/language/qsp-keywords/qsp-keyword-functions.md +++ b/docs/language/qsp-keywords/qsp-keyword-functions.md @@ -526,7 +526,7 @@ $qspver('platform') $REPLACE([$строка], [$поиск], [$замена], [#число_замен]) ``` -Данная функция заменяет в строке `[$строка]` несколько вхождений строки `[$поиск]` строкой `[$замена]` и возвращает результат. Замена производится слева-направо и только для непересекающихся вхождений. Параметр `[#число_замен]` показывает, сколько вхождений должно быть заменено. Если параметр не указан, производится замена всех вхождений. Если `[$замена]` отсутствует или указана пустая строка, то удаляет в исходной строке все вхождения искомой строки. Примеры: +Данная функция заменяет в строке `[$строка]` несколько вхождений строки `[$поиск]` строкой `[$замена]` и возвращает результат. Замена производится слева-направо и только для непересекающихся вхождений. Параметр `[#число_замен]` показывает, сколько вхождений должно быть заменено. Если параметр не указан, производится замена всех вхождений. Если `[$замена]` отсутствует или указана пустая строка, то удаляет в исходной строке все вхождения искомой строки. Примеры: ```qsp $replace('test', '12', '4') & ! выведет на экран 'test' @@ -731,7 +731,7 @@ ARRCOMP([$имя_массива], [$шаблон], [#начало]) , где `[#начало]` — номер элемента массива, с которого следует начать поиск, `[$имя_массива]` — название массива, по которому нужно произвести поиск, `[$шаблон]` — регулярное выражение, с которым будет сравниваться искомый элемент. - Параметр `[#начало]` может отсутствовать, при этом его значение принимается равным 0. -- Поиск работает только по текстовым массивам (символ `$` в названии массива можно опустить). +- Поиск работает только по текстовым массивам (символ `$` в названии массива можно опустить). Для примера возьмём вот такой массив: @@ -966,7 +966,7 @@ ARRSIZE([$имя_массива]) , где `[$имя_массива]` — название массива, размер которого хотим получить. -Не имеет значения, указываете ли вы **`$`** перед названием массива или нет. Подсчитывается общее число ячеек и со строковыми, и с числовыми значениями. Для примера: +Не имеет значения, указываете ли вы **`$`** перед названием массива или нет. Подсчитывается общее число ячеек и со строковыми, и с числовыми значениями. Для примера: ```qsp n = ARRSIZE('a') @@ -1121,7 +1121,7 @@ RAND([#выражение 1], [#выражение 2], [#мода]) , где `[#выражение 1]` и `[#выражение 2]` — два любых числа или числовых выражения. -Параметр `[#мода]` позволяет указать число, которое должно выпадать более часто, чем остальные. При этом распределение частоты выпадения будет плавно изменяться для всех остальных чисел, уменьшаясь от моды к пределам выбранного интервала. Если 3й параметр не указан, то функция возвращает случайное число в заданном диапазоне с равномерным/равновероятным распределением чисел. +Параметр `[#мода]` позволяет указать число, которое должно выпадать более часто, чем остальные. При этом распределение частоты выпадения будет плавно изменяться для всех остальных чисел, уменьшаясь от моды к пределам выбранного интервала. Если 3й параметр не указан, то функция возвращает случайное число в заданном диапазоне с равномерным/равновероятным распределением чисел. Параметр `[#выражение 2]` может отсутствовать, при этом он принимается равным `1`. diff --git a/docs/language/qsp-keywords/qsp-keyword-operators.md b/docs/language/qsp-keywords/qsp-keyword-operators.md index e2ceed4..fe14277 100644 --- a/docs/language/qsp-keywords/qsp-keyword-operators.md +++ b/docs/language/qsp-keywords/qsp-keyword-operators.md @@ -581,16 +581,16 @@ IF [#выражение]: END ``` -В данном случае, если верно условие `[#выражение]`, выполняются команды `{команда 1}`, `{команда 2}` и т.д. +В данном случае, если верно условие `[#выражение]`, выполняются команды `{команда 1}`, `{команда 2}` и т.д. -- Для **однострочной формы** записи это будут только те команды, которые идут в той же строке, что и оператор `IF` до конца строки; -- а для **многострочной формы** записи это будут те команды, которые идут в последующих строках после двоеточия и до специального ключевого слова `END`. +- Для **однострочной формы** записи это будут только те команды, которые идут в той же строке, что и оператор `IF` до конца строки; +- а для **многострочной формы** записи это будут те команды, которые идут в последующих строках после двоеточия и до специального ключевого слова `END`. В качестве условия могут выступать операции сравнения, логические операции и иные выражения, возвращающие числовые значения. -Ключевое слово `END` при многострочной форме записи должно стоять отдельной строкой. +Ключевое слово `END` при многострочной форме записи должно стоять отдельной строкой. -Если условие `[#выражение]` не верно, команды выполнены не будут. +Если условие `[#выражение]` не верно, команды выполнены не будут. Примеры однострочной формы записи условий: @@ -703,10 +703,10 @@ if abcd=3: k1=34 else k1=25 end ## ELSE -`ELSE` — ключевое слово, использующееся совместно с оператором `IF`, и которое служит для предоставления альтернативы, если условие не выполнено. Ключевое слово `ELSE` так же имеет две формы записи: однострочную и многострочную. +`ELSE` — ключевое слово, использующееся совместно с оператором `IF`, и которое служит для предоставления альтернативы, если условие не выполнено. Ключевое слово `ELSE` так же имеет две формы записи: однострочную и многострочную. -- Многострочную форму записи `ELSE` можно использовать только в многострочной конструкции оператора `IF`, -- однострочную форму записи можно использовать как в однострочной, так и в многострочной, конструкции оператора `IF`. Общая форма записи: +- Многострочную форму записи `ELSE` можно использовать только в многострочной конструкции оператора `IF`, +- однострочную форму записи можно использовать как в однострочной, так и в многострочной, конструкции оператора `IF`. Общая форма записи: ```qsp ! однострочная форма записи @@ -736,15 +736,15 @@ ELSE {команда н1} & {команда н2} & ... END ``` -Здесь, если условие`[#выражение]` верно, выполняются команды от двоеточия до ключевого слова `ELSE`, а если условие `[#выражение]` не верно, выполняются команды от ключевого слова `ELSE` и до конца конструкции условия. +Здесь, если условие`[#выражение]` верно, выполняются команды от двоеточия до ключевого слова `ELSE`, а если условие `[#выражение]` не верно, выполняются команды от ключевого слова `ELSE` и до конца конструкции условия. -После `ELSE` можно ставить, а можно не ставить двоеточие. +После `ELSE` можно ставить, а можно не ставить двоеточие. **При однострочной форме записи:** -- и команды и ключевое слово `ELSE` должны быть записаны в одной строке +- и команды и ключевое слово `ELSE` должны быть записаны в одной строке - окончанием альтернативного списка команд является конец строки. -- если однострочная форма записи `ELSE` используется в многострочной форме записи `IF`, все команды, которые идут в последующих строках после `ELSE` до `END` игнорируются. +- если однострочная форма записи `ELSE` используется в многострочной форме записи `IF`, все команды, которые идут в последующих строках после `ELSE` до `END` игнорируются. Примеры однострочной записи: @@ -769,7 +769,7 @@ end **При многострочной форме записи:** -- все команды должны идти в последующих строках после `ELSE`; +- все команды должны идти в последующих строках после `ELSE`; Примеры многострочной записи: @@ -795,10 +795,10 @@ end ## ELSEIF -`ELSEIF` — ключевое слово, которое используется совместно с оператором `IF` и позволяет определять на одном уровне вложенности последовательно-исключающие условия. Имеет однострочную и многострочную формы записи. +`ELSEIF` — ключевое слово, которое используется совместно с оператором `IF` и позволяет определять на одном уровне вложенности последовательно-исключающие условия. Имеет однострочную и многострочную формы записи. -- Многострочную форму записи можно использовать только в многострочных конструкциях с оператором `IF`, -- однострочную — как в многострочных, так и в однострочных конструкциях с оператором `IF`. +- Многострочную форму записи можно использовать только в многострочных конструкциях с оператором `IF`, +- однострочную — как в многострочных, так и в однострочных конструкциях с оператором `IF`. Общие формы записи: @@ -830,13 +830,13 @@ ELSE {последний набор команд} END ``` -Работает это следующим образом. Если `[#выражение 1]` верно, выполняются команды `{набор команд 1}`. Если `[#выражение 1]` неверно, но верно `[#выражение 2]`, выполняются команды `{набор команд 2}`, и т.д. И только если неверны все выражения в текущей конструкции условия, выполнятся команды после `ELSE`. Верность выражения `[#выражение 1]` не исключает верности выражения `[#выражение 2]`, однако верность выражения `[#выражение 2]` исключает верность выражения `[#выражение 1]`. +Работает это следующим образом. Если `[#выражение 1]` верно, выполняются команды `{набор команд 1}`. Если `[#выражение 1]` неверно, но верно `[#выражение 2]`, выполняются команды `{набор команд 2}`, и т.д. И только если неверны все выражения в текущей конструкции условия, выполнятся команды после `ELSE`. Верность выражения `[#выражение 1]` не исключает верности выражения `[#выражение 2]`, однако верность выражения `[#выражение 2]` исключает верность выражения `[#выражение 1]`. -Особенности записи `ELSEIF`: +Особенности записи `ELSEIF`: -- Может использоваться вариант написания `ELSE IF`. Работает точно так же. -- Если в многострочной конструкции `IF` после `ELSEIF` операторы идут в той же самой строке (однострочная форма), то все последующие строки игнорируются до следующего `ELSEIF`, либо до `ELSE` или `END`. -- В конструкции `IF` c `ELSEIF` может как присутствовать, так и отсутствовать часть с `ELSE`. +- Может использоваться вариант написания `ELSE IF`. Работает точно так же. +- Если в многострочной конструкции `IF` после `ELSEIF` операторы идут в той же самой строке (однострочная форма), то все последующие строки игнорируются до следующего `ELSEIF`, либо до `ELSE` или `END`. +- В конструкции `IF` c `ELSEIF` может как присутствовать, так и отсутствовать часть с `ELSE`. Примеры: @@ -860,7 +860,7 @@ elseif money mod 10=0 or money mod 10>4 or (money mod 100>10 and money mod 100<2 end ``` -Пример записи `ELSEIF` с операторами в той же строке: +Пример записи `ELSEIF` с операторами в той же строке: ```qsp ! реализация switch/case на QSP @@ -1118,7 +1118,7 @@ local arr Собственные локальные переменные можно создавать в следующих блоках кода: - Локации сами по себе. -- Код, передаваемый оператору `DYNAMIC`, или функции `DYNEVAL`, в виде текста. +- Код, передаваемый оператору `DYNAMIC`, или функции `DYNEVAL`, в виде текста. - Код, выполняемый при нажатии на гиперссылку. - Код каждого отдельного Действия ([ACT](qsp-keyword-operators.md#act)). - Код каждого отдельного Цикла ([LOOP](qsp-keyword-operators.md#loop)) @@ -1307,7 +1307,7 @@ MENU [$название массива] Здесь название массива (`%stone`) - это название меню, а кортежи - действия, для которых указаны названия пунктов и названия локаций-обработчиков выбора пунктов меню. При выборе пункта "Взять камень" произойдёт вызов локации с названием "takestone". Аналогично будет происходить с другими пунктами. -Чтобы вывести меню на экран, нужно воспользоваться оператором `MENU`: +Чтобы вывести меню на экран, нужно воспользоваться оператором `MENU`: ```qsp menu '%stone' @@ -1866,11 +1866,11 @@ showstat off & ! скрывает окно дополнительного опи SORTARR [$имя_массива], [#порядок] ``` - Здесь `[$имя_массива]` — название массива, который нужно отсортировать. Параметр `[#порядок]` можно не указывать. Если не указан или равен `0`, то сортирует массив по возрастанию (от меньшего к большему). Если равен `1`, то сортирует массив по убыванию (от большего к меньшему). + Здесь `[$имя_массива]` — название массива, который нужно отсортировать. Параметр `[#порядок]` можно не указывать. Если не указан или равен `0`, то сортирует массив по возрастанию (от меньшего к большему). Если равен `1`, то сортирует массив по убыванию (от большего к меньшему). Может сортировать массивы любых типов (числа, строки, кортежи), но не допускается смешивать значения разных типов в одном массиве. -Для указания типа сортируемых значений нужно указать префикс типа как часть имени массива (`$`, `%`). +Для указания типа сортируемых значений нужно указать префикс типа как часть имени массива (`$`, `%`). Пример сортировки текстового массива: diff --git a/docs/language/qsp-keywords/qsp-keyword-syntaxems.md b/docs/language/qsp-keywords/qsp-keyword-syntaxems.md index 5ede7fd..7190207 100644 --- a/docs/language/qsp-keywords/qsp-keyword-syntaxems.md +++ b/docs/language/qsp-keywords/qsp-keyword-syntaxems.md @@ -6,7 +6,7 @@ sidebar_position: 5 :::tip[Определение] -В контексте программирования синтаксема может рассматриваться как **минимальная единица синтаксиса**, которая определяет структуру и правила написания кода. +В контексте программирования синтаксема может рассматриваться как **минимальная единица синтаксиса**, которая определяет структуру и правила написания кода. Так синтаксемой может быть переменная, оператор, функция, ключевое слово объявления, или специальные символы, с помощью которых мы структурируем код. From 286b8a54cec4f6dbf06a7c9be95febc677b8488f Mon Sep 17 00:00:00 2001 From: aleksversus Date: Sat, 16 Aug 2025 11:36:24 +0500 Subject: [PATCH 08/12] docs(lang/kwrds/operators): fill miss info of set/let-multiple assign --- .../qsp-keywords/qsp-keyword-operators.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/docs/language/qsp-keywords/qsp-keyword-operators.md b/docs/language/qsp-keywords/qsp-keyword-operators.md index fe14277..fdbf33b 100644 --- a/docs/language/qsp-keywords/qsp-keyword-operators.md +++ b/docs/language/qsp-keywords/qsp-keyword-operators.md @@ -1043,10 +1043,11 @@ KILLVAR 'a', 1 ## LET -`LET` — устаревший оператор для установки значения переменной. Общая запись: +`LET` — устаревший оператор для установки значения переменных. Общая запись: ```qsp LET [название переменной] = [выражение] +LET [переменная 1], [переменная 2], ... = [значение 1], [значение 2], ... ``` , где `[название переменной]` — это допустимое имя переменной, `[выражение]` — это допустимое для данной переменной значение. @@ -1064,13 +1065,17 @@ let $text = "text string" let abs = 123 ! задаём кортеж let %tuple = [123, "text string"] +! множественное присваивание +let unit_power, $unit_name = 1300, 'DiggerBull' +! распаковка кортежа +let $name, age, height = %npc_fields ``` :::tip Данный оператор считается устаревшим. Используйте вместо него оператор `set`, и только в тех случаях, когда это улучшит читаемость кода. ```qsp -! присвоение можно проводить без операторов set или let: +! присвоение можно проводить без операторов `set` или `let`: $text = "text string" ``` @@ -1661,10 +1666,11 @@ scanstr '$words', $text, '\[(.*?)\]', 1 ## SET -`SET` — оператор для установки значения переменной. Общая запись: +`SET` — оператор для установки значения переменных. Общая запись: ```qsp SET [название переменной] = [выражение] +SET [переменная 1], [переменная 2], ... = [значение 1], [значение 2], ... ``` , где `[название переменной]` — это допустимое имя переменной, `[выражение]` — это допустимое для данной переменной значение. @@ -1678,6 +1684,10 @@ set $text = "text string" set abs = 123 ! задаём кортеж set %tuple = [27, 184, 'steel'] +! множественное присваивание +set unit_power, $unit_name = 1300, 'DiggerBull' +! распаковка кортежа +set $name, age, height = %npc_fields ``` :::note[Рекомендация:] From 8a16217f4051f205527e10c3016118985dea09c7 Mon Sep 17 00:00:00 2001 From: aleksversus Date: Sat, 16 Aug 2025 12:35:38 +0500 Subject: [PATCH 09/12] docs(EN:lang/kwrds): replace header of contents, fix md-alarms --- docs/language/qsp-keywords/qsp-keyword-functions.md | 1 + .../current/language/qsp-keywords/qsp-keyword-functions.md | 3 ++- .../current/language/qsp-keywords/qsp-keyword-operacion.md | 2 +- .../current/language/qsp-keywords/qsp-keyword-operators.md | 2 +- .../current/language/qsp-keywords/qsp-keyword-syntaxems.md | 4 ++-- 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/language/qsp-keywords/qsp-keyword-functions.md b/docs/language/qsp-keywords/qsp-keyword-functions.md index 001bdc5..b154a4b 100644 --- a/docs/language/qsp-keywords/qsp-keyword-functions.md +++ b/docs/language/qsp-keywords/qsp-keyword-functions.md @@ -927,6 +927,7 @@ ARRPOS([#начало], [$имя_массива], [$шаблон]) ## ARRTYPE `ARRTYPE` — возвращает тип значения, хранящегося в переменной, или указанной ячейке массива. Тип возвращается в виде одного из следующих значений: + - `''` (пустая строка) — значение не определено (например, для неинициализированных переменных); - `'#'` — переменная содержит число; - `'$'` — переменная содержит строку; diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md index 8487f44..5afb0c1 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md @@ -925,6 +925,7 @@ ARRPOS([#start], [$array_name], [$pattern]) ## ARRTYPE `ARRTYPE` — returns the type of value stored in a variable or specified array cell. The type is returned as one of the following values: + - `''` (empty string) — value not defined (for example, for uninitialized variables); - `'#'` — variable contains number; - `'$'` — variable contains string; @@ -1304,4 +1305,4 @@ apples = val($apples) val('123') & ! we'll see 123 val('') & ! we'll see 0 val('sand') & ! we'll see 0 -``` \ No newline at end of file +``` diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operacion.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operacion.md index 6fe3d5a..2e0457e 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operacion.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operacion.md @@ -1258,4 +1258,4 @@ Examples: :::note[5.7.0] In older player versions, the operation was bitwise. -::: \ No newline at end of file +::: diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md index 12d436d..2756191 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md @@ -2020,4 +2020,4 @@ The operator has a short form `xgt`: ```qsp XGT [$location], [argument 0], [argument 1], ... , [argument 18] -``` \ No newline at end of file +``` diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-syntaxems.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-syntaxems.md index babcfac..efd7f79 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-syntaxems.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-syntaxems.md @@ -4,7 +4,7 @@ sidebar_position: 5 # Syntaxemes and Special Characters -:::tips[Definition] +:::tip[Definition] In the context of programming, a syntaxeme can be considered as a **minimal unit of syntax** that defines the structure and rules for writing code. @@ -502,4 +502,4 @@ number = 123 $var[0], $var[1] = %number *pl '[<<$var[0]>>,<<$var[1]>>]' ! We'll see '[,]' on screen -``` \ No newline at end of file +``` From d875e2e0af7e603be9be8adde9a7a14d707b4050 Mon Sep 17 00:00:00 2001 From: aleksversus Date: Sat, 16 Aug 2025 12:46:15 +0500 Subject: [PATCH 10/12] docs(EN:lang/kwrds/operators): fill miss info of set/let-multiple assign --- .../language/qsp-keywords/qsp-keyword-operators.md | 4 ++-- .../language/qsp-keywords/qsp-keyword-operators.md | 14 ++++++++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/language/qsp-keywords/qsp-keyword-operators.md b/docs/language/qsp-keywords/qsp-keyword-operators.md index fdbf33b..c42aff2 100644 --- a/docs/language/qsp-keywords/qsp-keyword-operators.md +++ b/docs/language/qsp-keywords/qsp-keyword-operators.md @@ -1043,7 +1043,7 @@ KILLVAR 'a', 1 ## LET -`LET` — устаревший оператор для установки значения переменных. Общая запись: +`LET` — устаревший оператор для установки значений переменных. Общая запись: ```qsp LET [название переменной] = [выражение] @@ -1666,7 +1666,7 @@ scanstr '$words', $text, '\[(.*?)\]', 1 ## SET -`SET` — оператор для установки значения переменных. Общая запись: +`SET` — оператор для установки значений переменных. Общая запись: ```qsp SET [название переменной] = [выражение] diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md index 2756191..ff1c8a8 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md @@ -1043,10 +1043,11 @@ KILLVAR 'a', 1 ## LET -`LET` — deprecated operator for setting variable value. General syntax: +`LET` — deprecated operator for setting variables values. General syntax: ```qsp LET [variable name] = [expression] +LET [variable 1], [variable 2], ... = [value 1], [value 2], ... ``` where `[variable name]` is a valid variable name, `[expression]` is a valid value for this variable. @@ -1064,6 +1065,10 @@ let $text = "text string" let abs = 123 ! set tuple let %tuple = [123, "text string"] +! multiple assignment +let unit_power, $unit_name = 1300, 'DiggerBull' +! unpack the tuple +let $name, age, height = %npc_fields ``` :::tip @@ -1660,10 +1665,11 @@ scanstr '$words', $text, '\[(.*?)\]', 1 ## SET -`SET` — operator for setting variable value. General syntax: +`SET` — operator for setting variables values. General syntax: ```qsp SET [variable name] = [expression] +SET [variable 1], [variable 2], ... = [value 1], [value 2], ... ``` where `[variable name]` is a valid variable name, `[expression]` is a valid value for this variable. @@ -1677,6 +1683,10 @@ set $text = "text string" set abs = 123 ! set tuple set %tuple = [27, 184, 'steel'] +! multiple assignment +set unit_power, $unit_name = 1300, 'DiggerBull' +! unpack the tuple +set $name, age, height = %npc_fields ``` :::note[Recommendation:] From 5cb4d38008af759a1d7fc98ad9ae6bcaee341f7d Mon Sep 17 00:00:00 2001 From: aleksversus Date: Sat, 16 Aug 2025 17:24:23 +0500 Subject: [PATCH 11/12] docs(lang/kwrds): rename 'operators -> statements', 'operacion -> operators' --- ...08-15-docs-add-chapters-of-keywords-etc.md | 4 +- docs/language/qsp-keywords/index.md | 190 +- .../qsp-keywords/qsp-keyword-functions.md | 2 +- .../qsp-keywords/qsp-keyword-operacion.md | 1261 ---------- .../qsp-keywords/qsp-keyword-operators.md | 2122 ++++++----------- .../qsp-keywords/qsp-keyword-statements.md | 2043 ++++++++++++++++ .../qsp-keywords/qsp-keyword-syntaxems.md | 6 +- .../current/language/qsp-keywords/index.md | 190 +- .../qsp-keywords/qsp-keyword-functions.md | 2 +- .../qsp-keywords/qsp-keyword-operacion.md | 1261 ---------- .../qsp-keywords/qsp-keyword-operators.md | 2110 ++++++---------- .../qsp-keywords/qsp-keyword-statements.md | 2033 ++++++++++++++++ .../qsp-keywords/qsp-keyword-syntaxems.md | 6 +- .../qsp-keywords/qsp-keyword-sys-var.md | 2 +- 14 files changed, 5616 insertions(+), 5616 deletions(-) delete mode 100644 docs/language/qsp-keywords/qsp-keyword-operacion.md create mode 100644 docs/language/qsp-keywords/qsp-keyword-statements.md delete mode 100644 i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operacion.md create mode 100644 i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-statements.md diff --git a/blog/2024-08-15-docs-add-chapters-of-keywords-etc.md b/blog/2024-08-15-docs-add-chapters-of-keywords-etc.md index bc29fed..2864496 100644 --- a/blog/2024-08-15-docs-add-chapters-of-keywords-etc.md +++ b/blog/2024-08-15-docs-add-chapters-of-keywords-etc.md @@ -27,9 +27,9 @@ tags: ::: - Необходимо смириться с тем, что ссылки на `index.md` раздела не будут работать в докузаурусе, либо, если их "обрезать" для докузауруса, не будут работать в обсидиане. Лучше избегать создания разделов `index.md` для комфортной работы и там и там. - Ссылки на файлы статей должны быть относительными (чтобы работать и там и там), и включать так же расширение файлов (`.md`). - `../language/qsp-keywords/qsp-keywords-functions.md` + `../language/qsp-keywords/qsp-keyword-functions.md` :::note[Потому что:] Докузаурус опускает расширение `.md` в ссылках и таким образом в процессе работы ссылки поддерживаются и в обсидиане и в докузаурусе. После сборки ссылки во всех статьях приобретают вид валидный для докузауруса, но невалидный для Обсидиана. - `https://dev.qsp.org/docs/language/qsp-keywords/qsp-keyword-operators` + `https://dev.qsp.org/docs/language/qsp-keywords/qsp-keyword-statements` ::: - Необходимо смириться с тем, что обсидиан не поддерживает те же якоря заголовков, что и докузаурус, из-за чего сослаться на заголовок в обсидиане так же как в докузаурусе невозможно. Это не мешает обсидиану поддерживать такие ссылки при изменении местоположения статей и разделов. diff --git a/docs/language/qsp-keywords/index.md b/docs/language/qsp-keywords/index.md index df32c34..3974649 100644 --- a/docs/language/qsp-keywords/index.md +++ b/docs/language/qsp-keywords/index.md @@ -9,10 +9,10 @@ sidebar_position: 6 Вычеркнутые команды не работают в плеерах версии 5.8.0 и выше. ::: -- [Неявный оператор](qsp-keyword-operators#неявный-оператор) -- [`!` (комментарий)](qsp-keyword-operators.md#-комментарий) -- [`!` (не равно)](qsp-keyword-operacion.md#-не-равно-1) -- [`&` (конкатенация)](qsp-keyword-operacion.md#-конкатенация) +- [Неявный оператор](qsp-keyword-statements#неявный-оператор) +- [`!` (комментарий)](qsp-keyword-statements.md#-комментарий) +- [`!` (не равно)](qsp-keyword-operators.md#-не-равно-1) +- [`&` (конкатенация)](qsp-keyword-operators.md#-конкатенация) - [`&` (перечисление команд)](qsp-keyword-syntaxems.md#амперсанд-) - [`:` (метки)](qsp-keyword-syntaxems.md#метки-) - [`,` (разделитель аргументов)](qsp-keyword-syntaxems.md#запятая-) @@ -24,30 +24,30 @@ sidebar_position: 6 - [`@` (коммерческое "эт")](qsp-keyword-syntaxems#%D1%81%D0%B8%D0%BC%D0%B2%D0%BE%D0%BB-%D0%BA%D0%BE%D0%BC%D0%BC%D0%B5%D1%80%D1%87%D0%B5%D1%81%D0%BA%D0%BE%D0%B5-%D1%8D%D1%82-) - 5.8.0 - [`$` (знак доллара)](qsp-keyword-syntaxems#%D1%81%D0%B8%D0%BC%D0%B2%D0%BE%D0%BB-%D0%B7%D0%BD%D0%B0%D0%BA-%D0%B4%D0%BE%D0%BB%D0%BB%D0%B0%D1%80%D0%B0-) - [`%` (знак процента)](qsp-keyword-syntaxems#%D1%81%D0%B8%D0%BC%D0%B2%D0%BE%D0%BB-%D0%B7%D0%BD%D0%B0%D0%BA-%D0%BF%D1%80%D0%BE%D1%86%D0%B5%D0%BD%D1%82%D0%B0-) - 5.9.0 -- [`*`](qsp-keyword-operacion.md#-умножение) -- [`*=`](qsp-keyword-operacion.md#-умножение-присвоение) -- [`+`](qsp-keyword-operacion.md#-сложение) -- [`+=`](qsp-keyword-operacion.md#-сложение-присвоение) -- ~~[`+` (унарный)](qsp-keyword-operacion.md#--унарный-минус)~~ -- [`-`](qsp-keyword-operacion.md#--вычитание) -- [`-=`](qsp-keyword-operacion.md#--вычитание-присвоение) -- [`-` (унарный)](qsp-keyword-operacion.md#--унарный-минус) -- [`/`](qsp-keyword-operacion.md#-деление) -- [`/=`](qsp-keyword-operacion.md#-деление-присвоение) -- [`<`](qsp-keyword-operacion.md#-меньше) -- [`<=`](qsp-keyword-operacion.md#-меньше-либо-равно) -- [`<>`](qsp-keyword-operacion.md#-не-равно) -- [`=` (равно)](qsp-keyword-operacion.md#-равно) -- [`=` (присвоение)](qsp-keyword-operacion.md#-присвоение) -- [`=<`](qsp-keyword-operacion.md#-равно-либо-меньше) -- [`=>`](qsp-keyword-operacion.md#-равно-или-больше) -- [`>`](qsp-keyword-operacion.md#-больше) -- [`>=`](qsp-keyword-operacion.md#-больше-либо-равно) -- [`ACT`](qsp-keyword-operators.md#act) -- ~~[`ADDLIB`](qsp-keyword-operators.md#inclib)~~ -- [`ADDOBJ`](qsp-keyword-operators.md#addobj) -- ~~[`ADDQST`](qsp-keyword-operators.md#inclib)~~ -- [`AND`](qsp-keyword-operacion.md#and) +- [`*`](qsp-keyword-operators.md#-умножение) +- [`*=`](qsp-keyword-operators.md#-умножение-присвоение) +- [`+`](qsp-keyword-operators.md#-сложение) +- [`+=`](qsp-keyword-operators.md#-сложение-присвоение) +- ~~[`+` (унарный)](qsp-keyword-operators.md#--унарный-минус)~~ +- [`-`](qsp-keyword-operators.md#--вычитание) +- [`-=`](qsp-keyword-operators.md#--вычитание-присвоение) +- [`-` (унарный)](qsp-keyword-operators.md#--унарный-минус) +- [`/`](qsp-keyword-operators.md#-деление) +- [`/=`](qsp-keyword-operators.md#-деление-присвоение) +- [`<`](qsp-keyword-operators.md#-меньше) +- [`<=`](qsp-keyword-operators.md#-меньше-либо-равно) +- [`<>`](qsp-keyword-operators.md#-не-равно) +- [`=` (равно)](qsp-keyword-operators.md#-равно) +- [`=` (присвоение)](qsp-keyword-operators.md#-присвоение) +- [`=<`](qsp-keyword-operators.md#-равно-либо-меньше) +- [`=>`](qsp-keyword-operators.md#-равно-или-больше) +- [`>`](qsp-keyword-operators.md#-больше) +- [`>=`](qsp-keyword-operators.md#-больше-либо-равно) +- [`ACT`](qsp-keyword-statements.md#act) +- ~~[`ADDLIB`](qsp-keyword-statements.md#inclib)~~ +- [`ADDOBJ`](qsp-keyword-statements.md#addobj) +- ~~[`ADDQST`](qsp-keyword-statements.md#inclib)~~ +- [`AND`](qsp-keyword-operators.md#and) - [`ARGS`](qsp-keyword-sys-var.md#args) - [`ARRCOMP`](qsp-keyword-functions.md#arrcomp) - [`ARRITEM`](qsp-keyword-functions.md#arritem) - 5.8.0 @@ -57,77 +57,77 @@ sidebar_position: 6 - [`ARRSIZE`](qsp-keyword-functions.md#arrsize) - [`$BACKIMAGE`](qsp-keyword-sys-var.md#backimage) - [`BCOLOR`](qsp-keyword-sys-var.md#bcolor) -- [`CLA`](qsp-keyword-operators.md#cla) -- [`CLEAR`](qsp-keyword-operators.md#clear-1) -- [`*CLEAR`](qsp-keyword-operators.md#clear) -- [`CLOSE`](qsp-keyword-operators.md#close) -- [`CLOSE ALL`](qsp-keyword-operators.md#close-all) -- [`CLR`](qsp-keyword-operators.md#clear-1) -- [`*CLR`](qsp-keyword-operators.md#clear) -- [`CLS`](qsp-keyword-operators.md#cls) -- [`CMDCLEAR`](qsp-keyword-operators.md#cmdclear) -- [`CMDCLR`](qsp-keyword-operators.md#cmdclear) -- [`COPYARR`](qsp-keyword-operators.md#copyarr) +- [`CLA`](qsp-keyword-statements.md#cla) +- [`CLEAR`](qsp-keyword-statements.md#clear-1) +- [`*CLEAR`](qsp-keyword-statements.md#clear) +- [`CLOSE`](qsp-keyword-statements.md#close) +- [`CLOSE ALL`](qsp-keyword-statements.md#close-all) +- [`CLR`](qsp-keyword-statements.md#clear-1) +- [`*CLR`](qsp-keyword-statements.md#clear) +- [`CLS`](qsp-keyword-statements.md#cls) +- [`CMDCLEAR`](qsp-keyword-statements.md#cmdclear) +- [`CMDCLR`](qsp-keyword-statements.md#cmdclear) +- [`COPYARR`](qsp-keyword-statements.md#copyarr) - [`$COUNTER`](qsp-keyword-sys-var.md#counter) - [`COUNTOBJ`](qsp-keyword-functions.md#countobj) - [`$CURACTS`](qsp-keyword-functions.md#curacts) - [`$CURLOC`](qsp-keyword-functions.md#curloc) - [`$CUROBJS`](qsp-keyword-functions.md#curobjs) - 5.9.0 - [`DEBUG`](qsp-keyword-sys-var.md#debug) -- [`DELACT`](qsp-keyword-operators.md#delact) -- ~~[`DELLIB`](qsp-keyword-operators.md#freelib)~~ -- [`DELOBJ`](qsp-keyword-operators.md#delobj) +- [`DELACT`](qsp-keyword-statements.md#delact) +- ~~[`DELLIB`](qsp-keyword-statements.md#freelib)~~ +- [`DELOBJ`](qsp-keyword-statements.md#delobj) - [`$DESC`](qsp-keyword-functions.md#desc) - [`DISABLESCROLL`](qsp-keyword-sys-var.md#disablescroll) - ~~[`DISABLESUBEX`](qsp-keyword-sys-var.md#disablesubex)~~ -- [`DYNAMIC`](qsp-keyword-operators.md#dynamic) +- [`DYNAMIC`](qsp-keyword-statements.md#dynamic) - [`DYNEVAL`](qsp-keyword-functions.md#dyneval) -- [`ELSE`](qsp-keyword-operators.md#else) -- [`ELSEIF`](qsp-keyword-operators.md#elseif) +- [`ELSE`](qsp-keyword-statements.md#else) +- [`ELSEIF`](qsp-keyword-statements.md#elseif) - [`END`](qsp-keyword-syntaxems.md#end) -- [`EXIT`](qsp-keyword-operators.md#exit) +- [`EXIT`](qsp-keyword-statements.md#exit) - [`FCOLOR`](qsp-keyword-sys-var.md#fcolor) - [`$FNAME`](qsp-keyword-sys-var.md#fname) -- [`FREELIB`](qsp-keyword-operators.md#freelib) - 5.8.0 +- [`FREELIB`](qsp-keyword-statements.md#freelib) - 5.8.0 - [`FSIZE`](qsp-keyword-sys-var.md#fsize) - [`FUNC`](qsp-keyword-functions.md#func) - [`$GETOBJ`](qsp-keyword-functions.md#getobj) -- [`GOSUB`](qsp-keyword-operators.md#gosub) -- [`GOTO`](qsp-keyword-operators.md#goto) -- [`GS`](qsp-keyword-operators.md#gosub) -- [`GT`](qsp-keyword-operators.md#goto) -- [`IF`](qsp-keyword-operators.md#if) +- [`GOSUB`](qsp-keyword-statements.md#gosub) +- [`GOTO`](qsp-keyword-statements.md#goto) +- [`GS`](qsp-keyword-statements.md#gosub) +- [`GT`](qsp-keyword-statements.md#goto) +- [`IF`](qsp-keyword-statements.md#if) - [`IIF`](qsp-keyword-functions.md#iif) -- [`INCLIB`](qsp-keyword-operators.md#inclib) - 5.8.0 +- [`INCLIB`](qsp-keyword-statements.md#inclib) - 5.8.0 - [`$INPUT`](qsp-keyword-functions.md#input) - [`INSTR`](qsp-keyword-functions.md#instr) - [`ISNUM`](qsp-keyword-functions.md#isnum) - [`ISPLAY`](qsp-keyword-functions.md#isplay) -- [`JUMP`](qsp-keyword-operators.md#jump) -- [`KILLALL`](qsp-keyword-operators.md#killall) -- [`KILLOBJ`](qsp-keyword-operators.md#killobj) -- ~~[`KILLQST`](qsp-keyword-operators.md#freelib)~~ -- [`KILLVAR`](qsp-keyword-operators.md#killvar) +- [`JUMP`](qsp-keyword-statements.md#jump) +- [`KILLALL`](qsp-keyword-statements.md#killall) +- [`KILLOBJ`](qsp-keyword-statements.md#killobj) +- ~~[`KILLQST`](qsp-keyword-statements.md#freelib)~~ +- [`KILLVAR`](qsp-keyword-statements.md#killvar) - [`$LCASE`](qsp-keyword-functions.md#lcase) - [`LCOLOR`](qsp-keyword-sys-var.md#lcolor) - [`LEN`](qsp-keyword-functions.md#len) -- [`LET`](qsp-keyword-operators.md#let) -- [`LOC`](qsp-keyword-operacion.md#loc) -- [`LOCAL`](qsp-keyword-operators.md#local) - 5.8.0 -- [`LOOP`](qsp-keyword-operators.md#loop) - 5.8.0 +- [`LET`](qsp-keyword-statements.md#let) +- [`LOC`](qsp-keyword-operators.md#loc) +- [`LOCAL`](qsp-keyword-statements.md#local) - 5.8.0 +- [`LOOP`](qsp-keyword-statements.md#loop) - 5.8.0 - [`$MAINTXT`](qsp-keyword-functions.md#maintxt) - [`MAX`](qsp-keyword-functions.md#max) -- [`MENU`](qsp-keyword-operators.md#menu) +- [`MENU`](qsp-keyword-statements.md#menu) - [`$MID`](qsp-keyword-functions.md#mid) - [`MIN`](qsp-keyword-functions.md#min) -- [`MOD`](qsp-keyword-operacion.md#mod) +- [`MOD`](qsp-keyword-operators.md#mod) - [`MSECSCOUNT`](qsp-keyword-functions.md#msecscount) -- [`MSG`](qsp-keyword-operators.md#msg) -- [`NL`](qsp-keyword-operators.md#nl-1) -- [`*NL`](qsp-keyword-operators.md#nl) -- [`NO`](qsp-keyword-operacion.md#no) +- [`MSG`](qsp-keyword-statements.md#msg) +- [`NL`](qsp-keyword-statements.md#nl-1) +- [`*NL`](qsp-keyword-statements.md#nl) +- [`NO`](qsp-keyword-operators.md#no) - [`NOSAVE`](qsp-keyword-sys-var.md#nosave) -- [`OBJ`](qsp-keyword-operacion.md#obj) +- [`OBJ`](qsp-keyword-operators.md#obj) - [`$ONACTSEL`](qsp-keyword-sys-var.md#onactsel) - [`$ONGLOAD`](qsp-keyword-sys-var.md#ongload) - [`$ONGSAVE`](qsp-keyword-sys-var.md#ongsave) @@ -135,33 +135,33 @@ sidebar_position: 6 - [`$ONOBJADD`](qsp-keyword-sys-var.md#onobjadd) - [`$ONOBJDEL`](qsp-keyword-sys-var.md#onobjdel) - [`$ONOBJSEL`](qsp-keyword-sys-var.md#onobjsel) -- [`OPENGAME`](qsp-keyword-operators.md#opengame) -- [`OPENQST`](qsp-keyword-operators.md#openqst) -- [`OR`](qsp-keyword-operacion.md#or) -- [`P`](qsp-keyword-operators.md#p-1) -- [`*P`](qsp-keyword-operators.md#p) -- [`PL`](qsp-keyword-operators.md#pl-1) -- [`*PL`](qsp-keyword-operators.md#pl) -- [`PLAY`](qsp-keyword-operators.md#play) +- [`OPENGAME`](qsp-keyword-statements.md#opengame) +- [`OPENQST`](qsp-keyword-statements.md#openqst) +- [`OR`](qsp-keyword-operators.md#or) +- [`P`](qsp-keyword-statements.md#p-1) +- [`*P`](qsp-keyword-statements.md#p) +- [`PL`](qsp-keyword-statements.md#pl-1) +- [`*PL`](qsp-keyword-statements.md#pl) +- [`PLAY`](qsp-keyword-statements.md#play) - [`$QSPVER`](qsp-keyword-functions.md#qspver) - [`RAND`](qsp-keyword-functions.md#rand) -- [`REFINT`](qsp-keyword-operators.md#refint) +- [`REFINT`](qsp-keyword-statements.md#refint) - [`$REPLACE`](qsp-keyword-functions.md#replace) - [`RESULT`](qsp-keyword-sys-var.md#result) - [`RGB`](qsp-keyword-functions.md#rgb) - [`RND`](qsp-keyword-functions.md#rnd) -- [`SAVEGAME`](qsp-keyword-operators.md#savegame) -- [`SCANSTR`](qsp-keyword-operators.md#scanstr) - 5.9.0 +- [`SAVEGAME`](qsp-keyword-statements.md#savegame) +- [`SCANSTR`](qsp-keyword-statements.md#scanstr) - 5.9.0 - [`$SELACT`](qsp-keyword-functions.md#selact) - [`$SELOBJ`](qsp-keyword-functions.md#selobj) -- [`SET`](qsp-keyword-operators.md#set) -- [`SETTIMER`](qsp-keyword-operators.md#settimer) -- [`SETVAR`](qsp-keyword-operators.md#setvar) - 5.9.1 -- [`SHOWACTS`](qsp-keyword-operators.md#showacts) -- [`SHOWINPUT`](qsp-keyword-operators.md#showinput) -- [`SHOWOBJS`](qsp-keyword-operators.md#showobjs) -- [`SHOWSTAT`](qsp-keyword-operators.md#showstat) -- [`SORTARR`](qsp-keyword-operators.md#sortarr) - 5.9.0 +- [`SET`](qsp-keyword-statements.md#set) +- [`SETTIMER`](qsp-keyword-statements.md#settimer) +- [`SETVAR`](qsp-keyword-statements.md#setvar) - 5.9.1 +- [`SHOWACTS`](qsp-keyword-statements.md#showacts) +- [`SHOWINPUT`](qsp-keyword-statements.md#showinput) +- [`SHOWOBJS`](qsp-keyword-statements.md#showobjs) +- [`SHOWSTAT`](qsp-keyword-statements.md#showstat) +- [`SORTARR`](qsp-keyword-statements.md#sortarr) - 5.9.0 - [`$STATTXT`](qsp-keyword-functions.md#stattxt) - [`$STR`](qsp-keyword-functions.md#str) - [`STRCOMP`](qsp-keyword-functions.md#strcomp) @@ -169,15 +169,15 @@ sidebar_position: 6 - [`STRPOS`](qsp-keyword-functions.md#strpos) - [`$TRIM`](qsp-keyword-functions.md#trim) - [`$UCASE`](qsp-keyword-functions.md#ucase) -- [`UNPACKARR`](qsp-keyword-operators.md#unpackarr) - 5.9.1 -- [`UNSEL`](qsp-keyword-operators.md#unselect) -- [`UNSELECT`](qsp-keyword-operators.md#unselect) +- [`UNPACKARR`](qsp-keyword-statements.md#unpackarr) - 5.9.1 +- [`UNSEL`](qsp-keyword-statements.md#unselect) +- [`UNSELECT`](qsp-keyword-statements.md#unselect) - [`USEHTML`](qsp-keyword-sys-var.md#usehtml) - [`$USERCOM`](qsp-keyword-sys-var.md#usercom) - [`$USER_TEXT`](qsp-keyword-functions.md#user_text) - [`$USRTXT`](qsp-keyword-functions.md#user_text) - [`VAL`](qsp-keyword-functions.md#val) -- [`VIEW`](qsp-keyword-operators.md#view) -- [`WAIT`](qsp-keyword-operators.md#wait) -- [`XGOTO`](qsp-keyword-operators.md#xgoto) -- [`XGT`](qsp-keyword-operators.md#xgoto) +- [`VIEW`](qsp-keyword-statements.md#view) +- [`WAIT`](qsp-keyword-statements.md#wait) +- [`XGOTO`](qsp-keyword-statements.md#xgoto) +- [`XGT`](qsp-keyword-statements.md#xgoto) diff --git a/docs/language/qsp-keywords/qsp-keyword-functions.md b/docs/language/qsp-keywords/qsp-keyword-functions.md index b154a4b..2024deb 100644 --- a/docs/language/qsp-keywords/qsp-keyword-functions.md +++ b/docs/language/qsp-keywords/qsp-keyword-functions.md @@ -119,7 +119,7 @@ dyneval("code = 123 + 890") code ``` -См. также [оператор `DYNAMIC`](qsp-keyword-operators.md#dynamic). +См. также [оператор `DYNAMIC`](qsp-keyword-statements.md#dynamic). ## `$FUNC` diff --git a/docs/language/qsp-keywords/qsp-keyword-operacion.md b/docs/language/qsp-keywords/qsp-keyword-operacion.md deleted file mode 100644 index 98bce6d..0000000 --- a/docs/language/qsp-keywords/qsp-keyword-operacion.md +++ /dev/null @@ -1,1261 +0,0 @@ ---- -sidebar_position: 1 ---- - -# Операции - -Список операций для плеера версии 5.8.0 в порядке возрастания приоритета: - -- `OR` -- `AND` -- `NO` -- `=`, `<`, `>`, `!`, `<>`, `<=`, `>=`, `=<`, `=>` (операции сравнения) -- `OBJ`, `LOC` -- `&` (конкатенация) -- `+`, `-` (сложение, вычитание) -- `MOD` -- `*`, `/` (умножение, деление) -- `-` (унарный минус) -- `([выр])` - выражения в скобках - -Операции записанные на одной строке имеют одинаковый приоритет и выполняются по порядку слева направо, если присутствуют на одном уровне в выражении. - -Операции в скобках имеют приоритет перед другими операциями. - -Вычисление значений функций имеет приоритет перед всеми операциями. - -Верным считается числовое выражение, значение которого отлично от `0`. При значении `0` выражение считается ложным. Для значения "верно" настоятельно рекомендуется использовать `1` для совместимости с логическими операциями и функциями, возвращающими логические значения. - -:::note[5.7.0] -В более старых версиях плееров порядок приоритета был иной. - -- `&` -- `OR` -- `AND` -- `OBJ`, `LOC`, `NO` -- `=`, `<`, `>`, `!`, `<>`, `<=`, `>=`, `=<`, `=>` -- `+`, `-` -- `MOD` -- `*`, `/` -- `+`, `-` (унарные) - -::: - -**Некоторые особенности операций сравнения:** - -- Операции сравнения возвращают `1` (верно) или `0` (неверно) в зависимости от результата сравнения. -- При сравнении чисел всё просто: - - из двух положительных чисел положительное число большее по модулю будет считаться большим; - - отрицательное число всегда меньше не отрицательного (положительное и нуль); - - положительное число всегда больше не положительного (отрицательное и нуль); - - из двух отрицательных чисел отрицательное число большее по модулю будет считаться меньшим. -- При сравнении строк происходит посимвольное сравнение слева направо: - - большим считается символ, который в таблице символов стоит позже. Можно опираться на алфавитную последовательность символов, чтобы понять, какая строка окажется большей. Тогда символ '`z`' будет больше символа '`a`'. Примеры: - - ```qsp - 'z' > 'a' & ! вернёт 1 - 'z' > 'az' & ! вернёт 1 - 'akz' > 'akk' & ! вернёт 1 - ``` - - - при сравнении любой непустой строки с пустой строкой пустая строка будет считаться меньшей: - - ```qsp - ' ' > '' & ! вернёт 1 - 'a' > '' & ! вернёт 1 - 'z' > '' & ! вернёт 1 - 'akzakz' > 'akzak' & ! вернёт 1 - ``` - - :::tip[Можно считать,] - что отсутствующие символы в строке — это пустые символы (пустые строки), которые при сравнении с любым другим символом оказываются меньшим. - ::: - - - при сравнении строки с числом, плеер попытается преобразовать оба значения к числу. Если это удастся, будут сравниваться числа. Если не удастся — число будет преобразовано в строку, и будут сравниваться строки. - - ```qsp - 'zzz' > 123 & ! вернёт 1 - '123' > 92 & ! вернёт 1 - '123' > '92' & ! вернёт 0 - ``` - -- При сравнении кортежей происходит поэлементное сравнение слева направо: - - большим будет считаться тот кортеж, элемент которого оказался большим: - - ```qsp - [1, 2, 3] > [1, 2, 2] & ! вернёт 1 - [2, 2, 3] > [1, 2, 3] & ! вернёт 1 - ``` - - - при сравнении любого непустого кортежа с пустым кортежем, пустой кортеж будет считаться меньшим: - - ```qsp - [1] > [] & ! вернёт 1 - [''] > [] & ! вернёт 1 - [0] > [] & ! вернёт 1 - [1, 2] > [1] & ! вернёт 1 - [1, 2] < [9] & ! вернёт 1 - ``` - - :::tip[Можно считать,] - что отсутствующие элементы в кортеже — это пустые элементы, которые при сравнении с любым другим элементом оказываются меньшим. - ::: - - - при сравнении кортежей с числами или строками, число или строка будут сравниваться, как кортеж из одного элемента. Для упрощения понимания можно считать, что число или строка при сравнении преобразуются в кортеж: - - ```qsp - [8] < 9 & ! вернёт 1 - [9, 8] > 9 & ! вернёт 1 - [0, 0] > 9 & ! вернёт 0 - - [8, 9] > '8,9' & ! вернёт 0 - ['a', 'z'] < 'az' & ! вернёт 1 - ['a', 'z'] > 'a' & ! вернёт 1 - (['az'] = "az") & ! вернёт 1 - ``` - -:::warning[Рекомендуем:] -Не проводить сравнения значений разных типов, чтобы это не приводило к путанице. -::: - -## `*` (умножение) - -`*` — арифметическая операция "УМНОЖЕНИЕ". Перемножает два числа. Общая запись: - -```qsp -[#выражение 1] * [#выражение 2] -``` - -, где `[#выражение 1]` и `[#выражение 2]` — два любых числовых значения, или выражения. Результатом работы операции является произведение двух чисел. - -Примеры: - -```qsp -2 * 2 & ! вернёт 4 -4 * 2 & ! вернёт 8 -17 * 5 & ! вернёт 85 -37 * 100 & ! вернёт 3700 -``` - -Можно использовать с кортежами, значениями которых являются числа и/или другие кортежи, содержащие числа. Общая запись: - -```qsp -[%кортеж] * [#число] -``` - -В данном случае каждый элемент кортежа будет умножен на указанное число. Примеры: - -```qsp -%tuple = [4, 10, 16] -%a = %tuple * 2 -! %a будет равно [8, 20, 32] - -[4, 10] * 'b' & ! ошибка о несоответствии типов данных -``` - -Обратите внимание на последний пример. Ошибка о несоответствии типов данных возникает из-за того, что невозможно применить операцию умножения к строковому значению. Такая же ошибка возникнет, если кортеж будет содержать строковые значения. Однако перемножать между собой кортежи, содержащие только числовые значения можно: - -```qsp -*pl [2, 3] * [4, 5] -! [2 * [4,5], 3 * [4,5]] -! [[8,10],[12,15]] -``` - -В этом случае каждый элемент первого кортежа умножается на второй кортеж. Это и даёт нам в результате новый кортеж из двух кортежей. - -## `*=` (умножение-присвоение) - -`*=` — операция "УМНОЖЕНИЕ-ПРИСВОЕНИЕ". Сочетает в себе операции присвоения и умножения. Умножает значение указанной переменной на определённое число и возвращает результат той же переменной. Общая запись: - -```qsp -ИМЯ_МАССИВА *= [#выражение 1] -``` - -, где `ИМЯ_МАССИВА` — это название переменной (без кавычек), или название массива с указанием ячейки, а `[#выражение 1]` — любое числовое значение или выражение. - -Аналогично конструкции: - -```qsp -ИМЯ_МАССИВА = ИМЯ_МАССИВА*[#выражение 1] -``` - -Пример: - -```qsp -! мы заменяем две операции: присвоения и умножение -warrior = warrior * 2 -! на умножение-присвоение (действие аналогично) -warrior *= 2 -``` - -Если значением переменной `ИМЯ_МАССИВА` является кортеж, каждый элемент кортежа будет умножен на указанное число, а полученный таким образом кортеж присвоится переменной. Пример: - -```qsp -%tuple = [4, 10, 16] -%tuple *= 2 -! %tuple будет равно [8, 20, 32] -``` - -Нельзя умножать на значение строкового типа, это приведёт к ошибке о несоответствии типов данных. Так же и значения кортежа (и всех вложенных кортежей) при выполнении данной операции не должны содержать строковых значений. Однако можно выполнить умножение-присвоение с другим кортежем: - -```qsp -%tuple = [2, 3] -%tuple *= [4, 5] -! %tuple будет равно [[8,10],[12,15]] -``` - -:::warning[Обратите внимание.] -Умножение-присвоение с кортежем вызовет ошибку несоответствия типов данных, если тип переменной не является кортежем: - -```qsp -number = 4 -number *= [4,5] & ! ошибка о несоответствии типов данных -! так ошибки не будет, но в переменной окажется пустой кортеж: -%number *= [4,5] -``` - -::: - -## `+` (сложение) - -`+` — арифметическая операция "СЛОЖЕНИЕ". Суммирует два числа. Общая запись: - -```qsp -[выражение 1]+[выражение 2] -``` - -, где `[выражение 1]` и `[выражение 2]` — два любых значения, или выражения. Результатом работы операции является сумма двух значений. - -Примеры: - -```qsp -2+2 & ! вернёт 4 -4+2 & ! вернёт 6 -17+5 & ! вернёт 22 -37+100 & ! вернёт 137 -``` - -При "суммировании" строковых значений производится [конкатенация](qsp-keyword-operacion.md#-конкатенация), то есть "склеивание" строк: - -```qsp -! на экран будет выведена строка "2627" -"26"+"27" -``` - -Если значения "прибавляются" к кортежу, происходит суммирование каждого элемента кортежа с указанным значением: - -```qsp -%tuple = [4, 10, 16] -%a = %tuple + 2 -! %a будет равно [6, 12, 18] -``` - -Если складываются два кортежа, к значениям каждого элемента первого кортежа прибавляется второй кортеж: - -```qsp -[4, 10] + ['b', 'x'] -! [4 + ['b', 'x'], 10 + ['b', 'x']] -! [['4b','4x'], ['10b','10x']] -``` - -## `+=` (сложение-присвоение) - -`+=`, `(инкремент)` — операция "ИНКРЕМЕНТ", сочетающая в себе операции присвоения и сложения. Прибавляет к текущему значению переменной указанное значение. Общая запись: - -```qsp -ИМЯ_МАССИВА += [выражение 1] -``` - -, где `ИМЯ_МАССИВА` — это название переменной (без кавычек), или название массива с указанием ячейки, а `[выражение 1]` — любое значение или выражение. - -Аналогично конструкции: - -```qsp -ИМЯ_МАССИВА = ИМЯ_МАССИВА + [выражение 1] -``` - -Пример: - -```qsp -! мы заменяем две операции: присвоения и сложения -warrior = warrior + 15 -! на инкремент (действие аналогично) -warrior += 15 -``` - -Возможно так же проводить инкремент со строковыми значениями, работает как [конкатенация](qsp-keyword-operacion.md#-конкатенация): - -```qsp -$text += " (может быть тут что-то написано)" -``` - -Если значением переменной `ИМЯ_МАССИВА` является кортеж, каждый элемент кортежа будет суммирован с указанным значением, а полученный таким образом кортеж присвоится переменной. Пример: - -```qsp -%tuple = [4, 10, 16] -%tuple += 2 -! %tuple будет равно [6, 12, 18] -``` - -Можно выполнить сложение-присвоение с другим кортежем: - -```qsp -%tuple = [2, 3] -%tuple += [4, 5] -! %tuple будет равно [[6,7],[7,8]] -``` - -:::warning Обратите внимание. -Сложение-присвоение с кортежем вызовет ошибку несоответствия типов данных, если тип переменной не является кортежем: - -```qsp -number = 4 -number += [4,5] & ! ошибка о несоответствии типов данных -! так ошибки не будет, но в переменной окажется пустой кортеж: -%number += [4,5] -``` - -::: - -:::tip[Примечание] -Инкремент — во многих языках программирования это операция, которая выполняет увеличение переменной. Чаще всего под инкрементом подразумевается увеличение переменной на `1`. -::: - -## `-` (вычитание) - -`-` — арифметическая операция "ВЫЧИТАНИЕ". Вычитает одно число из другого. Общая запись: - -```qsp -[#выражение 1] - [#выражение 2] -``` - -, где `[#выражение 1]` и `[#выражение 2]` — два числовых значения, или выражения. Результатом работы операции является разность двух значений. - -Примеры: - -```qsp -2 - 2 & ! вернёт 0 -4 - 2 & ! вернёт 2 -17 - 5 & ! вернёт 12 -37 - 100 & ! вернёт -63 -``` - -Можно использовать с кортежами, значениями которых являются числа и/или другие кортежи, содержащие числа. Общая запись: - -```qsp -[%кортеж] - [#число] -``` - -В данном случае из каждого элемента кортежа будет вычтено указанное число. Примеры: - -```qsp -%tuple = [4, 10, 16] -%a = %tuple - 2 -! %a будет равно [2, 8, 14] - -[4, 10] - 'b' & ! ошибка о несоответствии типов данных -``` - -Обратите внимание на последний пример. Ошибка о несоответствии типов данных возникает из-за того, что невозможно применить операцию вычитания к строковому значению. Такая же ошибка возникнет, если кортеж будет содержать строковые значения. Однако из одного кортежа другой кортеж можно, если оба кортежа содержат только числовые значения: - -```qsp -*pl [2, 3] - [4, 5] -! [2 - [4,5], 3 - [4,5]] -! [2 + ([4,5] * -1), 3 + ([4,5] * -1)] -! [[-4, -5] + 2, [-4,-5] + 3] -! [[-2,-3],[-1,-2]] -``` - -В этом случае из каждого элемента первого кортежа вычитается второй кортеж. Если последовательно раскрыть скобки и произвести все необходимые математические операции, получится новый кортеж, содержащий другие кортежи с результатами. - -## `-=` (вычитание-присвоение) - -**`-=`, `(декремент)`** — операция "ДЕКРЕМЕНТ", сочетающая в себе операции присвоения и вычитания. Вычитает из текущего значения переменной указанное значение. Общая запись: - -```qsp -ИМЯ_МАССИВА -= [#выражение 1] -``` - -, где `ИМЯ_МАССИВА` — это название переменной (без кавычек), или название массива с указанием ячейки, а `[#выражение 1]` — любое числовое значение или выражение. - -Аналогично конструкции: - -```qsp -ИМЯ_МАССИВА = ИМЯ_МАССИВА - [#выражение 1] -``` - -Пример: - -```qsp -! мы заменяем две операции: присвоения и вычитания -warrior = warrior - 15 -! на декремент (действие аналогично) -warrior -= 15 -``` - -Если значением переменной `ИМЯ_МАССИВА` является кортеж, из каждого элемента кортежа будет вычитаться указанное число, а полученный таким образом кортеж присвоится переменной. Пример: - -```qsp -%tuple = [4, 10, 16] -%tuple -= 2 -! %tuple будет равно [2, 8, 14] -``` - -Нельзя вычитать значение строкового типа, это приведёт к ошибке о несоответствии типов данных. Так же и значения кортежа (и всех вложенных кортежей) при выполнении данной операции не должны содержать строковых значений. Однако можно выполнить вычитание-присвоение с другим кортежем: - -```qsp -%tuple = [2, 3] -%tuple -= [4, 5] -! %tuple будет равно [[-2,-3],[-1,-2]] -``` - -:::warning[Обратите внимание.] -Вычитание-присвоение с кортежем вызовет ошибку несоответствия типов данных, если тип переменной не является кортежем: - -```qsp -number = 4 -number -= [4,5] & ! ошибка о несоответствии типов данных -! так ошибки не будет, но в переменной окажется пустой кортеж: -%number -= [4,5] -``` - -::: - -:::tip[Примечание] -Декремент — во многих языках программирования это операция, которая выполняет уменьшение переменной. Чаще всего под декрементом подразумевается уменьшение переменной на `1`. -::: - -## `-` (унарный минус) - -**унарный `-`** — унарная операции. Общая запись: - -```qsp --[#выражение] -``` - -, где `[#выражение]` — любое числовое значение или выражение. Результатом работы этой операций является то же самое значение, только с противоположным знаком. - -Примеры: - -```qsp --2 & ! вернёт -2 --(3+6) & ! вернёт -9 --(-27) & ! вернёт 27 -``` - -Унарный минус можно использовать перед кортежем, содержащим только числовые значения. Это выражение вернёт новый кортеж, в котором знак каждого элемента будет изменён на противоположный: - -```qsp -- [2, 3, -1, -17, 5] -! [-2, -3, 1, 17, -5] -``` - -:::note[5.7.0] - -В более ранних версиях плеера существовала операция "унарный плюс": - -```qsp -+(6+7) -``` - -По сути, она ничего не делала, поэтому было решено от неё отказаться. -::: - -## `/` (деление) - -`/` — арифметическая операция "ДЕЛЕНИЕ". Общая запись: - -```qsp -[#выражение 1] / [#выражение 2] -``` - -, где `[#выражение 1]` и `[#выражение 2]` — два любых числовых значения, или выражения. Значение `[#выражение 2]` не должно быть равным нулю. Результатом работы операции является частное от деления двух чисел. - -Поскольку QSP поддерживает только целочисленные значения, деление производится так же нацело, без округления, с отсечением дробной части. - -Примеры: - -```qsp -2 / 2 & ! вернёт 1 -4 / 2 & ! вернёт 2 -17 / 5 & ! вернёт 3 -37 / 100 & ! вернёт 0 -``` - -Можно использовать с кортежами, значениями которых являются числа и/или другие кортежи, содержащие числа. Общая запись: - -```qsp -[%кортеж] / [#число] -``` - -В данном случае каждый элемент кортежа будет разделён на указанное число. Примеры: - -```qsp -%tuple = [4, 10, 16] -%a = %tuple / 2 -! %a будет равно [2, 5, 8] - -[4, 10] / 'b' & ! ошибка о несоответствии типов данных -``` - -Обратите внимание на последний пример. Ошибка о несоответствии типов данных возникает из-за того, что невозможно применить операцию деления к строковому значению. Такая же ошибка возникнет, если кортеж будет содержать строковые значения. Однако делить друг на друга кортежи, содержащие только числа можно: - -```qsp -*pl [30, 60] / [2, 6] -! [30 / [2,6], 60 / [2,6]] -! [[15,5],[30,10]] -``` - -В этом случае каждый элемент первого кортежа "делится" на второй кортеж. Это даёт нам в результате новый кортеж из двух кортежей. - -## `/=` (деление-присвоение) - -`/=` — операция "ДЕЛЕНИЕ-ПРИСВОЕНИЕ". Сочетает в себе операции присвоения и деления. Делит значение указанной переменной на определённое число и возвращает результат той же переменной. Общая запись: - -```qsp -ИМЯ_МАССИВА /= [#выражение 1] -``` - -, где `ИМЯ_МАССИВА` — это название переменной (без кавычек), или название массива с указанием ячейки, а `[#выражение 1]` — любое числовое значение или выражение. - -Аналогично конструкции: - -```qsp -ИМЯ_МАССИВА = ИМЯ_МАССИВА / [#выражение 1] -``` - -Пример: - -```qsp -! мы заменяем две операции: присвоения и деления -warrior = warrior / 2 -! на деление-присвоение (действие аналогично) -warrior /= 2 -``` - -Если значением переменной `ИМЯ_МАССИВА` является кортеж, каждый элемент кортежа будет разделён на указанное число, а полученный таким образом кортеж присвоится переменной. Пример: - -```qsp -%tuple = [4, 10, 16] -%tuple /= 2 -! %tuple будет равно [2, 5, 8] -``` - -Нельзя делить на значение строкового типа, это приведёт к ошибке о несоответствии типов данных. Так же и значения кортежа (и всех вложенных кортежей) при выполнении данной операции не должны содержать строковых значений. Однако можно выполнить деление-присвоение с другим кортежем: - -```qsp -%tuple = [10, 30] -%tuple /= [5, 2] -! %tuple будет равно [[2,5],[6,15]] -``` - -:::warning[Обратите внимание.] -Деление-присвоение с кортежем вызовет ошибку несоответствия типов данных, если тип переменной не является кортежем: - -```qsp -number = 4 -number /= [4,5] & ! ошибка о несоответствии типов данных -! так ошибки не будет, но в переменной окажется пустой кортеж: -%number /= [4,5] -``` - -::: - -## `<` (меньше) - -`<` — операция сравнения "МЕНЬШЕ". Общая запись: - -```qsp -[выражение_1] < [выражение_2] -``` - -Если значение выражения `[выражение_1]` меньше значения выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт `0`. Иными словами: верно, если первое меньше второго. - -Примеры: - -```qsp -! 2 меньше 4 — вернёт 1 -2 < 4 -! 5 не меньше 5 — вернёт 0 -5 < 5 -! 7 не меньше 3 — вернёт 0 -7 < 3 -``` - -Сравнивать можно текстовые значения: - -```qsp -"a" < "z" & ! верно -"z" < "zz" & ! верно -"aaaaaa" < "z" & ! верно -``` - -И можно сравнивать кортежи: - -```qsp -[1, 2, 3] < [1, 2, 9] & ! верно -[1, 2, 3] < [2, 2, 3] & ! верно -[1, 2] < [1, 2, 3] & ! верно -``` - -## `<=` (меньше либо равно) - -`<=` — операция сравнения "МЕНЬШЕ ЛИБО РАВНО". Общая запись: - -```qsp -[выражение_1] <= [выражение_2] -``` - -Если значение выражения `[выражение_1]` меньше либо равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт `0`. Иными словами: верно, если первое меньше второго, либо равно ему. - -Примеры: - -```qsp -! 2 меньше 4 — вернёт 1 -2 <= 4 -! 5 равно 5 — вернёт 1 -5 <= 5 -! 7 не меньше трёх и не равно ему -7 <= 3 & ! вернёт 0 -``` - -Аналогично "`=<`" и конструкциям: - -```qsp -([выражение_1] < [выражение_2]) or ([выражение_1] = [выражение_2]) - -no [выражение_1] > [выражение_2] -``` - -Сравнивать можно и текстовые значения: - -```qsp -"a" <= "z" & ! верно -"z" <= "zz" & ! верно -"aaaaaa" <= "z" & ! верно -"z" <= "z" & ! верно -``` - -И кортежи: - -```qsp -[1, 2, 3] <= [1, 2, 9] & ! верно -[1, 2, 3] <= [2, 2, 3] & ! верно -[1, 2] <= [1, 2, 3] & ! верно -[1, 2, 3] <= [1, 2, 3] & ! верно -``` - -## `<>` (не равно) - -`<>` — операция сравнения "НЕ РАВНО". Общая запись: - -```qsp -[выражение_1] <> [выражение_2] -``` - -Если значение выражения `[выражение_1]` не равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт `0`. Иными словами: верно, если выражения не равны. - -Аналогично "`!`", или конструкции: - -```qsp -no [выражение_1] = [выражение_2] -``` - -Примеры: - -```qsp -! 2 не равно 4 — вернёт 1 -2 <> 4 -! 5 равно 5 — вернёт 0 -5 <> 5 -``` - -Можно сравнивать и строковые значения: - -```qsp -"abc" <> "def" & ! вернёт 1 -"abc" <> "abc" & ! вернёт 0 -``` - -Можно сравнивать кортежи: - -```qsp -[1, 2, 3] <> [4, 6, 7] & ! вернёт 1 -[1, 2, 3] <> [1, 2, 3] & ! вернёт 0 -``` - -## `=` (равно) - -`=` — операция сравнения "РАВНО". Общая запись: - -```qsp -[выражение_1] = [выражение_2] -``` - -Если значение выражения `[выражение_1]` равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт `0`. Иными словами: верно, если выражения равны. - -Аналогично конструкции: - -```qsp -no [выражение_1] <> [выражение_2] -``` - -Примеры: - -```qsp -! 2 не равно 4 — вернёт 0 -(2 = 4) -! 5 равно 5 — вернёт 1 -(5 = 5) -``` - -Можно сравнивать и строковые значения: - -```qsp -("abc" = "def") & ! вернёт 0 -("abc" = "abc") & ! вернёт 1 -``` - -Можно сравнивать кортежи: - -```qsp -([1, 2, 3] = [4, 6, 7]) & ! вернёт 0 -([1, 2, 3] = [1, 2, 3]) & ! вернёт 1 -``` - -:::warning[Внимание!] -Не путайте с операцией [присвоения](#-присвоение). -::: - -## `=` (присвоение) - -`=` — операция присвоения. Общая запись: - -```qsp -ИМЯ_МАССИВА = [значение] -``` - -, где `ИМЯ_МАССИВА` — название переменной (не в кавычках), или название массива с указанием ячейки (не в кавычках), `[значение]` — любое значение или выражение. - -Примеры: - -```qsp -! переменной BOX присваиваем значение 13 -BOX = 13 -! переменной $text присваиваем значение "Строка текста" -$text = "Строка текста" -! нулевой ячейке массива day присваивается значение 365 -day[0] = 365 -! переменной tuple присваивается кортеж [1, 'unit', 3]: -%tuple = [1, 'unit', 3] -``` - -Имена строковых переменных/массивов должны начинаться с символа `$`. - -Имена переменных/массивов, содержащих кортежи должны начинаться с символа `%`. - -:::warning[Внимание!] -Операцию присвоения не следует путать с операцией сравнения "РАВНО", хотя они очень похожи: - -```qsp -! операция присвоения -alukard = 1000 -! операция сравнения -(alukard = 1000) -``` - -В этом случае плеер понимает, что внутри скобок находится операция сравнения, потому что скобки используются для записи выражений. Запись: - -```qsp -"abc" = "abc" -``` - -синтаксически ошибочна. Плеер выдаст ошибку: недопустимое название переменной/массива. Так как в этом случае он не понимает, что это операция сравнения. - -Если перед операцией сравнения явно стоит оператор, скобки можно не писать: - -```qsp -if alukard = 150: *pl "Не хватает сил" -*pl "abc" = "abc" -``` - -::: - -### Множественное присвоение - -Множественное присвоение позволяет одной командой `=` присвоить значения сразу нескольким переменным или ячейкам массива. Общая запись: - -```qsp -ИМЯ_МАССИВА_1, ИМЯ_МАССИВА_2, ... , ИМЯ_МАССИВА_N = [ЗНАЧЕНИЕ_1], [ЗНАЧЕНИЕ_2], ... , [ЗНАЧЕНИЕ_N] -``` - -, где слева от знака `=` пишутся имена переменных (или имена массивов с указанием индекса ячейки в квадратных скобках), а справа от знака `=` перечисляются значения, которые нужно присвоить переменным или ячейкам массивов. - -:::warning[Важно помнить!] -Слева от знака равенства должно быть столько же переменных, сколько справа значений. Число переменных, и число присваиваемых значений — должны совпадать. - -При распаковке кортежей это правило не соблюдается. -::: - -Примеры: - -```qsp -яблоки_в_кармане, яблоки_в_лукошке, яблоки_у_Лёшки = 58, 11, 19 -$строка_1, $строка_2 = 'Ехал Грека Через Реку', 'Видит Грека В Реке Рак' -$name, count = 'Старый меч', 2 -``` - -Вместо прямого указания значений можно присваивать значения других переменных, выражений, функций: - -```qsp -! три переменные = три значения -red, green, blue = rand(0,255), rand(0,255), rand(0,255) -! две переменные = два значения -яблоки_в_кармане, яблоки_в_лукошке = яблоки_у_Лёшки, яблоки_на_дереве+15 -``` - -Благодаря возможности одновременно присваивать значения сразу нескольким переменным, можно менять местами данные в двух переменных, не прибегая к помощи третьей: - -```qsp -! присваиваем пременным x и y значения 12 и 99 -x, y = 12, 99 -! меняем местами значения. Теперь в x находится число 99, а в y — 12 -x, y = y, x -``` - -### Распаковка кортежей - -Поскольку кортежи содержат в себе сразу несколько значений, запись присвоения значений переменным из кортежа может отличаться от привычной: - -```qsp -! %unit = [187, 94, 'steel', [0, 2]] -рост, вес, $материал, %координаты = %unit -``` - -Как видите, здесь у нас слева четыре имени переменной, а справа только одно имя переменной-кортежа. Такое присвоение называется распаковкой — значения извлекаются из кортежа и помещаются в указанные переменные. - -Точно так же распаковывается кортеж, даже не помещённый в переменную: - -```qsp -рост, вес, $материал, %координаты = [187, 94, 'steel', [0, 2]] -``` - -Такая запись мало чем отличается от множественного присвоения, поэтому внешние квадратные скобки не обязательны: - -```qsp -рост, вес, $материал, %координаты = 187, 94, 'steel', [0, 2] -``` - -Cледует подчеркнуть, что **множественное присвоение — это по сути распаковка кортежей**. - -Поскольку, если переменных слева от знака равенства будет больше, чем значений в кортеже, в "лишние" переменные запишутся значения по умолчанию для этих переменных, то и при множественном присвоении произойдёт то же самое. - -```qsp -r, g, b, a = [255, 188, 19] -! r = 255, g = 188, b = 19, a = 0 -raz, dva, tri, chetyre = 137, 61 -! raz = 137, dva = 61, tri = 0, chetyre = 0 -``` - -В то же время, если при множественном присвоении переменных слева от знака равенства будет меньше, чем значений справа, это вызовет ошибку о несоответствии типов данных: - -```qsp title="Несоответствие типов данных" -coords = 23, 34 -age, weight, material = 27, 94, 'steel', 'biorobot' -``` - -Если тип последней из перечисленных переменных будет кортеж, такое присвоение ошибку не вызовет: - -```qsp -age, weight, %type = 27, 94, 'steel', 'biorobot' -! age = 27, weight = 94, %type = ['steel', 'biorobot'] -``` - -## `=<` (равно либо меньше) - -:::warning[Внимание!] -Данная запись, хотя и допустима в QSP, к использованию не рекомендуется. Используйте "`<=` (меньше либо равно)" вместо этого. -::: - -`=<` — операция сравнения "РАВНО ЛИБО МЕНЬШЕ". Общая запись: - -```qsp -[выражение_1] =< [выражение_2] -``` - -Если значение выражения `[выражение_1]` меньше либо равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт 0. Иными словами: верно, если первое меньше второго, либо равно ему. - -Примеры: - -```qsp -! 2 меньше 4 — вернёт 1 -2 =< 4 -! 5 равно 5 — вернёт 1 -5 =< 5 -! 7 не меньше трёх и не равно ему -7 =< 3 & ! вернёт 0 -``` - -Аналогично "`<=`" и конструкциям: - -```qsp -([выражение_1] < [выражение_2]) or ([выражение_1] = [выражение_2]) - -no [выражение_1] > [выражение_2] -``` - -## `=>` (равно или больше) - -`=>` — операция сравнения "РАВНО ИЛИ БОЛЬШЕ". Общая запись: - -:::warning[Внимание!] -Данная запись, хотя и допустима в QSP, к использованию не рекомендуется. Используйте "`>=` (больше либо равно)" вместо этого. -::: - -```qsp -[выражение_1] => [выражение_2] -``` - -Если значение выражения `[выражение_1]` больше либо равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт 0. Иными словами: верно, если первое больше второго, либо равно ему. - -Примеры: - -```qsp -! 2 не меньше и не равно 4 — вернёт 0 -2 => 4 -! 5 равно 5 — вернёт 1 -5 => 5 -! 7 больше 3 -7 => 3 & ! вернёт 1 -``` - -Аналогично "`>=`" и конструкциям: - -```qsp -([выражение_1] > [выражение_2]) or ([выражение_1] = [выражение_2]) -no [выражение_1] < [выражение_2] -``` - -## `>` (больше) - -`>` — операция сравнения "БОЛЬШЕ". Общая запись: - -```qsp -[выражение_1] > [выражение_2] -``` - -Если значение выражения `[выражение_1]` больше значения выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт `0`. Иными словами: верно, если первое больше второго. - -Примеры: - -```qsp -! 2 не больше 4 — вернёт 0 -2 > 4 -! 5 не больше 5 — вернёт 0 -5 > 5 -! 7 больше 3 — вернёт 1 -7 > 3 -``` - -Сравнивать можно и текстовые значения, при этом символы сравниваются поочерёдно, и большим считается символ, стоящий ближе к концу алфавита. - -```qsp -"z" > "a" & ! верно -"zz" > "z" & ! верно -"z" > "aaaaaa" & ! верно -``` - -И можно сравнивать кортежи: - -```qsp -[1, 2, 9] > [1, 2, 3] & ! верно -[1, 2, 3] > [2, 2, 3] & ! неверно -[1, 2, 3] > [1, 2] & ! верно -``` - -## `>=` (больше либо равно) - -`>=` — операция сравнения "БОЛЬШЕ ЛИБО РАВНО". Общая запись: - -```qsp -[выражение_1] >= [выражение_2] -``` - -Если значение выражения `[выражение_1]` больше либо равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт 0. Иными словами: верно, если первое больше второго, либо равно ему. - -Примеры: - -```qsp -! 2 не меньше и не равно 4 — вернёт 0 -2 >= 4 -! 5 равно 5 — вернёт 1 -5 >= 5 -! 7 больше 3 -7 >= 3 & ! вернёт 1 -``` - -Аналогично "`=>`" и конструкциям: - -```qsp -([выражение_1] > [выражение_2]) or ([выражение_1] = [выражение_2]) -no [выражение_1] < [выражение_2] -``` - -Сравнивать можно и текстовые значения, при этом символы сравниваются поочерёдно, и большим считается символ, стоящий ближе к концу алфавита. - -```qsp -"z" >= "a" & ! верно -"zz" >= "z" & ! верно -"z" >= "aaaaaa" & ! верно -"z" >= "z" & ! верно -``` - -И кортежи: - -```qsp -[1, 2, 9] >= [1, 2, 3] & ! верно -[1, 2, 3] >= [2, 2, 3] & ! не верно -[1, 2] >= [1, 2, 3] & ! не верно -[1, 2, 3] >= [1, 2, 3] & ! верно -``` - -## `!` (не равно) - -:::warning[Внимание!] -Не путайте с оператором комментария. - -Для улучшения читаемости кода рекомендуем использовать `<>`. -::: - -`!` — операция сравнения "НЕ РАВНО". Общая запись: - -```qsp -[выражение_1]![выражение_2] -``` - -Если значение выражения `[выражение_1]` не равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт `0`. Иными словами: верно, если выражения не равны. - -Аналогично "`<>`", или конструкции: - -```qsp -no [выражение_1] = [выражение_2] -``` - -Примеры: - -```qsp -! 2 не равно 4 — вернёт 1 -2 ! 4 -! 5 равно 5 — вернёт 0 -5 ! 5 -``` - -## `&` (конкатенация) - -`&` — конкатенация, операция объединения строковых выражений или кортежей. Общая запись: - -```qsp -([$выражение 1] & [$выражение 2]) -([%выражение 1] & [%выражение 2]) -``` - -:::warning[внимание!] -Конкатенацию всегда нужно заключать в скобки! -::: - -Если попытаться объединить числовые значения, они будут преобразованы к строкам, а затем строки будут объединены. - -Примеры: - -```qsp -*pl ('привет, ' & 'Мир!') -! на экране увидим строку 'привет, Мир!' -*pl ([1, 2, 3] & [4, 5, 6]) -! на экране увидим кортеж [1, 2, 3, 4, 5, 6] -``` - -:::warning[внимание!] -Не путайте с символом перечисления команд: - -```qsp -! в данном случае на экран будут -! последовательно выведены строки "26" и "27" -"26" & "27" -! а здесь на экран будет выведена строка "2627" -("26" & "27") -``` - -::: - -:::tip -Не рекомендуется использовать данную операцию для объединения строк, поскольку строки можно объединять через [`+`](qsp-keyword-operacion.md#-сложение): - -```qsp -! на экран будет выведена строка "2627" -"26"+"27" -``` - -Такая запись создаёт меньше путаницы при чтении кода и работает аналогичным образом. - -Склеить два кортежа в один при помощи операции `+` не получится: - -```qsp -[2, 5] + [3, 7] -! на экране будет кортеж: [[5,9],[8,12]] -``` - -::: - -## AND - -`AND` — логическое "И". Общая запись: - -```qsp -[#выражение 1] AND [#выражение 2] -``` - -Всё данное выражение будет верным, если верны выражения `[#выражение 1]` и `[#выражение 2]`. - -Примеры: - -```qsp -! обе части выражения верны, значит и всё выражение верно -(2 = 2) and (3 <> 2) & ! выражение вернёт 1 (правда) -! одна часть выражения не верна, значит всё выражение неверно -(2 <> 2) and (3 <> 2) & ! выражение вернёт 0 (ложь) -! обе части выражения не верны, значит и всё выражение не верно -(2 <> 2) and (3 = 2) & ! выражение вернёт 0 (ложь) -``` - -:::note[5.7.0] -В старых версиях плеера операция была побитовой. -::: - -## LOC - -`LOC` — операция проверяет наличие локации и возвращает `1`, если локация есть, и — `0`, если локации нет. Общая запись: - -```qsp -LOC([$локация]) -``` - -, где `[$локация]` — название локации, наличие которой необходимо проверить в игре. Выражение верно, если локация существует в игре. - -Примеры: - -```qsp -! проверяет, есть ли в игре локация "начало" -loc("начало") & ! если локация есть, возвращает 1 - -! если локация "улица" не добавлена в игру -if loc("улица") = 0: - act "Выйти на улицу": *pl "Я не могу выйти на улицу, дверь не отпирается." -end -``` - -## MOD - -`MOD` — операция вычисляет остаток от деления двух чисел. Общая запись: - -```qsp -[#выражение 1] MOD [#выражение 2] -``` - -, где `[#выражение 1]` — делимое, `[#выражение 2]` — делитель. - -Примеры: - -```qsp -! 4 делится на 2 нацело -4 mod 2 & ! возвращает 0 -! 5 не делится на 2 нацело -5 mod 2 & ! возвращает 1 -! 13 не делится на 10 нацело -13 mod 10 & ! возвращает 3 -``` - -Остаток от деления отрицательного числа будет отрицательным числом. - -## NO - -`NO` — операция отрицания. Общая запись: - -```qsp -NO [#выражение] -``` - -Если `[#выражение]` верно, то всё выражение неверно, и наоборот. Иными словами, возвращает `0`, если значение выражения отлично от нуля, и возвращает `1`, если значение выражения равно `0`. - -Пример: - -```qsp -! 4 равно 4 это верно, значит всё выражение неверно -no (4 = 4) & ! вернёт 0 (ложь) -! можно читать как вопрос: четыре не равно четырём? Нет — ложь. - -! то, что 5 равно 3, — неверно, значит всё выражение верно -no (5 = 3) & ! вернёт 1 (правда) -! можно читать как вопрос: пять не равно трём? Да — правда. -``` - -:::note[5.7.0] -В старых версиях плеера операция была побитовой. -::: - -## OBJ - -`OBJ` — операция проверяет наличие предмета в инвентаре и возвращает `1`, если предмет есть, и — `0`, если предмета нет. Общая запись: - -```qsp -OBJ([$название]) -``` - -, где `[$название]` — название предмета, наличие которого необходимо проверить в окне предметов. Выражение верно, если предмет добавлен в окно предметов. - -Примеры: - -```qsp -! проверяет, добавлен ли в окно предметов предмет "Отвёртка" -obj("Отвёртка") & ! если предмет есть, возвращает 1 - -! в зависимости от наличия того или иного предмета -! выводится то или иное действие -if obj("Полный кувшин") = 1: - act "Опустошить кувшин": - delobj "Полный кувшин" - addobj "Пустой квушин" - goto $curloc - end -elseif obj("Пустой кувшин") = 1: - act "Наполнить кувшин": - addobj "Полный кувшин" - delobj "Пустой квушин" - goto $curloc - end -end -``` - -## OR - -`OR` — логическое "ИЛИ". Общая запись: - -```qsp -[#выражение 1] OR [#выражение 2] -``` - -Всё данное выражение будет верным, если хотя бы одно из выражений `[#выражение 1]` и `[#выражение 2]` верно. - -Примеры: - -```qsp -! обе части выражения верны, значит и всё выражение верно -(2 = 2) or (3 <> 2) & ! выражение вернёт 1 (правда) -! одна часть выражения верна, значит всё выражение верно -(2 <> 2) or (3 <> 2) & ! выражение вернёт 1 (правда) -! обе части выражения не верны, значит и всё выражение не верно -(2 <> 2) or (3 = 2) & ! выражение вернёт 0 (ложь) -``` - -:::note[5.7.0] -В старых версиях плеера операция была побитовой. -::: diff --git a/docs/language/qsp-keywords/qsp-keyword-operators.md b/docs/language/qsp-keywords/qsp-keyword-operators.md index c42aff2..8245e0e 100644 --- a/docs/language/qsp-keywords/qsp-keyword-operators.md +++ b/docs/language/qsp-keywords/qsp-keyword-operators.md @@ -1,2043 +1,1261 @@ --- -sidebar_position: 2 +sidebar_position: 1 --- -# Операторы +# Операции -## Неявный оператор +Список операций для плеера версии 5.8.0 в порядке возрастания приоритета: -Неявный оператор — это оператор, который не прописывается в коде QSP, но производит вывод значений на экран. Он подразумевается везде, где в команде присутствует выражение без оператора. Неявный оператор выводит в **Окно основного описания** значения таким же образом, как если бы вы использовали явное указание оператора `*pl`, то есть выводит значение и совершает переход на новую строку. Примеры: +- `OR` +- `AND` +- `NO` +- `=`, `<`, `>`, `!`, `<>`, `<=`, `>=`, `=<`, `=>` (операции сравнения) +- `OBJ`, `LOC` +- `&` (конкатенация) +- `+`, `-` (сложение, вычитание) +- `MOD` +- `*`, `/` (умножение, деление) +- `-` (унарный минус) +- `([выр])` - выражения в скобках -```qsp -$AAA + '989' -'Вы находитесь в парке' -'Преформатированная - - строка' -$curloc & ! выведет на экран название локации -``` - -В отличие от оператора `*pl` неявный оператор не выводит на экран пустую строку с переходом на новую строку, если ему не передаётся никакое значение. Это означает, что если функция не возвращает никакого значения, неявный оператор просто игнорируется. Пример: - -```qsp -# start -! это код локации, вызывающей локацию-функцию -$curloc -$func('foo') -$func('foo') -$curloc -- start - -# foo -! это код локации-функции -local i = 0 -- foo -``` - -В данном случае локация-функция `foo` ничего не возвращает, поэтому на экране мы увидим две строки со словом "start", между которыми не будет пустых строк, так как неявный оператор в строках с `$func` на локации `start` будет просто проигнорирован. Сравните с: +Операции записанные на одной строке имеют одинаковый приоритет и выполняются по порядку слева направо, если присутствуют на одном уровне в выражении. -```qsp -# start -! это код локации, вызывающей локацию-функцию -*pl $curloc -*pl $func('foo') -*pl $func('foo') -*pl $curloc -- start +Операции в скобках имеют приоритет перед другими операциями. -# foo -! это код локации-функции -local i=0 -- foo -``` +Вычисление значений функций имеет приоритет перед всеми операциями. -## `!` (комментарий) +Верным считается числовое выражение, значение которого отлично от `0`. При значении `0` выражение считается ложным. Для значения "верно" настоятельно рекомендуется использовать `1` для совместимости с логическими операциями и функциями, возвращающими логические значения. -`!` — оператор комментария. То, что находится в строке после оператора комментария, и до конца строки игнорируется интерпретатором. Оператор комментария позволяет "закомментировать" (выключить) ненужный временно оператор/функцию во время отладки игры. Кроме того, написание комментариев к коду программы является одним из признаков хорошего стиля программирования. - -Необходимо чётко понимать, что это именно оператор, поэтому если вы комментируете некую строку кода, то `!` должен стоять после `&`: - -```qsp -*pl "Hello, world!" & ! комментарий -``` - -Комментарии могут быть однострочными, то есть заканчиваться в той же строке, где стоит оператор комментария: - -```qsp -! однострочный комментарий -*pl "строка текста" & ! тоже однострочный комментарий -``` - -:::tip[Исключение] -Единственным исключением из этого правила является запись комментария после двоеточия в многострочных операторах: - -```qsp -act "Многострочное действие": ! комментарий - *pl "Текст на экране" -end -``` +:::note[5.7.0] +В более старых версиях плееров порядок приоритета был иной. + +- `&` +- `OR` +- `AND` +- `OBJ`, `LOC`, `NO` +- `=`, `<`, `>`, `!`, `<>`, `<=`, `>=`, `=<`, `=>` +- `+`, `-` +- `MOD` +- `*`, `/` +- `+`, `-` (унарные) ::: -Комментарии могут быть многострочными. Для этого после оператора комментария нужно записать кавычки, апострофы, или фигурные скобки. Например так: - -```qsp -! "это первая строка коммантария - это вторая строка комментария - это третья строка комментария -" -``` - -Многострочные комментарии могут принимать самые разнообразные формы: - -```qsp -! строка до кавычек " текст внутри кавычек -может переходить на другие строки " а так же { -можно использовать другие группы символов, чтобы -продолжать многострочный комментарий -} и комментарий не кончится, пока не кончится строка -``` - -## `*CLEAR` - -`*CLEAR` — очищает окно основного описания. Имеет краткую форму `*clr`. - -## `*NL` - -`*NL` — переход на новую строку, затем вывод текста в окне основного описания. Общая запись: - -```qsp -*NL [$текст] -``` - -, где `[$текст]` — любая строка текста, число, или выражение любого типа. Если `[$текст]` отсутствует, происходит просто переход на новую строку. Пример: - -```qsp -*p "Текст без перехода на новую строку." -*nl "Переход на новую строку + выведение текста." -*p "Текст без перехода на новую строку." -``` +**Некоторые особенности операций сравнения:** + +- Операции сравнения возвращают `1` (верно) или `0` (неверно) в зависимости от результата сравнения. +- При сравнении чисел всё просто: + - из двух положительных чисел положительное число большее по модулю будет считаться большим; + - отрицательное число всегда меньше не отрицательного (положительное и нуль); + - положительное число всегда больше не положительного (отрицательное и нуль); + - из двух отрицательных чисел отрицательное число большее по модулю будет считаться меньшим. +- При сравнении строк происходит посимвольное сравнение слева направо: + - большим считается символ, который в таблице символов стоит позже. Можно опираться на алфавитную последовательность символов, чтобы понять, какая строка окажется большей. Тогда символ '`z`' будет больше символа '`a`'. Примеры: + + ```qsp + 'z' > 'a' & ! вернёт 1 + 'z' > 'az' & ! вернёт 1 + 'akz' > 'akk' & ! вернёт 1 + ``` + + - при сравнении любой непустой строки с пустой строкой пустая строка будет считаться меньшей: + + ```qsp + ' ' > '' & ! вернёт 1 + 'a' > '' & ! вернёт 1 + 'z' > '' & ! вернёт 1 + 'akzakz' > 'akzak' & ! вернёт 1 + ``` + + :::tip[Можно считать,] + что отсутствующие символы в строке — это пустые символы (пустые строки), которые при сравнении с любым другим символом оказываются меньшим. + ::: + + - при сравнении строки с числом, плеер попытается преобразовать оба значения к числу. Если это удастся, будут сравниваться числа. Если не удастся — число будет преобразовано в строку, и будут сравниваться строки. + + ```qsp + 'zzz' > 123 & ! вернёт 1 + '123' > 92 & ! вернёт 1 + '123' > '92' & ! вернёт 0 + ``` + +- При сравнении кортежей происходит поэлементное сравнение слева направо: + - большим будет считаться тот кортеж, элемент которого оказался большим: + + ```qsp + [1, 2, 3] > [1, 2, 2] & ! вернёт 1 + [2, 2, 3] > [1, 2, 3] & ! вернёт 1 + ``` + + - при сравнении любого непустого кортежа с пустым кортежем, пустой кортеж будет считаться меньшим: + + ```qsp + [1] > [] & ! вернёт 1 + [''] > [] & ! вернёт 1 + [0] > [] & ! вернёт 1 + [1, 2] > [1] & ! вернёт 1 + [1, 2] < [9] & ! вернёт 1 + ``` + + :::tip[Можно считать,] + что отсутствующие элементы в кортеже — это пустые элементы, которые при сравнении с любым другим элементом оказываются меньшим. + ::: + + - при сравнении кортежей с числами или строками, число или строка будут сравниваться, как кортеж из одного элемента. Для упрощения понимания можно считать, что число или строка при сравнении преобразуются в кортеж: + + ```qsp + [8] < 9 & ! вернёт 1 + [9, 8] > 9 & ! вернёт 1 + [0, 0] > 9 & ! вернёт 0 + + [8, 9] > '8,9' & ! вернёт 0 + ['a', 'z'] < 'az' & ! вернёт 1 + ['a', 'z'] > 'a' & ! вернёт 1 + (['az'] = "az") & ! вернёт 1 + ``` + +:::warning[Рекомендуем:] +Не проводить сравнения значений разных типов, чтобы это не приводило к путанице. +::: -## `*P` +## `*` (умножение) -`*P` — вывод текста в окно основного описания без перехода на новую строку. Вывод текста любым другим оператором сразу после `*p` добавит новый текст сразу после текущего. Общая запись: +`*` — арифметическая операция "УМНОЖЕНИЕ". Перемножает два числа. Общая запись: ```qsp -*P [$текст] +[#выражение 1] * [#выражение 2] ``` -, где `[$текст]` — любая строка текста, число, или выражение любого типа. `[$текст]` может быть пустой строкой `''`, но не должен отсутствовать. Пример: - -```qsp -*p "Текст без перехода на новую строку." -*p "Текст без перехода на новую строку." -*p "" -*p "Текст без перехода на новую строку." -``` +, где `[#выражение 1]` и `[#выражение 2]` — два любых числовых значения, или выражения. Результатом работы операции является произведение двух чисел. -## `*PL` - -`*PL` — вывод текста в окно основного описания, затем переход на новую строку. Общая запись: +Примеры: ```qsp -*PL [$текст] +2 * 2 & ! вернёт 4 +4 * 2 & ! вернёт 8 +17 * 5 & ! вернёт 85 +37 * 100 & ! вернёт 3700 ``` -где `[$текст]` — любая строка текста, число, или выражение любого типа. `[$текст]` может отсутствовать, тогда просто переход на новую строку. Пример: +Можно использовать с кортежами, значениями которых являются числа и/или другие кортежи, содержащие числа. Общая запись: ```qsp -*pl "Вывод текста, затем переход на новую строку." -*pl "Вывод текста, затем переход на новую строку." -*p "Текст без перехода на новую строку." -*pl "Вывод текста, затем переход на новую строку." +[%кортеж] * [#число] ``` -Аналогичным образом можно вывести текст, просто написав нужное выражение вместо данного оператора. Например, строки: +В данном случае каждый элемент кортежа будет умножен на указанное число. Примеры: ```qsp -*pl $AAA + '989' -*pl 'Вы находитесь в парке' -*pl 'Преформатированная +%tuple = [4, 10, 16] +%a = %tuple * 2 +! %a будет равно [8, 20, 32] - строка' +[4, 10] * 'b' & ! ошибка о несоответствии типов данных ``` -и: +Обратите внимание на последний пример. Ошибка о несоответствии типов данных возникает из-за того, что невозможно применить операцию умножения к строковому значению. Такая же ошибка возникнет, если кортеж будет содержать строковые значения. Однако перемножать между собой кортежи, содержащие только числовые значения можно: ```qsp -$AAA + '989' -'Вы находитесь в парке' -'Преформатированная - - строка' +*pl [2, 3] * [4, 5] +! [2 * [4,5], 3 * [4,5]] +! [[8,10],[12,15]] ``` -сработают одинаково. - -## ACT - -`ACT` — создаёт и выводит в окно действий новое действие. - -Общая запись в однострочной форме: +В этом случае каждый элемент первого кортежа умножается на второй кортеж. Это и даёт нам в результате новый кортеж из двух кортежей. -```qsp -ACT [$название], [$путь к файлу изображения]: [оператор] & [оператор] & [оператор] -``` +## `*=` (умножение-присвоение) -Общая запись в многострочной форме: +`*=` — операция "УМНОЖЕНИЕ-ПРИСВОЕНИЕ". Сочетает в себе операции присвоения и умножения. Умножает значение указанной переменной на определённое число и возвращает результат той же переменной. Общая запись: ```qsp -ACT [$название], [$путь к файлу изображения]: - [оператор] - [оператор] - [оператор] -END +ИМЯ_МАССИВА *= [#выражение 1] ``` -К списку действий в окне действий добавляется новое с названием `[$название]` и изображением, которое лежит по пути `[$путь к файлу изображения]`. При нажатии на действие выполняются заданные операторы. +, где `ИМЯ_МАССИВА` — это название переменной (без кавычек), или название массива с указанием ячейки, а `[#выражение 1]` — любое числовое значение или выражение. -Параметр `[$путь к файлу изображения]` может отсутствовать, при этом действие добавится без изображения. - -Примеры: +Аналогично конструкции: ```qsp -! действие в однострочной форме записи -act "Сорвать с берёзы яблоко": яблоко += 1 & *pl "Вы сорвали яблоко, спелое белое." - -! действие в многострочной форме записи, с изображением -act "Сорвать арбуз с куста", "img/watermelon.png": - арбуз += 1 - *pl "Вы сорвали арбуз с куста" -end +ИМЯ_МАССИВА = ИМЯ_МАССИВА*[#выражение 1] ``` -Если в списке действий уже есть действие с указанным названием, то новое действие не создаётся, и не заменяет собой уже существующее, плеер просто игнорирует команду `act`. Таким образом нельзя вывести действия с одинаковыми названиями. Пример: +Пример: ```qsp -act "Действие 1": *pl "Старое действие." -act "Действие 1": *pl "Новое действие." +! мы заменяем две операции: присвоения и умножение +warrior = warrior * 2 +! на умножение-присвоение (действие аналогично) +warrior *= 2 ``` -Однако, вы можете сымитировать действия с одинаковыми названиями в режиме распознавания HTML, добавив в названия действий HTML-тег: +Если значением переменной `ИМЯ_МАССИВА` является кортеж, каждый элемент кортежа будет умножен на указанное число, а полученный таким образом кортеж присвоится переменной. Пример: ```qsp -usehtml = 1 -act 'Действие 1': *pl "Старое действие." -act 'Действие 1': *pl "Новое действие." +%tuple = [4, 10, 16] +%tuple *= 2 +! %tuple будет равно [8, 20, 32] ``` -## ADDOBJ - -`ADDOBJ` — добавление нового предмета в окно предметов. Общая запись: +Нельзя умножать на значение строкового типа, это приведёт к ошибке о несоответствии типов данных. Так же и значения кортежа (и всех вложенных кортежей) при выполнении данной операции не должны содержать строковых значений. Однако можно выполнить умножение-присвоение с другим кортежем: ```qsp -ADDOBJ [$название], [$путь к файлу изображения], [#позиция] +%tuple = [2, 3] +%tuple *= [4, 5] +! %tuple будет равно [[8,10],[12,15]] ``` -, где `[$название]` — это название предмета, `[$путь к файлу изображения]` — это путь к файлу изображения предмета (отображается рядом с названием предмета), а `[#позиция]` — на какое место в инвентаре добавляется предмет. Параметр `[#позиция]` может отсутствовать. По умолчанию предметы добавляются в конец списка. Нумерация предметов в инвентаре ведётся с `1`. Параметр `[$путь к файлу изображения]` может отсутствовать, значение по умолчанию - `''`, при этом предмет добавляется без изображения. - -:::note[Допустима, но не рекомендуется, устаревшая форма записи:] +:::warning[Обратите внимание.] +Умножение-присвоение с кортежем вызовет ошибку несоответствия типов данных, если тип переменной не является кортежем: ```qsp -ADD OBJ [$название],[$путь к файлу изображения],[#индекс] +number = 4 +number *= [4,5] & ! ошибка о несоответствии типов данных +! так ошибки не будет, но в переменной окажется пустой кортеж: +%number *= [4,5] ``` ::: -Можно добавлять предметы с одинаковым названием, однако если вы планируете добавлять много одинаковых предметов, то лучше использовать дополнительную переменную для подсчёта этих предметов, а в окно предметов добавить один предмет, чтобы не загромождать инвентарь списком из 137 предметов Рубль / Патрон: +## `+` (сложение) -```qsp -if obj('Патроны'): -! если предмет "Патроны" уже добавлен, просто увеличиваем их число - патроны += 10 -else -! если предмет "Патроны" ещё не добавлен, добавляем, и увеличиваем число - addobj 'Патроны' - патроны += 10 -end -``` - -Для хранения числа предметов можно использовать массивы, индексируемые через строки: +`+` — арифметическая операция "СЛОЖЕНИЕ". Суммирует два числа. Общая запись: ```qsp -objects['деньги'] = 12 -objects['патроны'] = 137 -'Количество: <>' +[выражение 1]+[выражение 2] ``` -Пример добавления предмета в самый верх списка (при этом все остальные предметы сместятся вниз): - -```qsp -addobj "Отвёртка", "", 1 -``` - -## CLA - -`CLA` - очистка списка текущих действий (удаление всех действий из окна действий). - -## CLEAR - -`CLEAR` — очищает окно дополнительного описания. Имеет краткую форму `clr`. - -## CLOSE - -`CLOSE` — останавливает проигрывание указанного звукового файла. Общая запись: - -```qsp -CLOSE [$путь к звуковому файлу] -``` - -, где `[$путь к звуковому файлу]` — путь к звуковому файлу относительно файла игры. Если параметр `[$путь к звуковому файлу]` не указан, происходит остановка воспроизведения всех звуковых файлов. - -## CLOSE ALL - -`CLOSE ALL` — остановка проигрывания всех активных звуковых файлов. Имеет краткую форму `close`. - -## CLS - -`CLS` — очищает все окна кроме списка предметов. Эквивалентно конструкции: - -```qsp -clear & *clear & cla & cmdclear -``` - -## CMDCLEAR - -`CMDCLEAR` — очистка строки ввода. Имеет краткую форму `cmdclr`. - -## COPYARR - -`COPYARR` — копирование содержимого одного массива в другой. Общая запись: - -```qsp -COPYARR [$приёмник], [$источник], [#начало], [#количество] -``` - -, где: `[$приёмник]` — это массив, в который производится копирование, размер и наполнение значения не имеют; `[$источник]` — это массив, из которого производится копирование; `[#начало]` — номер элемента, с которого нужно начинать копирование; `[#количество]` — сколько элементов нужно скопировать. Параметр `[#количество]` является необязательным; по умолчанию — до конца массива-источника. Параметр `[#начало]` является необязательным; по умолчанию — 0. +, где `[выражение 1]` и `[выражение 2]` — два любых значения, или выражения. Результатом работы операции является сумма двух значений. Примеры: ```qsp -! копируем все элементы массива '$b' в массив '$a' -copyarr '$a', '$b' -! при этом так же были скопированны все элементы массива 'b' в массив 'a' - -! копируем в массив 'c' элементы массива 'd', начиная с шестого -copyarr 'c', 'd', 6 - -! копируем шесть первых элементов массива 'd' в массив 'c' -copyarr 'c', 'd', 0, 6 +2+2 & ! вернёт 4 +4+2 & ! вернёт 6 +17+5 & ! вернёт 22 +37+100 & ! вернёт 137 ``` -В силу особенностей плеера при копировании, например, числового массива `mass1` в `mass2` копируется также текстовый массив `$mass1` в `$mass2`. - -Другие примеры: +При "суммировании" строковых значений производится [конкатенация](qsp-keyword-operators.md#-конкатенация), то есть "склеивание" строк: ```qsp -copyarr $arrname1, $arrname2, 10, 5 -copyarr 'a<<$arrname1>>', 'a<<$arrname2>>' +! на экран будет выведена строка "2627" +"26"+"27" ``` -## DELACT - -`DELACT` — удаляет действие из списка действий (если такое действие существует). Общая запись: +Если значения "прибавляются" к кортежу, происходит суммирование каждого элемента кортежа с указанным значением: ```qsp -DELACT [$название] +%tuple = [4, 10, 16] +%a = %tuple + 2 +! %a будет равно [6, 12, 18] ``` -, где `[$название]` — название действия, которое хотим удалить. - -Примеры: +Если складываются два кортежа, к значениям каждого элемента первого кортежа прибавляется второй кортеж: ```qsp -! удаляем действие с конкретным названием -delact 'Идти вперед' -! удаляем выделенное действие -delact $selact +[4, 10] + ['b', 'x'] +! [4 + ['b', 'x'], 10 + ['b', 'x']] +! [['4b','4x'], ['10b','10x']] ``` -:::note[Допустима, но не рекомендуется, устаревшая форма записи:] - -```qsp -DEL ACT [$название] -``` - -::: - -## DELOBJ +## `+=` (сложение-присвоение) -`DELOBJ` — удаление предмета из инвентаря по названию (если такой предмет существует). Общая запись: +`+=`, `(инкремент)` — операция "ИНКРЕМЕНТ", сочетающая в себе операции присвоения и сложения. Прибавляет к текущему значению переменной указанное значение. Общая запись: ```qsp -DELOBJ [$название] +ИМЯ_МАССИВА += [выражение 1] ``` -, где `[$название]` — название предмета, который хотим удалить. +, где `ИМЯ_МАССИВА` — это название переменной (без кавычек), или название массива с указанием ячейки, а `[выражение 1]` — любое значение или выражение. -Если в инвентаре присутствуют одинаковые предметы, команда удалит самый верхний с указанным индексом. - -Примеры: +Аналогично конструкции: ```qsp -! удаляем предмет с конкретным названием -delobj "Отвёртка" -! удаляем выделенный предмет -delobj $selobj +ИМЯ_МАССИВА = ИМЯ_МАССИВА + [выражение 1] ``` -:::note[Допустима, но не рекомендуется, устаревшая форма записи:] +Пример: ```qsp -DEL OBJ [$название] +! мы заменяем две операции: присвоения и сложения +warrior = warrior + 15 +! на инкремент (действие аналогично) +warrior += 15 ``` -::: - -## DYNAMIC - -`DYNAMIC` — выполняет код, переданный в виде строки текста. Общая запись: +Возможно так же проводить инкремент со строковыми значениями, работает как [конкатенация](qsp-keyword-operators.md#-конкатенация): ```qsp - DYNAMIC([$код], [аргумент 0], [аргумент 1], ... , [аргумент 18]) +$text += " (может быть тут что-то написано)" ``` -, где `[$код]` — это обычный код QSP, записанный в виде текста. Выполнение такого кода аналогично выполнению кода оператора `GOSUB`. Аргументы `[аргумент 0]`, `[аргумент 1]` и т.д. могут использоваться внутри `[$код]`, их значения автоматически помещаются в переменные `args[0]`, `args[1]`, и т.д. соответственно. После выполнения старые параметры `args` восстанавливаются, затем продолжается выполнение кода со следующей команды после `dynamic`. - -Примеры: +Если значением переменной `ИМЯ_МАССИВА` является кортеж, каждый элемент кортежа будет суммирован с указанным значением, а полученный таким образом кортеж присвоится переменной. Пример: ```qsp -dynamic '$a = "string<<$b>>"' -dynamic '$a' -dynamic 'if $a = "string": "text!"' -dynamic " - $args[0] - addobj $args[1] -", 'Текст', 'Вилка' +%tuple = [4, 10, 16] +%tuple += 2 +! %tuple будет равно [6, 12, 18] ``` -Нижеследующая информация справедлива и для функции [`dyneval`](qsp-keyword-functions.md#dyneval). - -**Важно!** Если код задан с помощью апострофов (`''`) или кавычек (`""`), в тексте вычисляются подвыражения: +Можно выполнить сложение-присвоение с другим кортежем: ```qsp -$args[0] = 'qwerty' -$code = ' - *pl "<<$args[0]>>" - *pl $args[0] -' - -dynamic $code, 'asdfg' +%tuple = [2, 3] +%tuple += [4, 5] +! %tuple будет равно [[6,7],[7,8]] ``` -В этом случае при задании переменной `$code` будет вычислено подвыражение, поэтому первой строкой выведется 'qwerty', второй строкой выведется 'asdfg'. - -Фигурные скобки - третий вид кавычек используемый специально для написания динамического кода. Здесь поддерживается вложенность скобок, а перед выполнением кода не вычисляются подвыражения: +:::warning Обратите внимание. +Сложение-присвоение с кортежем вызовет ошибку несоответствия типов данных, если тип переменной не является кортежем: ```qsp -$args[0]='qwerty' -$code = { - *pl "<<$args[0]>>" - *pl $args[0] -} - -dynamic $code, 'asdfg' +number = 4 +number += [4,5] & ! ошибка о несоответствии типов данных +! так ошибки не будет, но в переменной окажется пустой кортеж: +%number += [4,5] ``` -В этом случае будут выведены две строки 'asdfg'. - -## EXIT - -`EXIT` — завершение выполнения текущего блока кода (преждевременный выход из подпрограммы, функции, обработчика какого-либо события, и т.д.). - -В качестве блока кода может выступать локация, действие, код, переданный `dynamic`'у или `dyneval`'у, или код в гиперссылке. - -Пример: - -```qsp -if args[1] = 0: - exit -else - if args[0] mod args[1] = 0: - result = 1 - else - result = 0 - end -end -``` - -:::warning[Внимание!!!] -В плеерах версии 5.8.0 появился оператор цикла `loop`. - -Тело цикла так же считается отдельным блоком кода, однако оператор `exit` прерывает не только сам цикл, но и блок кода, в котором находится цикл. ::: -## FREELIB - -`FREELIB` — удаляет все локации, добавленные с помощью оператора `inclib`. - -:::note[5.7.0] -В старых версиях плеера команда называлась `dellib` и `killqst`. +:::tip[Примечание] +Инкремент — во многих языках программирования это операция, которая выполняет увеличение переменной. Чаще всего под инкрементом подразумевается увеличение переменной на `1`. ::: -## GOSUB +## `-` (вычитание) -`GOSUB` — выполнение кода указанной локации без непосредственного перехода на неё. - -Общая запись: +`-` — арифметическая операция "ВЫЧИТАНИЕ". Вычитает одно число из другого. Общая запись: ```qsp -GOSUB [$локация],[аргумент 0],[аргумент 1], ... ,[аргумент 8] +[#выражение 1] - [#выражение 2] ``` -, где `[$локация]` — это название локации, код которой мы хотим выполнить без непосредственного перехода на неё. Аргументы `[аргумент 0]`, `[аргумент 1]` и т.д. могут использоваться на этой локации, их значения автоматически помещаются в переменные `args[0]`, `args[1]`, и т.д. соответственно. После обработки локации предыдущие значения `args` восстанавливаются. Использование аргументов не обязательно. - -При обращении к локации по `gosub` базовое описание локации добавляется к текущему описанию, базовые действия добавляются к текущим действиям, и происходит выполнение операторов в поле "Выполнить при посещении", затем возврат на исходную строку (продолжение выполнения кода после `gosub`). - -Примеры вызова локаций по `gosub`: - -```qsp -!обработка локации "ход". Массив args[] пуст. -gosub 'ход' - -!обработка локации с названием из переменной $location -!Передаётся один параметр - args[0] равен 1. -gosub $location,1 - -!обработка локации "ход" с передачей 3-х параметров. -! $args[0] = $var (значению), args[1] = 2, -! $args[2] = "данные". Обратите внимание на символы '$'. -gosub 'ход',$var,2,'данные' -``` - -Ещё пример: - -```qsp -! это код вызова локации "переход" -gosub 'переход', 'локация' - -! а это код самой локации "переход" -# переход -*pl $args[0] & ! на экран выведется текст 'локация' -! в окне действий появится новое действие: -act 'перейти': - goto "улица" -end -- переход -``` +, где `[#выражение 1]` и `[#выражение 2]` — два числовых значения, или выражения. Результатом работы операции является разность двух значений. -Оператор имеет краткую форму `gs`: +Примеры: ```qsp -GS [$локация], [аргумент 0], [аргумент 1], ... , [аргумент 18] +2 - 2 & ! вернёт 0 +4 - 2 & ! вернёт 2 +17 - 5 & ! вернёт 12 +37 - 100 & ! вернёт -63 ``` -## GOTO - -`GOTO` — переход на указанную локацию. Общая запись: +Можно использовать с кортежами, значениями которых являются числа и/или другие кортежи, содержащие числа. Общая запись: ```qsp -GOTO [$локация], [аргумент 0], [аргумент 1], ... , [аргумент 18] +[%кортеж] - [#число] ``` -, где `[$локация]` — название локации, на которую должен быть осуществлён переход. Аргументы `[аргумент 0]`, `[аргумент 1]` и т.д. могут использоваться на этой локации, их значения автоматически помещаются в переменные `args[0]`, `args[1]`, и т.д. соответственно. Использование аргументов не обязательно. - -При переходе на новую локацию при помощи `goto` очищается окно основного описания, а также список текущих действий, затем в окно основного описания выводится текст базового описания, в окно действий — базовые действия, а так же выполняется код из поля "Выполнить при посещении" локации `[$локация]`. Так же при переходе на новую локацию изменяется значение, возвращаемое функцией `$curloc`. - -Примеры: +В данном случае из каждого элемента кортежа будет вычтено указанное число. Примеры: ```qsp -! переход на локацию "дом". -! Массив args на локации "дом" будет пуст. -goto 'дом' +%tuple = [4, 10, 16] +%a = %tuple - 2 +! %a будет равно [2, 8, 14] -! переход на локацию "улица" с передачей 2-х параметров. -! на локации "улица" args[0] равен 1, -! $args[1] содержит строку "данные". -goto 'улица',1,'данные' +[4, 10] - 'b' & ! ошибка о несоответствии типов данных ``` -Оператор имеет краткую форму `gt`: +Обратите внимание на последний пример. Ошибка о несоответствии типов данных возникает из-за того, что невозможно применить операцию вычитания к строковому значению. Такая же ошибка возникнет, если кортеж будет содержать строковые значения. Однако из одного кортежа другой кортеж можно, если оба кортежа содержат только числовые значения: ```qsp -GT [$локация],[аргумент 0],[аргумент 1], ... ,[аргумент 8] +*pl [2, 3] - [4, 5] +! [2 - [4,5], 3 - [4,5]] +! [2 + ([4,5] * -1), 3 + ([4,5] * -1)] +! [[-4, -5] + 2, [-4,-5] + 3] +! [[-2,-3],[-1,-2]] ``` -## IF +В этом случае из каждого элемента первого кортежа вычитается второй кортеж. Если последовательно раскрыть скобки и произвести все необходимые математические операции, получится новый кортеж, содержащий другие кортежи с результатами. -`IF` — основной оператор для записи конструкций условий. Конструкции, записываемые с помощью этого оператора (назовём их "простыми условиями"), имеют две формы: однострочную и многострочную, — и в общем виде выглядят так: +## `-=` (вычитание-присвоение) -Общая форма записи: +**`-=`, `(декремент)`** — операция "ДЕКРЕМЕНТ", сочетающая в себе операции присвоения и вычитания. Вычитает из текущего значения переменной указанное значение. Общая запись: ```qsp -! однострочная форма записи -IF [#выражение]: {команда 1} & {команда 2} & ... - -! многострочная форма записи -IF [#выражение]: - {команда 1} - {команда 2} - ... -END +ИМЯ_МАССИВА -= [#выражение 1] ``` -В данном случае, если верно условие `[#выражение]`, выполняются команды `{команда 1}`, `{команда 2}` и т.д. +, где `ИМЯ_МАССИВА` — это название переменной (без кавычек), или название массива с указанием ячейки, а `[#выражение 1]` — любое числовое значение или выражение. -- Для **однострочной формы** записи это будут только те команды, которые идут в той же строке, что и оператор `IF` до конца строки; -- а для **многострочной формы** записи это будут те команды, которые идут в последующих строках после двоеточия и до специального ключевого слова `END`. - -В качестве условия могут выступать операции сравнения, логические операции и иные выражения, возвращающие числовые значения. - -Ключевое слово `END` при многострочной форме записи должно стоять отдельной строкой. - -Если условие `[#выражение]` не верно, команды выполнены не будут. - -Примеры однострочной формы записи условий: +Аналогично конструкции: ```qsp -! если сумма a и b равна двум, -! переменной c присваивается значение 30 -if a + b = 2: c = 30 -! Если в инвентаре нет апельсина, выводится текст -if no obj("Апельсин"): pl "У Вас нет апельсина." -! это тоже простая однострочная форма -if ((a+b)/c)=45+54 or (b<5 or c>45) and no obj 'лопата' and $f=$vvv+'RRRRR': p 'OK' & goto 'Next' +ИМЯ_МАССИВА = ИМЯ_МАССИВА - [#выражение 1] ``` -Примеры многострочной формы записи условий: +Пример: ```qsp -if библиотека = 0: - узнал_о_тусовке = 0 - библиотека_вернулся = 1 - gt 'библиотека' -end -if a+b=2: - c=30 -end +! мы заменяем две операции: присвоения и вычитания +warrior = warrior - 15 +! на декремент (действие аналогично) +warrior -= 15 ``` -:::warning[Обратите внимание!!!] - -При многострочной форме записи после двоеточия в той же строке, в какой находится оператор IF, не должны идти никакие команды, иначе плеер посчитает такой оператор условия однострочным, и команды в последующих строках будут выполняться в любом случае, независимо от того, верным окажется условие или нет. Пример такой ошибочной записи: +Если значением переменной `ИМЯ_МАССИВА` является кортеж, из каждого элемента кортежа будет вычитаться указанное число, а полученный таким образом кортеж присвоится переменной. Пример: ```qsp -if библиотека = 0: узнал_о_тусовке = 0 - библиотека_вернулся = 1 &! эта строчка будет выполняться в независимости от верности условия - gt 'библиотека' &! и эта -end &! ключевое слово end - просто игнорируется +%tuple = [4, 10, 16] +%tuple -= 2 +! %tuple будет равно [2, 8, 14] ``` -Исключением является оператор комментария записанный после двоеточия: +Нельзя вычитать значение строкового типа, это приведёт к ошибке о несоответствии типов данных. Так же и значения кортежа (и всех вложенных кортежей) при выполнении данной операции не должны содержать строковых значений. Однако можно выполнить вычитание-присвоение с другим кортежем: ```qsp -if библиотека = 0: ! если не посещал библиотеку - узнал_о_тусовке = 0 - библиотека_вернулся = 1 - gt 'библиотека' -end +%tuple = [2, 3] +%tuple -= [4, 5] +! %tuple будет равно [[-2,-3],[-1,-2]] ``` -Но в случае, если комментарий отделён амперсандом, условие будет считаться однострочным: +:::warning[Обратите внимание.] +Вычитание-присвоение с кортежем вызовет ошибку несоответствия типов данных, если тип переменной не является кортежем: ```qsp -if библиотека = 0: & ! такой комментарий делает условие однострочным! - узнал_о_тусовке = 0 & ! эта строчка будет выполняться в независимости от верности условия - библиотека_вернулся = 1 & ! и эта - gt 'библиотека' &! и эта тоже -end &! ключевое слово end - просто игнорируется +number = 4 +number -= [4,5] & ! ошибка о несоответствии типов данных +! так ошибки не будет, но в переменной окажется пустой кортеж: +%number -= [4,5] ``` ::: -Для многострочных форм записи допускается вложенность неограниченной глубины. Каждый уровень вложения должен заканчиваться своей строкой `end`. +:::tip[Примечание] +Декремент — во многих языках программирования это операция, которая выполняет уменьшение переменной. Чаще всего под декрементом подразумевается уменьшение переменной на `1`. +::: -Примеры: +## `-` (унарный минус) -```qsp -if a+b<3 or y=8: - p 'A+B<3 или Y=8' - nl - if j=88: nl & p 'NEXT' - if $h='ooo': - p 'loo' & jump 'lll' - end -end -``` +**унарный `-`** — унарная операции. Общая запись: ```qsp -if a=0: - 'abc1234' - if b=0: '0' else '1' - if j=88: nl & p 'NEXT' - if $h='ooo': - p 'loo' & jump 'lll' - else - p 'sample text' - v=8 - end - 1234 -else - '01234' - g=78 -end +-[#выражение] ``` -Несколько примеров неверной записи: +, где `[#выражение]` — любое числовое значение или выражение. Результатом работы этой операций является то же самое значение, только с противоположным знаком. -```qsp {4} -! в этом случае, если условие не будет выполнено, -! плеер проигнорирует только команду `k1=34` -! поскольку посчитает, что это однострочное условие -if abcd=3: k1=34 - k2=35 & ! эта команда будет выполняться всегда - k3=36 & ! эта комнада будет выполняться всегда -end & ! этот end будет проигнорирован -``` - -```qsp {3,9} -! данная строка выведет ошибку неизвестное действие -! так как однострочные формы записи не должны оканчиваться end`ом -if abcd=3: k1=34 else k1=25 end -``` - -## ELSE - -`ELSE` — ключевое слово, использующееся совместно с оператором `IF`, и которое служит для предоставления альтернативы, если условие не выполнено. Ключевое слово `ELSE` так же имеет две формы записи: однострочную и многострочную. - -- Многострочную форму записи `ELSE` можно использовать только в многострочной конструкции оператора `IF`, -- однострочную форму записи можно использовать как в однострочной, так и в многострочной, конструкции оператора `IF`. Общая форма записи: +Примеры: ```qsp -! однострочная форма записи -IF [#выражение]: {команда д1} & {команда д2} & ... ELSE {команда н1} & {команда н2} & ... - -! в многострочном IF: - -! многострочная форма ELSE -IF [#выражение]: - {команда д1} - {команда д2} - ... -ELSE - {команда н1} - {команда н2} - ... -END - -! однострочная форма ELSE -IF [#выражение]: - {команда д1} - {команда д2} - ... -ELSE {команда н1} & {команда н2} & ... - ! команды в следующих строках - ! до END игнорируются -END +-2 & ! вернёт -2 +-(3+6) & ! вернёт -9 +-(-27) & ! вернёт 27 ``` -Здесь, если условие`[#выражение]` верно, выполняются команды от двоеточия до ключевого слова `ELSE`, а если условие `[#выражение]` не верно, выполняются команды от ключевого слова `ELSE` и до конца конструкции условия. - -После `ELSE` можно ставить, а можно не ставить двоеточие. - -**При однострочной форме записи:** - -- и команды и ключевое слово `ELSE` должны быть записаны в одной строке -- окончанием альтернативного списка команд является конец строки. -- если однострочная форма записи `ELSE` используется в многострочной форме записи `IF`, все команды, которые идут в последующих строках после `ELSE` до `END` игнорируются. - -Примеры однострочной записи: +Унарный минус можно использовать перед кортежем, содержащим только числовые значения. Это выражение вернёт новый кортеж, в котором знак каждого элемента будет изменён на противоположный: ```qsp -! если сумма a и b равна двум, переменной c присваивается значение 30 -! в противном случае (то есть если сумма a и b не равна двум) -! переменной c присваивается значение 10 -if a+b=2: c=30 else c=10 - -! в зависимости от того есть ли в инвентаре апельсин -! выводится соответствующий текст -if obj("Апельсин"): pl "У Вас есть апельсин." else pl "У Вас нет апельсина." - -! однострочная форма else внутри многострочной if -if $левая_рука = 'Великий меч': - gosub 'atack', 300 - gosub 'health.prove' - gosub 'win.prove' -else gosub 'atack', atack_power -end +- [2, 3, -1, -17, 5] +! [-2, -3, 1, 17, -5] ``` -**При многострочной форме записи:** - -- все команды должны идти в последующих строках после `ELSE`; +:::note[5.7.0] -Примеры многострочной записи: +В более ранних версиях плеера существовала операция "унарный плюс": ```qsp -if a+b=2: - c=30 -else - c=10 -end - -if obj("Апельсин"): - pl "У Вас есть апельсин." -else - pl "У Вас нет апельсина." -end - -if len($curtoken) > 0: - $tokens[curtoken_num] = $curtoken tokens_count = curtoken_num + 1 -else - tokens_count = curtoken_num -end ++(6+7) ``` -## ELSEIF - -`ELSEIF` — ключевое слово, которое используется совместно с оператором `IF` и позволяет определять на одном уровне вложенности последовательно-исключающие условия. Имеет однострочную и многострочную формы записи. +По сути, она ничего не делала, поэтому было решено от неё отказаться. +::: -- Многострочную форму записи можно использовать только в многострочных конструкциях с оператором `IF`, -- однострочную — как в многострочных, так и в однострочных конструкциях с оператором `IF`. +## `/` (деление) -Общие формы записи: +`/` — арифметическая операция "ДЕЛЕНИЕ". Общая запись: ```qsp -! однострочная в однострочном условии -IF [#выражение 1]: {набор команд 1} ELSEIF [#выражение 2]: {набор команд 2} ELSE {последний набор команд} - -! многострочная в многострочном условии -IF [#выражение 1]: - {набор команд 1} - ... -ELSEIF [#выражение 2]: - {набор команд 2} - ... -ELSEIF ... : - ... -ELSE - {последний набор команд} - ... -END - -! однострочная в многострочном условии -IF [#выражение 1]: - {набор команд 1} - ... -ELSEIF [#выражение 2]: {набор команд 2} -ELSEIF ... : ... -ELSE {последний набор команд} -END +[#выражение 1] / [#выражение 2] ``` -Работает это следующим образом. Если `[#выражение 1]` верно, выполняются команды `{набор команд 1}`. Если `[#выражение 1]` неверно, но верно `[#выражение 2]`, выполняются команды `{набор команд 2}`, и т.д. И только если неверны все выражения в текущей конструкции условия, выполнятся команды после `ELSE`. Верность выражения `[#выражение 1]` не исключает верности выражения `[#выражение 2]`, однако верность выражения `[#выражение 2]` исключает верность выражения `[#выражение 1]`. - -Особенности записи `ELSEIF`: +, где `[#выражение 1]` и `[#выражение 2]` — два любых числовых значения, или выражения. Значение `[#выражение 2]` не должно быть равным нулю. Результатом работы операции является частное от деления двух чисел. -- Может использоваться вариант написания `ELSE IF`. Работает точно так же. -- Если в многострочной конструкции `IF` после `ELSEIF` операторы идут в той же самой строке (однострочная форма), то все последующие строки игнорируются до следующего `ELSEIF`, либо до `ELSE` или `END`. -- В конструкции `IF` c `ELSEIF` может как присутствовать, так и отсутствовать часть с `ELSE`. +Поскольку QSP поддерживает только целочисленные значения, деление производится так же нацело, без округления, с отсечением дробной части. Примеры: ```qsp -if obj('Зелье здоровья'): health += 100 esleif obj('Яблоко'): health += 15 else *pl 'Нечем пополнить силы!' - -IF ОЧКИ>124: - GOTO 'КОН3' -ELSEIF ОЧКИ>99: - GOTO 'КОН4' -ELSE - GOTO 'КОН5' -END - -if money mod 10=1 and money mod 100<>11: - *pl "У вас <> монета." -elseif money mod 10>1 and money mod 10<5 and (money mod 100<5 or money mod 100>20): - *pl "У вас <> монеты." -elseif money mod 10=0 or money mod 10>4 or (money mod 100>10 and money mod 100<21): - *pl "У вас <> монет." -end +2 / 2 & ! вернёт 1 +4 / 2 & ! вернёт 2 +17 / 5 & ! вернёт 3 +37 / 100 & ! вернёт 0 ``` -Пример записи `ELSEIF` с операторами в той же строке: +Можно использовать с кортежами, значениями которых являются числа и/или другие кортежи, содержащие числа. Общая запись: ```qsp -! реализация switch/case на QSP -if r = 0: - 'Вариант 0' - elseif r = 1: 'Вариант 1' - elseif r = 2: 'Вариант 2' - elseif r = 3: 'Вариант 3' - else: 'Без вариантов' -end +[%кортеж] / [#число] ``` -:::tip[На заметку:] - -Для улучшения читаемости кода рекомендуется использовать конструкции с `elseif` только в многострочной форме оператора `if`. - -::: - -## INCLIB - -`INCLIB` — из заданного файла игры добавляет все локации, названия которых отсутствуют среди текущих игровых локаций. Загруженные локации полностью эквивалентны локациям из основного файла игры. Общая запись: +В данном случае каждый элемент кортежа будет разделён на указанное число. Примеры: ```qsp -INCLIB [$путь к файлу игры] +%tuple = [4, 10, 16] +%a = %tuple / 2 +! %a будет равно [2, 5, 8] + +[4, 10] / 'b' & ! ошибка о несоответствии типов данных ``` -Пример: +Обратите внимание на последний пример. Ошибка о несоответствии типов данных возникает из-за того, что невозможно применить операцию деления к строковому значению. Такая же ошибка возникнет, если кортеж будет содержать строковые значения. Однако делить друг на друга кортежи, содержащие только числа можно: ```qsp -inclib "lib/easy.math.qsp" -inclib "lib/easy.title.qsp" -inclib "res/drive.qsp" -inclib "res/base.qsp" -inclib "res/intro.qsp" +*pl [30, 60] / [2, 6] +! [30 / [2,6], 60 / [2,6]] +! [[15,5],[30,10]] ``` -:::note[5.7.0] -В более старых версиях плееров команда называлась `addqst` и `addlib`. -::: +В этом случае каждый элемент первого кортежа "делится" на второй кортеж. Это даёт нам в результате новый кортеж из двух кортежей. -## JUMP +## `/=` (деление-присвоение) -`JUMP` — переход в текущем блоке кода на указанную метку. Общая запись: +`/=` — операция "ДЕЛЕНИЕ-ПРИСВОЕНИЕ". Сочетает в себе операции присвоения и деления. Делит значение указанной переменной на определённое число и возвращает результат той же переменной. Общая запись: ```qsp -JUMP [$метка] +ИМЯ_МАССИВА /= [#выражение 1] ``` -, где `[$метка]` — это метка ниже или выше по коду (см. раздел ["Метки"](qsp-keyword-syntaxems.md#метки-)). +, где `ИМЯ_МАССИВА` — это название переменной (без кавычек), или название массива с указанием ячейки, а `[#выражение 1]` — любое числовое значение или выражение. -`jump` находит метку только в пределах текущего блока кода, то есть метки локальны. - -Отдельными блоками кода в QSP являются: - -- код "Выполнить при посещении" конкретной локации (каждая локация - отдельный блок кода), -- код действия даже если действие добавлено программно, -- код в гиперссылке, -- код `DYNAMIC`/`DYNEVAL` - -Пример: +Аналогично конструкции: ```qsp -jump 'КонеЦ' -p 'Это сообщение не будет выведено' -:конец -p 'А это сообщение пользователь увидит' +ИМЯ_МАССИВА = ИМЯ_МАССИВА / [#выражение 1] ``` -:::note[5.7.0] -С помощью оператора `jump` в старых версиях плеера можно было организовывать циклы: +Пример: ```qsp -:loop -if s<9: - s=s+1 - pl s - jump 'loop' -end -p 'Всё!' +! мы заменяем две операции: присвоения и деления +warrior = warrior / 2 +! на деление-присвоение (действие аналогично) +warrior /= 2 ``` -Двойной цикл с одной меткой: +Если значением переменной `ИМЯ_МАССИВА` является кортеж, каждый элемент кортежа будет разделён на указанное число, а полученный таким образом кортеж присвоится переменной. Пример: ```qsp -:loop -if y<9: - if x<9: - *p "<> - " - x=x+1 - jump 'loop' - end - *pl ":<>" - y=y+1 - x=0 - jump 'loop' -end +%tuple = [4, 10, 16] +%tuple /= 2 +! %tuple будет равно [2, 5, 8] ``` -Начиная с версии 5.8.0 для циклов введён собственный оператор `loop`. -::: - -## KILLALL - -`KILLALL` — уничтожает все переменные и удаляет все предметы из окна предметов. Эквивалентен конструкции: +Нельзя делить на значение строкового типа, это приведёт к ошибке о несоответствии типов данных. Так же и значения кортежа (и всех вложенных кортежей) при выполнении данной операции не должны содержать строковых значений. Однако можно выполнить деление-присвоение с другим кортежем: ```qsp -killvar & killobj +%tuple = [10, 30] +%tuple /= [5, 2] +! %tuple будет равно [[2,5],[6,15]] ``` -:::warning[Внимание!] -Следует помнить, что `killall` не эквивалентен конструкции: +:::warning[Обратите внимание.] +Деление-присвоение с кортежем вызовет ошибку несоответствия типов данных, если тип переменной не является кортежем: ```qsp -killobj & killvar +number = 4 +number /= [4,5] & ! ошибка о несоответствии типов данных +! так ошибки не будет, но в переменной окажется пустой кортеж: +%number /= [4,5] ``` -поскольку в этом случае значения переменных удаляются после удаления предметов, а значит код локации-обработчика удаления предметов успевает выполниться (см. `$onobjdel`). ::: -Обычно `killall` используют в начале игры, если в конце игры предусмотрено действие "Начать заново". - -## KILLOBJ +## `<` (меньше) -`KILLOBJ` — удаление предмета, расположенного в заданной позиции. Общая запись: +`<` — операция сравнения "МЕНЬШЕ". Общая запись: ```qsp -KILLOBJ [#номер] +[выражение_1] < [выражение_2] ``` -, где `[#номер]` — номер предмета в окне инвентаря. Нумерация предметов начинается с 1. Если параметр `[#номер]` не указан, удаляются все предметы. При удалении каждого предмета с помощью `killobj`, происходит выполнение кода локации-обработчика удаления предметов (см. `$onobjdel`). - -Пример: - -```qsp -! удаляем самый верхний предмет в списке -killobj 1 -! удаляем самый нижний предмет в списке -killobj countobj -! удаляем все предметы -killobj -``` - -## KILLVAR - -`KILLVAR` — удаление указанного элемента массива. Общая запись: - -```qsp -KILLVAR [$название массива], [индекс элемента] -``` - -, где `[$название массива]` — название массива, из которого хотим удалить элемент, а `[индекс элемента]` — номер, текстовый индекс, или многомерный индекс элемента в массиве, который хотим удалить. Нумерация элементов массивов начинается с 0. - -Если индекс элемента не указан, то очищается весь массив. Если оператор вызван без аргументов, то удаляются все переменные и массивы. +Если значение выражения `[выражение_1]` меньше значения выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт `0`. Иными словами: верно, если первое меньше второго. Примеры: ```qsp -killvar 'a', 3 & ! удалит из массива 'a' элемент с индексом 3. -killvar 'unit', 'Десантник' & ! удаляет из массива элемент с индексом 'Десантник' -killvar 'a' & ! удаляет массив 'a' -killvar & ! удаляет все переменные, массивы -killvar '$map_cell', (3, 4) & ! удаление по многомерному индексу +! 2 меньше 4 — вернёт 1 +2 < 4 +! 5 не меньше 5 — вернёт 0 +5 < 5 +! 7 не меньше 3 — вернёт 0 +7 < 3 ``` -При удалении элемента все следующие за ним элементы сдвигаются на позицию вверх. - -Пример: - -```qsp -a[0] = 4 -a[1] = 3 -a[2] = 23 -a[3] = 15 -KILLVAR 'a', 1 -! теперь массив выглядит так: -! a[0] = 4 -! a[1] = 23 -! a[2] = 15 -``` - -## LET - -`LET` — устаревший оператор для установки значений переменных. Общая запись: - -```qsp -LET [название переменной] = [выражение] -LET [переменная 1], [переменная 2], ... = [значение 1], [значение 2], ... -``` - -, где `[название переменной]` — это допустимое имя переменной, `[выражение]` — это допустимое для данной переменной значение. - -- Названия числовых переменных записываются без символов `$` и `%` в начале. -- Названия текстовых переменных записываются с символом `$` в начале. -- Названия переменных, содержащих кортежи, записываются с символом `%` в начале. - -Примеры: +Сравнивать можно текстовые значения: ```qsp -! задаём текстовую переменную -let $text = "text string" -! задаём числовую переменную -let abs = 123 -! задаём кортеж -let %tuple = [123, "text string"] -! множественное присваивание -let unit_power, $unit_name = 1300, 'DiggerBull' -! распаковка кортежа -let $name, age, height = %npc_fields +"a" < "z" & ! верно +"z" < "zz" & ! верно +"aaaaaa" < "z" & ! верно ``` -:::tip -Данный оператор считается устаревшим. Используйте вместо него оператор `set`, и только в тех случаях, когда это улучшит читаемость кода. +И можно сравнивать кортежи: ```qsp -! присвоение можно проводить без операторов `set` или `let`: -$text = "text string" +[1, 2, 3] < [1, 2, 9] & ! верно +[1, 2, 3] < [2, 2, 3] & ! верно +[1, 2] < [1, 2, 3] & ! верно ``` -::: - -## LOCAL - -`LOCAL` — объявляет локальную переменную (или несколько переменных) в текущем блоке кода. +## `<=` (меньше либо равно) -Общая запись: +`<=` — операция сравнения "МЕНЬШЕ ЛИБО РАВНО". Общая запись: ```qsp -LOCAL [переменная 1], [переменная 2], ... -LOCAL [переменная 1], [переменная 2], ... = [значение 1], [значение 2], ... +[выражение_1] <= [выражение_2] ``` -, где `[переменная 1]`, `[переменная 2]` и т.д. — это имена переменных/массивов, записанные прямо (не в кавычках), а `[значение 1]`, `[значние 2]` и т.д. — любые значения, константы, значения выражений, функций или других переменных. +Если значение выражения `[выражение_1]` меньше либо равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт `0`. Иными словами: верно, если первое меньше второго, либо равно ему. -Число переменных и значений должно совпадать (кроме случаев распаковки). +Примеры: ```qsp -! объявляем одну локальную переменную -local tempora = 12 -! объявляем несколько локальных переменных -local x, y, $item = 11, 19, "Старый меч" -! объявляение с распаковкой -local i, j = %map_cell -local z, $a = [13, '37'] +! 2 меньше 4 — вернёт 1 +2 <= 4 +! 5 равно 5 — вернёт 1 +5 <= 5 +! 7 не меньше трёх и не равно ему +7 <= 3 & ! вернёт 0 ``` -В отличие от операторов `set` и `let` переменную можно объявить, но значение ей не присваивать. +Аналогично "`=<`" и конструкциям: ```qsp -local tempora -local x, y, $item, %map_cell -``` - -При этом, несмотря на то, что переменная создаётся, `arrsize` для неё будет возвращать `0`. Т.е. проверить, объявлена ли переменная нельзя. +([выражение_1] < [выражение_2]) or ([выражение_1] = [выражение_2]) -```qsp -local arr -*pl arrsize('arr') & ! выведет 0 +no [выражение_1] > [выражение_2] ``` -Собственные локальные переменные можно создавать в следующих блоках кода: - -- Локации сами по себе. -- Код, передаваемый оператору `DYNAMIC`, или функции `DYNEVAL`, в виде текста. -- Код, выполняемый при нажатии на гиперссылку. -- Код каждого отдельного Действия ([ACT](qsp-keyword-operators.md#act)). -- Код каждого отдельного Цикла ([LOOP](qsp-keyword-operators.md#loop)) - -:::warning[**Внимание!**] -У локальных переменных есть одна особенность, которую нужно очень чётко понимать. Значение объявленной в данном блоке кода локальной переменной транслируется и во все вложенные, или вызванные из данного, блоки кода. Например, если на локации объявлена локальная переменная, то её значение транслируется во все вызываемые с помощью `GOSUB` или `FUNC` локации, в блоки кода для `DYNAMIC`/`DYNEVAL`, в блоки циклов и так далее. Пример: +Сравнивать можно и текстовые значения: ```qsp -# start -! из этой локации мы будем вызывать локацию foo -i = 99 & ! объявляем глобальную переменную -gosub 'foo' -*nl i & ! на экране увидим число 99 ---- start --- - -# foo -! на этой локации объявляем локальную переменную -local i = 0 -! локальная переменная транслируется в цикл -loop while i < 10 step i += 1: - ! в цикле мы вызываем локацию undo - gosub 'undo' - ! и так же в цикле мы работаем с переменной, - ! объявленной на локации foo -end -*nl i & ! на экране увидим число 10 ---- foo --- - -# undo -! в эту локацию из цикла с локации foo -! транслируется всё та же локальная переменная -! объявленная на локации foo -i+=1 & ! увеличиваем значение переменной, влияя на значение в foo -*p 'undo:<>, ' & ! на экране появятся числа 1,3,5,7,9 с припиской undo: ---- undo --- +"a" <= "z" & ! верно +"z" <= "zz" & ! верно +"aaaaaa" <= "z" & ! верно +"z" <= "z" & ! верно ``` -**Однако!** Значения локальных переменных не транслируются в действия (в отличие от значений массива `ARGS` на текущей локации): +И кортежи: ```qsp -$args[0] = 'текущая локация' -local $var = 'локальная переменная' -*pl $args[0] -*pl $var -act "Вывести значения": - *pl $args[0] - *pl $var -end -``` - -::: - -### Примеры назначения локальных переменных - -```qsp title="Две локации, на каждой из которых собственная переменная i" -# локация 1 -if i = 0: i = 99 & ! значение переменной i задаётся лишь раз -*pl "Глобальное i = <>" -act "На локацию 2": goto 'локация 2' ---- локация 1 --- - -# локация 2 -*pl "Глобальное i = <>" -local i = 137 & ! значение переменной i задаётся лишь раз -*pl "Локальное i = <>" -act "На локацию 1": goto 'локация 1' ---- локация 2 --- -``` - -```qsp title="Ещё пример с двумя локациями" -! этот код последовательно выведет на экран числа 12, 549 и 99, 549 -# start -x = 99 -z = 4608 -gosub 'foo' -*pl x & *pl z & ! на экран выведутся числа 99 и 549 ---- start --- - -# foo -local x & ! объявляем переменную x локальной для данной локации -x = 12 & ! изменяем значение переменной x -z = 549 -*pl x & *pl z & ! на экран выведутся числа 12 и 549 ---- foo --- -``` - -```qsp title="Пример объявления локальных переменных в коде для DYNEVAL и в цикле" -$chkObjWord = { - ! это код, записанный в виде текста в переменную $chkObjWord - ! в локальную переменную $word записываем слово, - ! по которому производим поиск - local $word = $args[0] - loop local i = 1 while no i > countobj step i += 1: - ! используем локальную переменную i внутри цикла - ! цикл выполняется пока счётчик не превысит число предметов - if instr($getobj(i), $word) <> 0: - ! как только в названии очередного предмета - ! встречается рассматриваемое слово - result = i & ! возвращаем позицию - exit & ! закрываем функцию - end - end -} -object_position = dyneval($chkObjWord, 'граната') -``` - -```qsp title="Локальные переменные можно объявлять и внутри действий" -i=99 -act "Действие с локальной i": - local i = 449933 - *pl i -end -act "Действие с глобальной i": - *pl i -end +[1, 2, 3] <= [1, 2, 9] & ! верно +[1, 2, 3] <= [2, 2, 3] & ! верно +[1, 2] <= [1, 2, 3] & ! верно +[1, 2, 3] <= [1, 2, 3] & ! верно ``` -## LOOP - -`LOOP` — оператор цикла. Необходим для организации циклических вычислений. Общая запись однострочной формы: - -```qsp -LOOP {команды до начала цикла} WHILE [условие] STEP {команды в конце итеррации}: {операторы тела цикла} -``` +## `<>` (не равно) -Общая запись многострочной формы: +`<>` — операция сравнения "НЕ РАВНО". Общая запись: ```qsp -LOOP {команды до начала цикла} WHILE [условие] STEP {команды в конце итеррации}: - {операторы тела цикла} -END +[выражение_1] <> [выражение_2] ``` -, где: +Если значение выражения `[выражение_1]` не равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт `0`. Иными словами: верно, если выражения не равны. -- `{команды до начала цикла}` — это команды, выполняемые до того, как цикл будет запущен. Данные команды относятся к блоку цикла, но не попадают в итерации (проходы), т.е. выполняются только один раз. Здесь можно, например, объявить счётчик цикла. И здесь можно писать множество команд, перечисляя их через разделитель `&` (амперсанд). -- `[условие]` — это выражение, по значению которого проверяется условие. Здесь могут использоваться операции сравнения и логические операции в любых связках. В случае, если значение выражения `[условие]` равно нулю, цикл прерывается. -- `{команды в конце итеррации}` — это команды, выполняемые в конце каждого прохода цикла. Сюда можно помещать команды, которые не относятся напрямую к телу цикла, но тем не менее должны быть выполнены на каждой итерации. Здесь можно, например, изменять значение счётчика цикла. И здесь можно писать на самом деле множество команд, перечисляя их через разделитель `&` (амперсанд). -- `{операторы тела цикла}` — это команды, которые необходимо выполнять на каждом проходе, и являющиеся основными для цикла. То есть мы делаем цикл именно ради этих команд. - -Цикл в QSP является отдельным блоком кода, и это значит, что внутри этого блока кода мы можем объявить локальные переменные. Это очень удобно, потому что мы можем объявить локальную переменную для счётчика, и это не повлияет на остальные переменные на локации: +Аналогично "`!`", или конструкции: ```qsp -i = 99 -*pl "i до цикла <>" -loop local i = 0 & *p "i в цикле: " while i < 6 step i += 1: - *p "<>, " -end -*nl "i после цикла <>" +no [выражение_1] = [выражение_2] ``` -Циклы очень удобно использовать для перебора массивов. Например, с помощью цикла можно сложить все числа, хранящиеся в массиве: +Примеры: ```qsp -summ=0 & ! сюда будем записывать сумму чисел -! наши числа лежат в массиве **mass** -loop local i, size = 0, arrsize('mass') while i < size step i += 1: - summ += mass[i] -end -*pl 'Сумма всех элементов массива mass: <>' +! 2 не равно 4 — вернёт 1 +2 <> 4 +! 5 равно 5 — вернёт 0 +5 <> 5 ``` -## MENU - -`MENU` — в любом месте игры выводит на экран всплывающее меню, пункты которого прописаны в указанном массиве. Общая запись: +Можно сравнивать и строковые значения: ```qsp -MENU [$название массива] +"abc" <> "def" & ! вернёт 1 +"abc" <> "abc" & ! вернёт 0 ``` -Прежде, чем использовать данный оператор, необходимо заполнить массив, на основе содержимого которого будут формироваться пункты меню. Пункты меню — это кортежи из трёх значений, последовательно помещаемые в подряд идущие ячейки массива, начиная с нулевой. Содержимое каждого кортежа должно быть примерно таким: +Можно сравнивать кортежи: ```qsp -["название пункта меню", "название локации", "путь к файлу иконки"] +[1, 2, 3] <> [4, 6, 7] & ! вернёт 1 +[1, 2, 3] <> [1, 2, 3] & ! вернёт 0 ``` -Название пункта меню — это то, что мы увидим на экране, когда меню будет выведено; название локации — это название локации, код которой будет выполняться при щелчке на соответствующем пункте меню; путь к файлу иконки — это путь к файлу изображения, которое будет выведено рядом с названием пункта меню. +## `=` (равно) -Зная это, мы можем заполнить массив для того, чтоб создать наши пункты меню: +`=` — операция сравнения "РАВНО". Общая запись: ```qsp -%stone[0] = ['Взять камень', 'takestone'] -%stone[1] = ['Кинуть камень', 'throwstone'] -%stone[2] = ['Осмотреть камень', 'lookstone'] +[выражение_1] = [выражение_2] ``` -Здесь название массива (`%stone`) - это название меню, а кортежи - действия, для которых указаны названия пунктов и названия локаций-обработчиков выбора пунктов меню. При выборе пункта "Взять камень" произойдёт вызов локации с названием "takestone". Аналогично будет происходить с другими пунктами. +Если значение выражения `[выражение_1]` равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт `0`. Иными словами: верно, если выражения равны. -Чтобы вывести меню на экран, нужно воспользоваться оператором `MENU`: +Аналогично конструкции: ```qsp -menu '%stone' +no [выражение_1] <> [выражение_2] ``` -Пример создания меню с иконками: +Примеры: ```qsp -! нет иконки -%usr_menu[0] = ['Взять предмет', 'take_item'] -! иконка задана gif-файлом -%usr_menu[1] = ['Положить предмет', 'put_item', 'images/put_item.gif'] -! иконка задана значением $icon_file -%usr_menu[2] = ['Уничтожить предмет','del_item', $icon_file] -! пункт меню задан 3-мя переменными -%usr_menu[3] = [$name, $location, $icon_file] - -menu 'usr_menu' &! покажет меню из 4-х пунктов +! 2 не равно 4 — вернёт 0 +(2 = 4) +! 5 равно 5 — вернёт 1 +(5 = 5) ``` -Меню заканчивается на элементе массива со пустым кортежем, либо с кортежем, в котором отсутствует значение для названия пункта меню или локации-обработчика пункта меню. - -Примеры, когда два последних пункта меню не будут созданы: +Можно сравнивать и строковые значения: ```qsp -%usr_menu[0]=['Взять предмет','take_item'] & ! этот пункт мы увидим на экране -$usr_menu[1]=['Осмотреть предмет','look_item'] & ! и этот пункт мы увидим на экране -$usr_menu[2]=[] & ! пустой кортеж, плеер посчитает, что меню кончилось -$usr_menu[3]=['Положить предмет','put_item'] & ! этот пункт мы не увидим +("abc" = "def") & ! вернёт 0 +("abc" = "abc") & ! вернёт 1 ``` -```qsp -%usr_menu[0]=['Взять предмет','take_item'] & ! этот пункт мы увидим на экране -$usr_menu[1]=['Осмотреть предмет','look_item'] & ! и этот пункт мы увидим на экране -$usr_menu[2]=['уничтожить предмет', ''] & ! не указана локация-обработчик, пункт не увидим -$usr_menu[3]=['Положить предмет','put_item'] & ! и этот пункт мы не увидим -``` +Можно сравнивать кортежи: ```qsp -%usr_menu[0]=['Взять предмет','take_item'] & ! этот пункт мы увидим на экране -$usr_menu[1]=['Осмотреть предмет','look_item'] & ! и этот пункт мы увидим на экране -$usr_menu[2]=['', 'del_item'] & ! не указано название, пункт не увидим -$usr_menu[3]=['Положить предмет','put_item'] & ! и этот пункт мы не увидим +([1, 2, 3] = [4, 6, 7]) & ! вернёт 0 +([1, 2, 3] = [1, 2, 3]) & ! вернёт 1 ``` -Чтобы вставить разделитель в меню, используйте кортеж со значениями -. Т.е. если нужно поставить разделитель вместо 3-го элемента: - -```qsp -%usr_menu[0]=['Взять предмет','take_item'] -$usr_menu[1]=['Осмотреть предмет','look_item'] -$usr_menu[2]=['-', '-'] & ! разделитель вместо пункта меню -$usr_menu[3]=['Положить предмет','put_item'] -``` - -В локацию-обработчик выбора пункта меню передаётся аргумент (`args[0]`) - позиция выбранного пункта. Позиции элементов меню нумеруются с 1. - -:::note[Устаревший вариант заполнения массива меню. Строки] - -Этот вариант можно использовать, как в плеерах версии 5.9.0, так и в более ранних версиях. - -Здесь пункты меню — это строковые значения массива с особым форматом записи: - -```qsp -"название пункта меню:название локации:путь к файлу иконки" -``` +:::warning[Внимание!] +Не путайте с операцией [присвоения](#-присвоение). +::: -- Название пункта меню — это то, что мы увидим на экране, когда меню будет выведено; -- название локации — это название локации-обработчика пункта меню, код которой будет выполняться при щелчке на соответствующем пункте меню; -- путь к файлу иконки — это путь к файлу изображения, которое будет выведено рядом с названием пункта меню. Если путь к файлу иконки не указан или указанный файл недоступен, то пункт меню отобразится без иконки. +## `=` (присвоение) -Поиск символов ":" начинается с конца строки, то есть название пункта меню может содержать двоеточия, однако тогда обязательно после названия локации должно стоять двоеточие, даже если вы не используете иконки для пунктов меню. +`=` — операция присвоения. Общая запись: ```qsp -$stone[0]='Камень: взять:takestone:' -$stone[1]='Камень: кинуть:throwstone:' -$stone[2]='Камень: осмотреть:lookstone:' +ИМЯ_МАССИВА = [значение] ``` -Если путь к файлу иконки не указан или указанный файл недоступен, то пункт меню отобразится без иконки. +, где `ИМЯ_МАССИВА` — название переменной (не в кавычках), или название массива с указанием ячейки (не в кавычках), `[значение]` — любое значение или выражение. -Таким образом мы должны заполнить массив для того, чтоб создать наши пункты меню: +Примеры: ```qsp -$stone[0]='Взять камень:takestone' -$stone[1]='Кинуть камень:throwstone' -$stone[2]='Осмотреть камень:lookstone' +! переменной BOX присваиваем значение 13 +BOX = 13 +! переменной $text присваиваем значение "Строка текста" +$text = "Строка текста" +! нулевой ячейке массива day присваивается значение 365 +day[0] = 365 +! переменной tuple присваивается кортеж [1, 'unit', 3]: +%tuple = [1, 'unit', 3] ``` -Здесь название массива (`$stone`) - это название меню, а текстовые значения массива - действия, для которых указаны названия и названия локаций-обработчиков выбора пунктов меню. При выборе пункта "Взять камень" произойдёт обработка локации с названием "takestone". Аналогично будет происходить с другими пунктами. +Имена строковых переменных/массивов должны начинаться с символа `$`. -Чтобы вызвать меню на экран нужно воспользоваться оператором `menu`: - -```qsp -menu '$stone' -``` +Имена переменных/массивов, содержащих кортежи должны начинаться с символа `%`. -Меню можно вызывать в любом месте игры, например, из гиперссылок: +:::warning[Внимание!] +Операцию присвоения не следует путать с операцией сравнения "РАВНО", хотя они очень похожи: ```qsp -'Камень' +! операция присвоения +alukard = 1000 +! операция сравнения +(alukard = 1000) ``` -Пример создания меню с иконками: +В этом случае плеер понимает, что внутри скобок находится операция сравнения, потому что скобки используются для записи выражений. Запись: ```qsp -! нет иконки -$usr_menu[0] = 'Взять предмет:take_item' -! иконка задана gif-файлом -$usr_menu[1] = 'Положить предмет:put_item:images/put_item.gif' -! иконка задана значением $icon_file -$usr_menu[2] = 'Осмотреть предмет:look_item:<<$icon_file>>' -! пункт меню задан 3-мя переменными -$usr_menu[3] = '<<$name>>:<<$location>>:<<$file>>' - -menu 'usr_menu' &! покажет меню из 4-х пунктов +"abc" = "abc" ``` -Меню заканчивается на элементе массива со значением `''` (пустая строка). Т.е. если массив меню состоит из элементов 'Взять', 'Осмотреть', '', 'Бросить', то 2 последних пункта меню не будут созданы: +синтаксически ошибочна. Плеер выдаст ошибку: недопустимое название переменной/массива. Так как в этом случае он не понимает, что это операция сравнения. -```qsp -$usr_menu[0] = 'Взять предмет:take_item' & ! этот пункт мы увидим на экране -$usr_menu[1] = 'Осмотреть предмет:look_item' & ! и этот пункт мы увидим на экране -$usr_menu[2] = '' & ! здесь пустое значение, плеер посчитает, что меню кончилось -$usr_menu[3] = 'Положить предмет:put_item' & ! этот пункт мы не увидим -``` - -Чтобы вставить разделитель в меню, вместо соответствующего элемента массива напишите `"-:-"`. Т.е. если нужно поставить разделитель вместо 3-го элемента: +Если перед операцией сравнения явно стоит оператор, скобки можно не писать: ```qsp -$usr_menu[0] = 'Взять предмет:take_item' -$usr_menu[1] = 'Осмотреть предмет:look_item' -$usr_menu[2] = '-:-' -$usr_menu[3] = 'Положить предмет:put_item' +if alukard = 150: *pl "Не хватает сил" +*pl "abc" = "abc" ``` ::: -## MSG +### Множественное присвоение -`MSG` — вывод указанного сообщения в диалоговом окне. Общая запись: +Множественное присвоение позволяет одной командой `=` присвоить значения сразу нескольким переменным или ячейкам массива. Общая запись: ```qsp -MSG [сообщение] +ИМЯ_МАССИВА_1, ИМЯ_МАССИВА_2, ... , ИМЯ_МАССИВА_N = [ЗНАЧЕНИЕ_1], [ЗНАЧЕНИЕ_2], ... , [ЗНАЧЕНИЕ_N] ``` -, где `[сообщение]` — любая строка текста, число, выражение любого типа. Примеры: +, где слева от знака `=` пишутся имена переменных (или имена массивов с указанием индекса ячейки в квадратных скобках), а справа от знака `=` перечисляются значения, которые нужно присвоить переменным или ячейкам массивов. -Примеры: +:::warning[Важно помнить!] +Слева от знака равенства должно быть столько же переменных, сколько справа значений. Число переменных, и число присваиваемых значений — должны совпадать. -```qsp -! простой вывод сообщения. -msg 'Много спелых груш.' -! получим окно с сообщением 'Много спелых груш' -``` +При распаковке кортежей это правило не соблюдается. +::: -```qsp -! Пример сообщения в действии ACT. -act 'Поесть груш': - msg 'Ммм груши очень вкусные.' -end -! Получим вывод сообщения при клике по действию "Поесть груш" -``` +Примеры: ```qsp -!Пример с условием. -if hlebgotov = 1: - msg 'Похоже хлеб уже готов.' -end -! Получаем вывод сообщения когда условие hlebgotov = 1 +яблоки_в_кармане, яблоки_в_лукошке, яблоки_у_Лёшки = 58, 11, 19 +$строка_1, $строка_2 = 'Ехал Грека Через Реку', 'Видит Грека В Реке Рак' +$name, count = 'Старый меч', 2 ``` -## NL - -`NL` — переход на новую строку, затем вывод текста в окне дополнительного описания. Общая запись: +Вместо прямого указания значений можно присваивать значения других переменных, выражений, функций: ```qsp -NL [$текст] +! три переменные = три значения +red, green, blue = rand(0,255), rand(0,255), rand(0,255) +! две переменные = два значения +яблоки_в_кармане, яблоки_в_лукошке = яблоки_у_Лёшки, яблоки_на_дереве+15 ``` -, где `[$текст]` — любая строка текста, число, или выражение любого типа. Если `[$текст]` отсутствует, происходит просто переход на новую строку. Пример: +Благодаря возможности одновременно присваивать значения сразу нескольким переменным, можно менять местами данные в двух переменных, не прибегая к помощи третьей: ```qsp -p "Текст без перехода на новую строку." -nl "Переход на новую строку + выведение текста." -p "Текст без перехода на новую строку." +! присваиваем пременным x и y значения 12 и 99 +x, y = 12, 99 +! меняем местами значения. Теперь в x находится число 99, а в y — 12 +x, y = y, x ``` -## OPENGAME +### Распаковка кортежей -`OPENGAME` — загрузка указанного файла состояния игры. Общая запись: +Поскольку кортежи содержат в себе сразу несколько значений, запись присвоения значений переменным из кортежа может отличаться от привычной: ```qsp -OPENGAME [$путь] +! %unit = [187, 94, 'steel', [0, 2]] +рост, вес, $материал, %координаты = %unit ``` -, где `[$путь]` — путь к файлу сохранённого состояния игры. Если параметр `[$путь]` отсутствует, то вызывается окно загрузки состояния игры. +Как видите, здесь у нас слева четыре имени переменной, а справа только одно имя переменной-кортежа. Такое присвоение называется распаковкой — значения извлекаются из кортежа и помещаются в указанные переменные. -Пример: +Точно так же распаковывается кортеж, даже не помещённый в переменную: ```qsp -! загрузка состояния из файла 1.sav -opengame "1.sav" -! открываем окно загрузки состояния -opengame +рост, вес, $материал, %координаты = [187, 94, 'steel', [0, 2]] ``` -См. также локацию-обработчик события загрузки состояния игры ([$ongload](qsp-keyword-sys-var.md#ongload)). - -## OPENQST - -`OPENQST` — открытие и запуск указанного файла игры. Общая запись: +Такая запись мало чем отличается от множественного присвоения, поэтому внешние квадратные скобки не обязательны: ```qsp -OPENQST [$путь] +рост, вес, $материал, %координаты = 187, 94, 'steel', [0, 2] ``` -, где [$путь] — путь к файлу игры, который требуется запустить. Пример: - -```qsp -openqst "gamespool/cubesgame.qsp" -``` +Cледует подчеркнуть, что **множественное присвоение — это по сути распаковка кортежей**. -При использовании данного оператора, не происходит удаления переменных, удаления предметов инвентаря, очистки дополнительного описания и строки ввода, а также остановки проигрываемых файлов. Если вам нужно очистить экран и значения всех переменных, можно прописать в начале загружаемого файла игры такие команды: +Поскольку, если переменных слева от знака равенства будет больше, чем значений в кортеже, в "лишние" переменные запишутся значения по умолчанию для этих переменных, то и при множественном присвоении произойдёт то же самое. ```qsp -killall & cls & close all +r, g, b, a = [255, 188, 19] +! r = 255, g = 188, b = 19, a = 0 +raz, dva, tri, chetyre = 137, 61 +! raz = 137, dva = 61, tri = 0, chetyre = 0 ``` -## P - -`P` — вывод текста в окно дополнительного описания без перехода на новую строку. Вывод текста любым другим оператором сразу после p добавит новый текст сразу после текущего. Общая запись: +В то же время, если при множественном присвоении переменных слева от знака равенства будет меньше, чем значений справа, это вызовет ошибку о несоответствии типов данных: -```qsp -P [$текст] +```qsp title="Несоответствие типов данных" +coords = 23, 34 +age, weight, material = 27, 94, 'steel', 'biorobot' ``` -, где `[$текст]` — любая строка текста, число, или выражение любого типа. `[$текст]` может быть пустой строкой `''`, но не должен отсутствовать. Пример: +Если тип последней из перечисленных переменных будет кортеж, такое присвоение ошибку не вызовет: ```qsp -p "Текст без перехода на новую строку." -p "Текст без перехода на новую строку." -p "" -p "Текст без перехода на новую строку." +age, weight, %type = 27, 94, 'steel', 'biorobot' +! age = 27, weight = 94, %type = ['steel', 'biorobot'] ``` -## PL - -`PL` — вывод текста в окно дополнительного описания, затем переход на новую строку. Общая запись: +## `=<` (равно либо меньше) -```qsp -PL [$текст] -``` +:::warning[Внимание!] +Данная запись, хотя и допустима в QSP, к использованию не рекомендуется. Используйте "`<=` (меньше либо равно)" вместо этого. +::: -, где `[$текст]` — любая строка текста, число, или выражение любого типа. `[$текст]` может отсутствовать, тогда просто переход на новую строку. Пример: +`=<` — операция сравнения "РАВНО ЛИБО МЕНЬШЕ". Общая запись: ```qsp -pl "Вывод текста, затем переход на новую строку." -pl & ! переход на новую строку без вывода текста -pl "Вывод текста, затем переход на новую строку." -p "Текст без перехода на новую строку." -pl "Вывод текста, затем переход на новую строку." +[выражение_1] =< [выражение_2] ``` -## PLAY +Если значение выражения `[выражение_1]` меньше либо равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт 0. Иными словами: верно, если первое меньше второго, либо равно ему. -`PLAY` — проигрывание указанного звукового файла с заданной громкостью. Общая запись: +Примеры: ```qsp -PLAY [$путь к звуковому файлу],[#громкость] +! 2 меньше 4 — вернёт 1 +2 =< 4 +! 5 равно 5 — вернёт 1 +5 =< 5 +! 7 не меньше трёх и не равно ему +7 =< 3 & ! вернёт 0 ``` -, где `[$путь к звуковому файлу]` — путь к звуковому файлу относительно файла игры, `[#громкость]` — громкость воспроизведения в процентах от 0 до 100. Параметр `[#громкость]` может отсутствовать, при этом громкость принимается равной 100%. Примеры: +Аналогично "`<=`" и конструкциям: ```qsp -!Громкость 100% -play 'sound/music.mp3' -!Громкость 50% -play 'sound/music.mp3', 50 -!Громкость 0% (без звука) -play 'sound/music.mp3', 0 -``` +([выражение_1] < [выражение_2]) or ([выражение_1] = [выражение_2]) -```qsp -!Проигрывание файла по адресу из переменной $file -! с расширением 'mid' -! и громкостью volume -$file = "melody" -play '<<$file>>.mid', volume -! аналогично: -$file = "melody.mid" -play $file, volume +no [выражение_1] > [выражение_2] ``` -Если файл уже проигрывается, то изменяется громкость звучания без его "перезапуска". Поддерживается множество различных аудиоформатов и одновременное звучание до 32-х композиций. - -## REFINT - -`REFINT` — принудительное обновление интерфейса (в т.ч. смена цветов, шрифтов, назначенных с помощью системных переменных). - -По умолчанию обновление интерфейса происходит 2 раза в секунду (каждые 500 мс). Так же см. оператор [`settimer`](#settimer). +## `=>` (равно или больше) -## SAVEGAME +`=>` — операция сравнения "РАВНО ИЛИ БОЛЬШЕ". Общая запись: -`SAVEGAME` — сохранение состояния игры в указанный файл. Общая запись: +:::warning[Внимание!] +Данная запись, хотя и допустима в QSP, к использованию не рекомендуется. Используйте "`>=` (больше либо равно)" вместо этого. +::: ```qsp -SAVEGAME [$путь] +[выражение_1] => [выражение_2] ``` -, где `[$путь]` — путь к создаваемому файлу сохранения состояния игры. Если параметр `[$путь]` отсутствует, то вызывается окно сохранения состояния игры. +Если значение выражения `[выражение_1]` больше либо равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт 0. Иными словами: верно, если первое больше второго, либо равно ему. -Пример: +Примеры: ```qsp -! сохранение состояния в файл 1.sav -savegame "1.sav" -! открываем окно сохранения состояния -savegame +! 2 не меньше и не равно 4 — вернёт 0 +2 => 4 +! 5 равно 5 — вернёт 1 +5 => 5 +! 7 больше 3 +7 => 3 & ! вернёт 1 ``` -См. также [локацию-обработчик события сохранения состояния игры ($ongsave)](qsp-keyword-sys-var.md#ongsave). - -## SCANSTR - -`SCANSTR` — поиск в строке непересекающихся вхождений, соответствующих шаблону, и помещение этих вхождений в массив. Общая запись: +Аналогично "`>=`" и конструкциям: ```qsp -SCANSTR [$имя_массива], [$текст_для_разбора], [$регэксп], [#номер_группы] +([выражение_1] > [выражение_2]) or ([выражение_1] = [выражение_2]) +no [выражение_1] < [выражение_2] ``` -, где `[$имя_массива]` — массив, в который помещаются строки, соответствующие регулярному выражению `[$регэксп]`. поиск производится по строке `[$текст_для_разбора]`. Если указан параметр `[#номер_группы]`, в массив будет помещаться не вся строка, соответствующая регулярному выражению, а лишь часть, соответствующая указанной группе в этом регулярном выражении. +## `>` (больше) -Примеры: +`>` — операция сравнения "БОЛЬШЕ". Общая запись: ```qsp -! вытаскиваем из строки все слова: -$text = 'Шла Саша по шоссе, а Грека через реку.' -scanstr '$words', $text, '\b\w+\b' -!В массиве $words окажутся значения: 'Шла', 'Саша', 'по', 'шоссе', 'а', 'Грека', 'через', 'реку' - -! разбиваем строку по разделителю: -$text = 'утро|день|вечер|ночь' -scanstr '$words', $text, '[^|]+' -!В массиве $words окажутся значения: 'утро', 'день', 'вечер', 'ночь' - -! вытаскиваем из строки все слова, помещённые в квадратные скобки, но без квадратных скобок: -$text = '[first] ignoredtext [second][third] also ignored' -scanstr '$words', $text, '\[(.*?)\]', 1 -!В массиве $words окажутся значения: 'first', 'second', 'third' +[выражение_1] > [выражение_2] ``` -## SET +Если значение выражения `[выражение_1]` больше значения выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт `0`. Иными словами: верно, если первое больше второго. -`SET` — оператор для установки значений переменных. Общая запись: +Примеры: ```qsp -SET [название переменной] = [выражение] -SET [переменная 1], [переменная 2], ... = [значение 1], [значение 2], ... +! 2 не больше 4 — вернёт 0 +2 > 4 +! 5 не больше 5 — вернёт 0 +5 > 5 +! 7 больше 3 — вернёт 1 +7 > 3 ``` -, где `[название переменной]` — это допустимое имя переменной, `[выражение]` — это допустимое для данной переменной значение. - -Названия числовых переменных записываются без символа `$` в начале. Названия текстовых переменных записываются с символом `$` в начале. Примеры: +Сравнивать можно и текстовые значения, при этом символы сравниваются поочерёдно, и большим считается символ, стоящий ближе к концу алфавита. ```qsp -! задаём текстовую переменную -set $text = "text string" -! задаём числовую переменную -set abs = 123 -! задаём кортеж -set %tuple = [27, 184, 'steel'] -! множественное присваивание -set unit_power, $unit_name = 1300, 'DiggerBull' -! распаковка кортежа -set $name, age, height = %npc_fields +"z" > "a" & ! верно +"zz" > "z" & ! верно +"z" > "aaaaaa" & ! верно ``` -:::note[Рекомендация:] -Поскольку присваивание можно делать без оператора `set`, рекомендуем использовать данный оператор лишь для тех случаев, когда это улучшит читаемость кода. Например, при множественном присваивании: +И можно сравнивать кортежи: ```qsp -set яблоки_в_кармане, яблоки_в_лукошке, яблоки_у_Лёшки = 58, 11, 19 -set $строка_1, $строка_2 = 'Ехал Грека Через Реку', 'Видит Грека В Реке Рак' +[1, 2, 9] > [1, 2, 3] & ! верно +[1, 2, 3] > [2, 2, 3] & ! неверно +[1, 2, 3] > [1, 2] & ! верно ``` -::: - -## SETTIMER +## `>=` (больше либо равно) -`SETTIMER` — задаёт интервал обращения к локации-счётчику. Общая запись: +`>=` — операция сравнения "БОЛЬШЕ ЛИБО РАВНО". Общая запись: ```qsp -SETTIMER [#выражение] +[выражение_1] >= [выражение_2] ``` -, где `[#выражение]` — период обращения к локации-счётчику в миллисекундах. По умолчанию плеер обращается к локации-счётчику каждые 500 мс., т.е. 2 раза в секунду. - -Установка периода обращения к локации-счётчику влияет и на частоту автоматического обновления настроек интерфейса. +Если значение выражения `[выражение_1]` больше либо равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт 0. Иными словами: верно, если первое больше второго, либо равно ему. Примеры: ```qsp -! локация-счётчик будет запускаться каждые 2 секунды: -settimer 2000 -``` - -```qsp -! локация-счётчик будет запускаться 4 раза в секунду: -settimer 250 +! 2 не меньше и не равно 4 — вернёт 0 +2 >= 4 +! 5 равно 5 — вернёт 1 +5 >= 5 +! 7 больше 3 +7 >= 3 & ! вернёт 1 ``` -```qsp -! если мы задаём частоту обращения (раз в секунду) -frequency=10 & ! десять раз в секунду -settimer 1000/frequency -``` +Аналогично "`=>`" и конструкциям: ```qsp -! если мы задаём период обращения (через сколько секунд) -period=2 & ! каждые две секунды -settimer 1000*period +([выражение_1] > [выражение_2]) or ([выражение_1] = [выражение_2]) +no [выражение_1] < [выражение_2] ``` -Минимальное значение периода таким образом может быть 1 миллисекунда: +Сравнивать можно и текстовые значения, при этом символы сравниваются поочерёдно, и большим считается символ, стоящий ближе к концу алфавита. ```qsp -settimer 1 +"z" >= "a" & ! верно +"zz" >= "z" & ! верно +"z" >= "aaaaaa" & ! верно +"z" >= "z" & ! верно ``` -Однако на практике минимальное значение ограничено мощностью вашего компьютера, и оно, как правило, выше 1 миллисекунды. - -## SETVAR - -`SETVAR` — присваивает значение переменной или ячейке массива. - -Данная функция позволит избегать использования `dynamic` в тех случаях, когда нужно присвоить значение переменной, имя которой заранее неизвестно. - -Общая запись: +И кортежи: ```qsp -SETVAR [$имя_массива], [значение], [индекс] +[1, 2, 9] >= [1, 2, 3] & ! верно +[1, 2, 3] >= [2, 2, 3] & ! не верно +[1, 2] >= [1, 2, 3] & ! не верно +[1, 2, 3] >= [1, 2, 3] & ! верно ``` -, где `[$имя_массива]` — название массива или переменной, которой нужно присвоить значение; `[значение]` — значение любого типа: строка, число, кортеж, — однако тип значения, которое будет помещено в переменную определяется по префиксу типа перед именем переменной; `[индекс]` — если значение присваивается ячейке массива, необходимо указать индекс ячейки данным параметром (может быть любого типа). +## `!` (не равно) -Примеры: - -```qsp -SETVAR 'A', 65 -SETVAR '$X', 'name', 4 -SETVAR '$X', 'name', 'string index' -SETVAR '%Q', ['пример', 'кортежа'], 3 -SETVAR '%Q', ['пример', 'кортежа'], [x, y] - -$arr_pref = '%' -$arr_name = 'tuple' -SETVAR $arr_pref+$arr_name, ['кортеж', 1], 3 -``` +:::warning[Внимание!] +Не путайте с оператором комментария. -## SHOWACTS +Для улучшения читаемости кода рекомендуем использовать `<>`. +::: -`SHOWACTS` — управляет отображением окна действий на экране. Общая запись: +`!` — операция сравнения "НЕ РАВНО". Общая запись: ```qsp -SHOWACTS [#выражение] +[выражение_1]![выражение_2] ``` -, где `[#выражение]` — это число. Обычно используются значения `0` и `1`. Если значение выражения `[#выражение]` отлично от нуля, окно действий отображается. Если значение выражения `[#выражение]` равно нулю, окно действий скрыто. Примеры: +Если значение выражения `[выражение_1]` не равно значению выражения `[выражение_2]` операция вернёт `1`, в противном случае вернёт `0`. Иными словами: верно, если выражения не равны. + +Аналогично "`<>`", или конструкции: ```qsp -showacts 1 & ! показывает список действий -showacts 0 & ! скрывает список действий +no [выражение_1] = [выражение_2] ``` -Для удобства чтения кода можно заранее определить переменные `on` и `off` и использовать их: +Примеры: ```qsp -on = 1 -off = 0 -showacts on & ! показывает список действий -showacts off & ! скрывает список действий +! 2 не равно 4 — вернёт 1 +2 ! 4 +! 5 равно 5 — вернёт 0 +5 ! 5 ``` -## SHOWINPUT +## `&` (конкатенация) -`SHOWINPUT` — управляет отображением строки ввода на экране. Общая запись: +`&` — конкатенация, операция объединения строковых выражений или кортежей. Общая запись: ```qsp -SHOWINPUT [#выражение] +([$выражение 1] & [$выражение 2]) +([%выражение 1] & [%выражение 2]) ``` -, где `[#выражение]` — это число. Обычно используются значения `0` и `1`. Если значение выражения `[#выражение]` отлично от нуля, строка ввода отображается. Если значение выражения `[#выражение]` равно нулю, строка ввода скрыта. Примеры: +:::warning[внимание!] +Конкатенацию всегда нужно заключать в скобки! +::: -```qsp -showinput 1 & ! показывает строку ввода -showinput 0 & ! скрывает строку ввода -``` +Если попытаться объединить числовые значения, они будут преобразованы к строкам, а затем строки будут объединены. -Для удобства чтения кода можно заранее определить переменные `on` и `off` и использовать их: +Примеры: ```qsp -on = 1 -off = 0 -showinput on & ! показывает строку ввода -showinput off & ! скрывает строку ввода +*pl ('привет, ' & 'Мир!') +! на экране увидим строку 'привет, Мир!' +*pl ([1, 2, 3] & [4, 5, 6]) +! на экране увидим кортеж [1, 2, 3, 4, 5, 6] ``` -## SHOWOBJS - -`SHOWOBJS` — управляет отображением инвентаря на экране. Общая запись: +:::warning[внимание!] +Не путайте с символом перечисления команд: ```qsp -SHOWOBJS [#выражение] +! в данном случае на экран будут +! последовательно выведены строки "26" и "27" +"26" & "27" +! а здесь на экран будет выведена строка "2627" +("26" & "27") ``` -, где `[#выражение]` — это число. Обычно используются значения 0 и 1. Если значение выражения `[#выражение]` отлично от нуля, инвентарь отображается. Если значение выражения `[#выражение]` равно нулю, инвентарь скрыт. Примеры: - -```qsp -showobjs 1 & ! показывает инвентарь -showobjs 0 & ! скрывает инвентарь -``` +::: -Для удобства чтения кода можно заранее определить переменные `on` и `off` и использовать их: +:::tip +Не рекомендуется использовать данную операцию для объединения строк, поскольку строки можно объединять через [`+`](qsp-keyword-operators.md#-сложение): ```qsp -on = 1 -off = 0 -showobjs on & ! показывает инвентарь -showobjs off & ! скрывает инвентарь +! на экран будет выведена строка "2627" +"26"+"27" ``` -## SHOWSTAT +Такая запись создаёт меньше путаницы при чтении кода и работает аналогичным образом. -`SHOWSTAT` — управляет отображением окна дополнительного описания на экране. Общая запись: +Склеить два кортежа в один при помощи операции `+` не получится: ```qsp -SHOWSTAT [#выражение] +[2, 5] + [3, 7] +! на экране будет кортеж: [[5,9],[8,12]] ``` -, где `[#выражение]` — это число. Обычно используются значения `0` и `1`. Если значение выражения `[#выражение]` отлично от нуля, окно дополнительного описания отображается. Если значение выражения `[#выражение]` равно нулю, окно дополнительного описания скрыто. Примеры: +::: -```qsp -showstat 1 & ! показывает окно дополнительного описания -showstat 0 & ! скрывает окно дополнительного описания -``` +## AND -Для удобства чтения кода можно заранее определить переменные `on` и `off` и использовать их: +`AND` — логическое "И". Общая запись: ```qsp -on = 1 -off = 0 -showstat on & ! показывает окно дополнительного описания -showstat off & ! скрывает окно дополнительного описания +[#выражение 1] AND [#выражение 2] ``` -## SORTARR +Всё данное выражение будет верным, если верны выражения `[#выражение 1]` и `[#выражение 2]`. -`SORTARR` — сортировка указанного массива. Общая запись: +Примеры: ```qsp -SORTARR [$имя_массива], [#порядок] +! обе части выражения верны, значит и всё выражение верно +(2 = 2) and (3 <> 2) & ! выражение вернёт 1 (правда) +! одна часть выражения не верна, значит всё выражение неверно +(2 <> 2) and (3 <> 2) & ! выражение вернёт 0 (ложь) +! обе части выражения не верны, значит и всё выражение не верно +(2 <> 2) and (3 = 2) & ! выражение вернёт 0 (ложь) ``` - Здесь `[$имя_массива]` — название массива, который нужно отсортировать. Параметр `[#порядок]` можно не указывать. Если не указан или равен `0`, то сортирует массив по возрастанию (от меньшего к большему). Если равен `1`, то сортирует массив по убыванию (от большего к меньшему). - -Может сортировать массивы любых типов (числа, строки, кортежи), но не допускается смешивать значения разных типов в одном массиве. - -Для указания типа сортируемых значений нужно указать префикс типа как часть имени массива (`$`, `%`). - -Пример сортировки текстового массива: - -```qsp -$a[] = 'nn' -$a[] = 'zz' -$a[] = 'aa' -sortarr '$a' - -!проверяем результат сортировки: -loop local i=0 while i 2) & ! выражение вернёт 1 (правда) +! одна часть выражения верна, значит всё выражение верно +(2 <> 2) or (3 <> 2) & ! выражение вернёт 1 (правда) +! обе части выражения не верны, значит и всё выражение не верно +(2 <> 2) or (3 = 2) & ! выражение вернёт 0 (ложь) ``` -```qsp -! переход на локацию "улица" с передачей 2-х параметров. -! на локации "улица" args[0] равен 1, -! $args[1] содержит строку "данные". -xgoto 'улица', 1, 'данные' -``` - -Оператор имеет краткую форму `xgt`: - -```qsp -XGT [$локация], [аргумент 0], [аргумент 1], ... , [аргумент 18] -``` +:::note[5.7.0] +В старых версиях плеера операция была побитовой. +::: diff --git a/docs/language/qsp-keywords/qsp-keyword-statements.md b/docs/language/qsp-keywords/qsp-keyword-statements.md new file mode 100644 index 0000000..a4ac2f7 --- /dev/null +++ b/docs/language/qsp-keywords/qsp-keyword-statements.md @@ -0,0 +1,2043 @@ +--- +sidebar_position: 2 +--- + +# Операторы + +## Неявный оператор + +Неявный оператор — это оператор, который не прописывается в коде QSP, но производит вывод значений на экран. Он подразумевается везде, где в команде присутствует выражение без оператора. Неявный оператор выводит в **Окно основного описания** значения таким же образом, как если бы вы использовали явное указание оператора `*pl`, то есть выводит значение и совершает переход на новую строку. Примеры: + +```qsp +$AAA + '989' +'Вы находитесь в парке' +'Преформатированная + + строка' +$curloc & ! выведет на экран название локации +``` + +В отличие от оператора `*pl` неявный оператор не выводит на экран пустую строку с переходом на новую строку, если ему не передаётся никакое значение. Это означает, что если функция не возвращает никакого значения, неявный оператор просто игнорируется. Пример: + +```qsp +# start +! это код локации, вызывающей локацию-функцию +$curloc +$func('foo') +$func('foo') +$curloc +- start + +# foo +! это код локации-функции +local i = 0 +- foo +``` + +В данном случае локация-функция `foo` ничего не возвращает, поэтому на экране мы увидим две строки со словом "start", между которыми не будет пустых строк, так как неявный оператор в строках с `$func` на локации `start` будет просто проигнорирован. Сравните с: + +```qsp +# start +! это код локации, вызывающей локацию-функцию +*pl $curloc +*pl $func('foo') +*pl $func('foo') +*pl $curloc +- start + +# foo +! это код локации-функции +local i=0 +- foo +``` + +## `!` (комментарий) + +`!` — оператор комментария. То, что находится в строке после оператора комментария, и до конца строки игнорируется интерпретатором. Оператор комментария позволяет "закомментировать" (выключить) ненужный временно оператор/функцию во время отладки игры. Кроме того, написание комментариев к коду программы является одним из признаков хорошего стиля программирования. + +Необходимо чётко понимать, что это именно оператор, поэтому если вы комментируете некую строку кода, то `!` должен стоять после `&`: + +```qsp +*pl "Hello, world!" & ! комментарий +``` + +Комментарии могут быть однострочными, то есть заканчиваться в той же строке, где стоит оператор комментария: + +```qsp +! однострочный комментарий +*pl "строка текста" & ! тоже однострочный комментарий +``` + +:::tip[Исключение] +Единственным исключением из этого правила является запись комментария после двоеточия в многострочных операторах: + +```qsp +act "Многострочное действие": ! комментарий + *pl "Текст на экране" +end +``` + +::: + +Комментарии могут быть многострочными. Для этого после оператора комментария нужно записать кавычки, апострофы, или фигурные скобки. Например так: + +```qsp +! "это первая строка коммантария + это вторая строка комментария + это третья строка комментария +" +``` + +Многострочные комментарии могут принимать самые разнообразные формы: + +```qsp +! строка до кавычек " текст внутри кавычек +может переходить на другие строки " а так же { +можно использовать другие группы символов, чтобы +продолжать многострочный комментарий +} и комментарий не кончится, пока не кончится строка +``` + +## `*CLEAR` + +`*CLEAR` — очищает окно основного описания. Имеет краткую форму `*clr`. + +## `*NL` + +`*NL` — переход на новую строку, затем вывод текста в окне основного описания. Общая запись: + +```qsp +*NL [$текст] +``` + +, где `[$текст]` — любая строка текста, число, или выражение любого типа. Если `[$текст]` отсутствует, происходит просто переход на новую строку. Пример: + +```qsp +*p "Текст без перехода на новую строку." +*nl "Переход на новую строку + выведение текста." +*p "Текст без перехода на новую строку." +``` + +## `*P` + +`*P` — вывод текста в окно основного описания без перехода на новую строку. Вывод текста любым другим оператором сразу после `*p` добавит новый текст сразу после текущего. Общая запись: + +```qsp +*P [$текст] +``` + +, где `[$текст]` — любая строка текста, число, или выражение любого типа. `[$текст]` может быть пустой строкой `''`, но не должен отсутствовать. Пример: + +```qsp +*p "Текст без перехода на новую строку." +*p "Текст без перехода на новую строку." +*p "" +*p "Текст без перехода на новую строку." +``` + +## `*PL` + +`*PL` — вывод текста в окно основного описания, затем переход на новую строку. Общая запись: + +```qsp +*PL [$текст] +``` + +где `[$текст]` — любая строка текста, число, или выражение любого типа. `[$текст]` может отсутствовать, тогда просто переход на новую строку. Пример: + +```qsp +*pl "Вывод текста, затем переход на новую строку." +*pl "Вывод текста, затем переход на новую строку." +*p "Текст без перехода на новую строку." +*pl "Вывод текста, затем переход на новую строку." +``` + +Аналогичным образом можно вывести текст, просто написав нужное выражение вместо данного оператора. Например, строки: + +```qsp +*pl $AAA + '989' +*pl 'Вы находитесь в парке' +*pl 'Преформатированная + + строка' +``` + +и: + +```qsp +$AAA + '989' +'Вы находитесь в парке' +'Преформатированная + + строка' +``` + +сработают одинаково. + +## ACT + +`ACT` — создаёт и выводит в окно действий новое действие. + +Общая запись в однострочной форме: + +```qsp +ACT [$название], [$путь к файлу изображения]: [оператор] & [оператор] & [оператор] +``` + +Общая запись в многострочной форме: + +```qsp +ACT [$название], [$путь к файлу изображения]: + [оператор] + [оператор] + [оператор] +END +``` + +К списку действий в окне действий добавляется новое с названием `[$название]` и изображением, которое лежит по пути `[$путь к файлу изображения]`. При нажатии на действие выполняются заданные операторы. + +Параметр `[$путь к файлу изображения]` может отсутствовать, при этом действие добавится без изображения. + +Примеры: + +```qsp +! действие в однострочной форме записи +act "Сорвать с берёзы яблоко": яблоко += 1 & *pl "Вы сорвали яблоко, спелое белое." + +! действие в многострочной форме записи, с изображением +act "Сорвать арбуз с куста", "img/watermelon.png": + арбуз += 1 + *pl "Вы сорвали арбуз с куста" +end +``` + +Если в списке действий уже есть действие с указанным названием, то новое действие не создаётся, и не заменяет собой уже существующее, плеер просто игнорирует команду `act`. Таким образом нельзя вывести действия с одинаковыми названиями. Пример: + +```qsp +act "Действие 1": *pl "Старое действие." +act "Действие 1": *pl "Новое действие." +``` + +Однако, вы можете сымитировать действия с одинаковыми названиями в режиме распознавания HTML, добавив в названия действий HTML-тег: + +```qsp +usehtml = 1 +act 'Действие 1': *pl "Старое действие." +act 'Действие 1': *pl "Новое действие." +``` + +## ADDOBJ + +`ADDOBJ` — добавление нового предмета в окно предметов. Общая запись: + +```qsp +ADDOBJ [$название], [$путь к файлу изображения], [#позиция] +``` + +, где `[$название]` — это название предмета, `[$путь к файлу изображения]` — это путь к файлу изображения предмета (отображается рядом с названием предмета), а `[#позиция]` — на какое место в инвентаре добавляется предмет. Параметр `[#позиция]` может отсутствовать. По умолчанию предметы добавляются в конец списка. Нумерация предметов в инвентаре ведётся с `1`. Параметр `[$путь к файлу изображения]` может отсутствовать, значение по умолчанию - `''`, при этом предмет добавляется без изображения. + +:::note[Допустима, но не рекомендуется, устаревшая форма записи:] + +```qsp +ADD OBJ [$название],[$путь к файлу изображения],[#индекс] +``` + +::: + +Можно добавлять предметы с одинаковым названием, однако если вы планируете добавлять много одинаковых предметов, то лучше использовать дополнительную переменную для подсчёта этих предметов, а в окно предметов добавить один предмет, чтобы не загромождать инвентарь списком из 137 предметов Рубль / Патрон: + +```qsp +if obj('Патроны'): +! если предмет "Патроны" уже добавлен, просто увеличиваем их число + патроны += 10 +else +! если предмет "Патроны" ещё не добавлен, добавляем, и увеличиваем число + addobj 'Патроны' + патроны += 10 +end +``` + +Для хранения числа предметов можно использовать массивы, индексируемые через строки: + +```qsp +objects['деньги'] = 12 +objects['патроны'] = 137 +'Количество: <>' +``` + +Пример добавления предмета в самый верх списка (при этом все остальные предметы сместятся вниз): + +```qsp +addobj "Отвёртка", "", 1 +``` + +## CLA + +`CLA` - очистка списка текущих действий (удаление всех действий из окна действий). + +## CLEAR + +`CLEAR` — очищает окно дополнительного описания. Имеет краткую форму `clr`. + +## CLOSE + +`CLOSE` — останавливает проигрывание указанного звукового файла. Общая запись: + +```qsp +CLOSE [$путь к звуковому файлу] +``` + +, где `[$путь к звуковому файлу]` — путь к звуковому файлу относительно файла игры. Если параметр `[$путь к звуковому файлу]` не указан, происходит остановка воспроизведения всех звуковых файлов. + +## CLOSE ALL + +`CLOSE ALL` — остановка проигрывания всех активных звуковых файлов. Имеет краткую форму `close`. + +## CLS + +`CLS` — очищает все окна кроме списка предметов. Эквивалентно конструкции: + +```qsp +clear & *clear & cla & cmdclear +``` + +## CMDCLEAR + +`CMDCLEAR` — очистка строки ввода. Имеет краткую форму `cmdclr`. + +## COPYARR + +`COPYARR` — копирование содержимого одного массива в другой. Общая запись: + +```qsp +COPYARR [$приёмник], [$источник], [#начало], [#количество] +``` + +, где: `[$приёмник]` — это массив, в который производится копирование, размер и наполнение значения не имеют; `[$источник]` — это массив, из которого производится копирование; `[#начало]` — номер элемента, с которого нужно начинать копирование; `[#количество]` — сколько элементов нужно скопировать. Параметр `[#количество]` является необязательным; по умолчанию — до конца массива-источника. Параметр `[#начало]` является необязательным; по умолчанию — 0. + +Примеры: + +```qsp +! копируем все элементы массива '$b' в массив '$a' +copyarr '$a', '$b' +! при этом так же были скопированны все элементы массива 'b' в массив 'a' + +! копируем в массив 'c' элементы массива 'd', начиная с шестого +copyarr 'c', 'd', 6 + +! копируем шесть первых элементов массива 'd' в массив 'c' +copyarr 'c', 'd', 0, 6 +``` + +В силу особенностей плеера при копировании, например, числового массива `mass1` в `mass2` копируется также текстовый массив `$mass1` в `$mass2`. + +Другие примеры: + +```qsp +copyarr $arrname1, $arrname2, 10, 5 +copyarr 'a<<$arrname1>>', 'a<<$arrname2>>' +``` + +## DELACT + +`DELACT` — удаляет действие из списка действий (если такое действие существует). Общая запись: + +```qsp +DELACT [$название] +``` + +, где `[$название]` — название действия, которое хотим удалить. + +Примеры: + +```qsp +! удаляем действие с конкретным названием +delact 'Идти вперед' +! удаляем выделенное действие +delact $selact +``` + +:::note[Допустима, но не рекомендуется, устаревшая форма записи:] + +```qsp +DEL ACT [$название] +``` + +::: + +## DELOBJ + +`DELOBJ` — удаление предмета из инвентаря по названию (если такой предмет существует). Общая запись: + +```qsp +DELOBJ [$название] +``` + +, где `[$название]` — название предмета, который хотим удалить. + +Если в инвентаре присутствуют одинаковые предметы, команда удалит самый верхний с указанным индексом. + +Примеры: + +```qsp +! удаляем предмет с конкретным названием +delobj "Отвёртка" +! удаляем выделенный предмет +delobj $selobj +``` + +:::note[Допустима, но не рекомендуется, устаревшая форма записи:] + +```qsp +DEL OBJ [$название] +``` + +::: + +## DYNAMIC + +`DYNAMIC` — выполняет код, переданный в виде строки текста. Общая запись: + +```qsp + DYNAMIC([$код], [аргумент 0], [аргумент 1], ... , [аргумент 18]) +``` + +, где `[$код]` — это обычный код QSP, записанный в виде текста. Выполнение такого кода аналогично выполнению кода оператора `GOSUB`. Аргументы `[аргумент 0]`, `[аргумент 1]` и т.д. могут использоваться внутри `[$код]`, их значения автоматически помещаются в переменные `args[0]`, `args[1]`, и т.д. соответственно. После выполнения старые параметры `args` восстанавливаются, затем продолжается выполнение кода со следующей команды после `dynamic`. + +Примеры: + +```qsp +dynamic '$a = "string<<$b>>"' +dynamic '$a' +dynamic 'if $a = "string": "text!"' +dynamic " + $args[0] + addobj $args[1] +", 'Текст', 'Вилка' +``` + +Нижеследующая информация справедлива и для функции [`dyneval`](qsp-keyword-functions.md#dyneval). + +**Важно!** Если код задан с помощью апострофов (`''`) или кавычек (`""`), в тексте вычисляются подвыражения: + +```qsp +$args[0] = 'qwerty' +$code = ' + *pl "<<$args[0]>>" + *pl $args[0] +' + +dynamic $code, 'asdfg' +``` + +В этом случае при задании переменной `$code` будет вычислено подвыражение, поэтому первой строкой выведется 'qwerty', второй строкой выведется 'asdfg'. + +Фигурные скобки - третий вид кавычек используемый специально для написания динамического кода. Здесь поддерживается вложенность скобок, а перед выполнением кода не вычисляются подвыражения: + +```qsp +$args[0]='qwerty' +$code = { + *pl "<<$args[0]>>" + *pl $args[0] +} + +dynamic $code, 'asdfg' +``` + +В этом случае будут выведены две строки 'asdfg'. + +## EXIT + +`EXIT` — завершение выполнения текущего блока кода (преждевременный выход из подпрограммы, функции, обработчика какого-либо события, и т.д.). + +В качестве блока кода может выступать локация, действие, код, переданный `dynamic`'у или `dyneval`'у, или код в гиперссылке. + +Пример: + +```qsp +if args[1] = 0: + exit +else + if args[0] mod args[1] = 0: + result = 1 + else + result = 0 + end +end +``` + +:::warning[Внимание!!!] +В плеерах версии 5.8.0 появился оператор цикла `loop`. + +Тело цикла так же считается отдельным блоком кода, однако оператор `exit` прерывает не только сам цикл, но и блок кода, в котором находится цикл. +::: + +## FREELIB + +`FREELIB` — удаляет все локации, добавленные с помощью оператора `inclib`. + +:::note[5.7.0] +В старых версиях плеера команда называлась `dellib` и `killqst`. +::: + +## GOSUB + +`GOSUB` — выполнение кода указанной локации без непосредственного перехода на неё. + +Общая запись: + +```qsp +GOSUB [$локация],[аргумент 0],[аргумент 1], ... ,[аргумент 8] +``` + +, где `[$локация]` — это название локации, код которой мы хотим выполнить без непосредственного перехода на неё. Аргументы `[аргумент 0]`, `[аргумент 1]` и т.д. могут использоваться на этой локации, их значения автоматически помещаются в переменные `args[0]`, `args[1]`, и т.д. соответственно. После обработки локации предыдущие значения `args` восстанавливаются. Использование аргументов не обязательно. + +При обращении к локации по `gosub` базовое описание локации добавляется к текущему описанию, базовые действия добавляются к текущим действиям, и происходит выполнение операторов в поле "Выполнить при посещении", затем возврат на исходную строку (продолжение выполнения кода после `gosub`). + +Примеры вызова локаций по `gosub`: + +```qsp +!обработка локации "ход". Массив args[] пуст. +gosub 'ход' + +!обработка локации с названием из переменной $location +!Передаётся один параметр - args[0] равен 1. +gosub $location,1 + +!обработка локации "ход" с передачей 3-х параметров. +! $args[0] = $var (значению), args[1] = 2, +! $args[2] = "данные". Обратите внимание на символы '$'. +gosub 'ход',$var,2,'данные' +``` + +Ещё пример: + +```qsp +! это код вызова локации "переход" +gosub 'переход', 'локация' + +! а это код самой локации "переход" +# переход +*pl $args[0] & ! на экран выведется текст 'локация' +! в окне действий появится новое действие: +act 'перейти': + goto "улица" +end +- переход +``` + +Оператор имеет краткую форму `gs`: + +```qsp +GS [$локация], [аргумент 0], [аргумент 1], ... , [аргумент 18] +``` + +## GOTO + +`GOTO` — переход на указанную локацию. Общая запись: + +```qsp +GOTO [$локация], [аргумент 0], [аргумент 1], ... , [аргумент 18] +``` + +, где `[$локация]` — название локации, на которую должен быть осуществлён переход. Аргументы `[аргумент 0]`, `[аргумент 1]` и т.д. могут использоваться на этой локации, их значения автоматически помещаются в переменные `args[0]`, `args[1]`, и т.д. соответственно. Использование аргументов не обязательно. + +При переходе на новую локацию при помощи `goto` очищается окно основного описания, а также список текущих действий, затем в окно основного описания выводится текст базового описания, в окно действий — базовые действия, а так же выполняется код из поля "Выполнить при посещении" локации `[$локация]`. Так же при переходе на новую локацию изменяется значение, возвращаемое функцией `$curloc`. + +Примеры: + +```qsp +! переход на локацию "дом". +! Массив args на локации "дом" будет пуст. +goto 'дом' + +! переход на локацию "улица" с передачей 2-х параметров. +! на локации "улица" args[0] равен 1, +! $args[1] содержит строку "данные". +goto 'улица',1,'данные' +``` + +Оператор имеет краткую форму `gt`: + +```qsp +GT [$локация],[аргумент 0],[аргумент 1], ... ,[аргумент 8] +``` + +## IF + +`IF` — основной оператор для записи конструкций условий. Конструкции, записываемые с помощью этого оператора (назовём их "простыми условиями"), имеют две формы: однострочную и многострочную, — и в общем виде выглядят так: + +Общая форма записи: + +```qsp +! однострочная форма записи +IF [#выражение]: {команда 1} & {команда 2} & ... + +! многострочная форма записи +IF [#выражение]: + {команда 1} + {команда 2} + ... +END +``` + +В данном случае, если верно условие `[#выражение]`, выполняются команды `{команда 1}`, `{команда 2}` и т.д. + +- Для **однострочной формы** записи это будут только те команды, которые идут в той же строке, что и оператор `IF` до конца строки; +- а для **многострочной формы** записи это будут те команды, которые идут в последующих строках после двоеточия и до специального ключевого слова `END`. + +В качестве условия могут выступать операции сравнения, логические операции и иные выражения, возвращающие числовые значения. + +Ключевое слово `END` при многострочной форме записи должно стоять отдельной строкой. + +Если условие `[#выражение]` не верно, команды выполнены не будут. + +Примеры однострочной формы записи условий: + +```qsp +! если сумма a и b равна двум, +! переменной c присваивается значение 30 +if a + b = 2: c = 30 +! Если в инвентаре нет апельсина, выводится текст +if no obj("Апельсин"): pl "У Вас нет апельсина." +! это тоже простая однострочная форма +if ((a+b)/c)=45+54 or (b<5 or c>45) and no obj 'лопата' and $f=$vvv+'RRRRR': p 'OK' & goto 'Next' +``` + +Примеры многострочной формы записи условий: + +```qsp +if библиотека = 0: + узнал_о_тусовке = 0 + библиотека_вернулся = 1 + gt 'библиотека' +end +if a+b=2: + c=30 +end +``` + +:::warning[Обратите внимание!!!] + +При многострочной форме записи после двоеточия в той же строке, в какой находится оператор IF, не должны идти никакие команды, иначе плеер посчитает такой оператор условия однострочным, и команды в последующих строках будут выполняться в любом случае, независимо от того, верным окажется условие или нет. Пример такой ошибочной записи: + +```qsp +if библиотека = 0: узнал_о_тусовке = 0 + библиотека_вернулся = 1 &! эта строчка будет выполняться в независимости от верности условия + gt 'библиотека' &! и эта +end &! ключевое слово end - просто игнорируется +``` + +Исключением является оператор комментария записанный после двоеточия: + +```qsp +if библиотека = 0: ! если не посещал библиотеку + узнал_о_тусовке = 0 + библиотека_вернулся = 1 + gt 'библиотека' +end +``` + +Но в случае, если комментарий отделён амперсандом, условие будет считаться однострочным: + +```qsp +if библиотека = 0: & ! такой комментарий делает условие однострочным! + узнал_о_тусовке = 0 & ! эта строчка будет выполняться в независимости от верности условия + библиотека_вернулся = 1 & ! и эта + gt 'библиотека' &! и эта тоже +end &! ключевое слово end - просто игнорируется +``` + +::: + +Для многострочных форм записи допускается вложенность неограниченной глубины. Каждый уровень вложения должен заканчиваться своей строкой `end`. + +Примеры: + +```qsp +if a+b<3 or y=8: + p 'A+B<3 или Y=8' + nl + if j=88: nl & p 'NEXT' + if $h='ooo': + p 'loo' & jump 'lll' + end +end +``` + +```qsp +if a=0: + 'abc1234' + if b=0: '0' else '1' + if j=88: nl & p 'NEXT' + if $h='ooo': + p 'loo' & jump 'lll' + else + p 'sample text' + v=8 + end + 1234 +else + '01234' + g=78 +end +``` + +Несколько примеров неверной записи: + +```qsp {4} +! в этом случае, если условие не будет выполнено, +! плеер проигнорирует только команду `k1=34` +! поскольку посчитает, что это однострочное условие +if abcd=3: k1=34 + k2=35 & ! эта команда будет выполняться всегда + k3=36 & ! эта комнада будет выполняться всегда +end & ! этот end будет проигнорирован +``` + +```qsp {3,9} +! данная строка выведет ошибку неизвестное действие +! так как однострочные формы записи не должны оканчиваться end`ом +if abcd=3: k1=34 else k1=25 end +``` + +## ELSE + +`ELSE` — ключевое слово, использующееся совместно с оператором `IF`, и которое служит для предоставления альтернативы, если условие не выполнено. Ключевое слово `ELSE` так же имеет две формы записи: однострочную и многострочную. + +- Многострочную форму записи `ELSE` можно использовать только в многострочной конструкции оператора `IF`, +- однострочную форму записи можно использовать как в однострочной, так и в многострочной, конструкции оператора `IF`. Общая форма записи: + +```qsp +! однострочная форма записи +IF [#выражение]: {команда д1} & {команда д2} & ... ELSE {команда н1} & {команда н2} & ... + +! в многострочном IF: + +! многострочная форма ELSE +IF [#выражение]: + {команда д1} + {команда д2} + ... +ELSE + {команда н1} + {команда н2} + ... +END + +! однострочная форма ELSE +IF [#выражение]: + {команда д1} + {команда д2} + ... +ELSE {команда н1} & {команда н2} & ... + ! команды в следующих строках + ! до END игнорируются +END +``` + +Здесь, если условие`[#выражение]` верно, выполняются команды от двоеточия до ключевого слова `ELSE`, а если условие `[#выражение]` не верно, выполняются команды от ключевого слова `ELSE` и до конца конструкции условия. + +После `ELSE` можно ставить, а можно не ставить двоеточие. + +**При однострочной форме записи:** + +- и команды и ключевое слово `ELSE` должны быть записаны в одной строке +- окончанием альтернативного списка команд является конец строки. +- если однострочная форма записи `ELSE` используется в многострочной форме записи `IF`, все команды, которые идут в последующих строках после `ELSE` до `END` игнорируются. + +Примеры однострочной записи: + +```qsp +! если сумма a и b равна двум, переменной c присваивается значение 30 +! в противном случае (то есть если сумма a и b не равна двум) +! переменной c присваивается значение 10 +if a+b=2: c=30 else c=10 + +! в зависимости от того есть ли в инвентаре апельсин +! выводится соответствующий текст +if obj("Апельсин"): pl "У Вас есть апельсин." else pl "У Вас нет апельсина." + +! однострочная форма else внутри многострочной if +if $левая_рука = 'Великий меч': + gosub 'atack', 300 + gosub 'health.prove' + gosub 'win.prove' +else gosub 'atack', atack_power +end +``` + +**При многострочной форме записи:** + +- все команды должны идти в последующих строках после `ELSE`; + +Примеры многострочной записи: + +```qsp +if a+b=2: + c=30 +else + c=10 +end + +if obj("Апельсин"): + pl "У Вас есть апельсин." +else + pl "У Вас нет апельсина." +end + +if len($curtoken) > 0: + $tokens[curtoken_num] = $curtoken tokens_count = curtoken_num + 1 +else + tokens_count = curtoken_num +end +``` + +## ELSEIF + +`ELSEIF` — ключевое слово, которое используется совместно с оператором `IF` и позволяет определять на одном уровне вложенности последовательно-исключающие условия. Имеет однострочную и многострочную формы записи. + +- Многострочную форму записи можно использовать только в многострочных конструкциях с оператором `IF`, +- однострочную — как в многострочных, так и в однострочных конструкциях с оператором `IF`. + +Общие формы записи: + +```qsp +! однострочная в однострочном условии +IF [#выражение 1]: {набор команд 1} ELSEIF [#выражение 2]: {набор команд 2} ELSE {последний набор команд} + +! многострочная в многострочном условии +IF [#выражение 1]: + {набор команд 1} + ... +ELSEIF [#выражение 2]: + {набор команд 2} + ... +ELSEIF ... : + ... +ELSE + {последний набор команд} + ... +END + +! однострочная в многострочном условии +IF [#выражение 1]: + {набор команд 1} + ... +ELSEIF [#выражение 2]: {набор команд 2} +ELSEIF ... : ... +ELSE {последний набор команд} +END +``` + +Работает это следующим образом. Если `[#выражение 1]` верно, выполняются команды `{набор команд 1}`. Если `[#выражение 1]` неверно, но верно `[#выражение 2]`, выполняются команды `{набор команд 2}`, и т.д. И только если неверны все выражения в текущей конструкции условия, выполнятся команды после `ELSE`. Верность выражения `[#выражение 1]` не исключает верности выражения `[#выражение 2]`, однако верность выражения `[#выражение 2]` исключает верность выражения `[#выражение 1]`. + +Особенности записи `ELSEIF`: + +- Может использоваться вариант написания `ELSE IF`. Работает точно так же. +- Если в многострочной конструкции `IF` после `ELSEIF` операторы идут в той же самой строке (однострочная форма), то все последующие строки игнорируются до следующего `ELSEIF`, либо до `ELSE` или `END`. +- В конструкции `IF` c `ELSEIF` может как присутствовать, так и отсутствовать часть с `ELSE`. + +Примеры: + +```qsp +if obj('Зелье здоровья'): health += 100 esleif obj('Яблоко'): health += 15 else *pl 'Нечем пополнить силы!' + +IF ОЧКИ>124: + GOTO 'КОН3' +ELSEIF ОЧКИ>99: + GOTO 'КОН4' +ELSE + GOTO 'КОН5' +END + +if money mod 10=1 and money mod 100<>11: + *pl "У вас <> монета." +elseif money mod 10>1 and money mod 10<5 and (money mod 100<5 or money mod 100>20): + *pl "У вас <> монеты." +elseif money mod 10=0 or money mod 10>4 or (money mod 100>10 and money mod 100<21): + *pl "У вас <> монет." +end +``` + +Пример записи `ELSEIF` с операторами в той же строке: + +```qsp +! реализация switch/case на QSP +if r = 0: + 'Вариант 0' + elseif r = 1: 'Вариант 1' + elseif r = 2: 'Вариант 2' + elseif r = 3: 'Вариант 3' + else: 'Без вариантов' +end +``` + +:::tip[На заметку:] + +Для улучшения читаемости кода рекомендуется использовать конструкции с `elseif` только в многострочной форме оператора `if`. + +::: + +## INCLIB + +`INCLIB` — из заданного файла игры добавляет все локации, названия которых отсутствуют среди текущих игровых локаций. Загруженные локации полностью эквивалентны локациям из основного файла игры. Общая запись: + +```qsp +INCLIB [$путь к файлу игры] +``` + +Пример: + +```qsp +inclib "lib/easy.math.qsp" +inclib "lib/easy.title.qsp" +inclib "res/drive.qsp" +inclib "res/base.qsp" +inclib "res/intro.qsp" +``` + +:::note[5.7.0] +В более старых версиях плееров команда называлась `addqst` и `addlib`. +::: + +## JUMP + +`JUMP` — переход в текущем блоке кода на указанную метку. Общая запись: + +```qsp +JUMP [$метка] +``` + +, где `[$метка]` — это метка ниже или выше по коду (см. раздел ["Метки"](qsp-keyword-syntaxems.md#метки-)). + +`jump` находит метку только в пределах текущего блока кода, то есть метки локальны. + +Отдельными блоками кода в QSP являются: + +- код "Выполнить при посещении" конкретной локации (каждая локация - отдельный блок кода), +- код действия даже если действие добавлено программно, +- код в гиперссылке, +- код `DYNAMIC`/`DYNEVAL` + +Пример: + +```qsp +jump 'КонеЦ' +p 'Это сообщение не будет выведено' +:конец +p 'А это сообщение пользователь увидит' +``` + +:::note[5.7.0] +С помощью оператора `jump` в старых версиях плеера можно было организовывать циклы: + +```qsp +:loop +if s<9: + s=s+1 + pl s + jump 'loop' +end +p 'Всё!' +``` + +Двойной цикл с одной меткой: + +```qsp +:loop +if y<9: + if x<9: + *p "<> - " + x=x+1 + jump 'loop' + end + *pl ":<>" + y=y+1 + x=0 + jump 'loop' +end +``` + +Начиная с версии 5.8.0 для циклов введён собственный оператор `loop`. +::: + +## KILLALL + +`KILLALL` — уничтожает все переменные и удаляет все предметы из окна предметов. Эквивалентен конструкции: + +```qsp +killvar & killobj +``` + +:::warning[Внимание!] +Следует помнить, что `killall` не эквивалентен конструкции: + +```qsp +killobj & killvar +``` + +поскольку в этом случае значения переменных удаляются после удаления предметов, а значит код локации-обработчика удаления предметов успевает выполниться (см. `$onobjdel`). +::: + +Обычно `killall` используют в начале игры, если в конце игры предусмотрено действие "Начать заново". + +## KILLOBJ + +`KILLOBJ` — удаление предмета, расположенного в заданной позиции. Общая запись: + +```qsp +KILLOBJ [#номер] +``` + +, где `[#номер]` — номер предмета в окне инвентаря. Нумерация предметов начинается с 1. Если параметр `[#номер]` не указан, удаляются все предметы. При удалении каждого предмета с помощью `killobj`, происходит выполнение кода локации-обработчика удаления предметов (см. `$onobjdel`). + +Пример: + +```qsp +! удаляем самый верхний предмет в списке +killobj 1 +! удаляем самый нижний предмет в списке +killobj countobj +! удаляем все предметы +killobj +``` + +## KILLVAR + +`KILLVAR` — удаление указанного элемента массива. Общая запись: + +```qsp +KILLVAR [$название массива], [индекс элемента] +``` + +, где `[$название массива]` — название массива, из которого хотим удалить элемент, а `[индекс элемента]` — номер, текстовый индекс, или многомерный индекс элемента в массиве, который хотим удалить. Нумерация элементов массивов начинается с 0. + +Если индекс элемента не указан, то очищается весь массив. Если оператор вызван без аргументов, то удаляются все переменные и массивы. + +Примеры: + +```qsp +killvar 'a', 3 & ! удалит из массива 'a' элемент с индексом 3. +killvar 'unit', 'Десантник' & ! удаляет из массива элемент с индексом 'Десантник' +killvar 'a' & ! удаляет массив 'a' +killvar & ! удаляет все переменные, массивы +killvar '$map_cell', (3, 4) & ! удаление по многомерному индексу +``` + +При удалении элемента все следующие за ним элементы сдвигаются на позицию вверх. + +Пример: + +```qsp +a[0] = 4 +a[1] = 3 +a[2] = 23 +a[3] = 15 +KILLVAR 'a', 1 +! теперь массив выглядит так: +! a[0] = 4 +! a[1] = 23 +! a[2] = 15 +``` + +## LET + +`LET` — устаревший оператор для установки значений переменных. Общая запись: + +```qsp +LET [название переменной] = [выражение] +LET [переменная 1], [переменная 2], ... = [значение 1], [значение 2], ... +``` + +, где `[название переменной]` — это допустимое имя переменной, `[выражение]` — это допустимое для данной переменной значение. + +- Названия числовых переменных записываются без символов `$` и `%` в начале. +- Названия текстовых переменных записываются с символом `$` в начале. +- Названия переменных, содержащих кортежи, записываются с символом `%` в начале. + +Примеры: + +```qsp +! задаём текстовую переменную +let $text = "text string" +! задаём числовую переменную +let abs = 123 +! задаём кортеж +let %tuple = [123, "text string"] +! множественное присваивание +let unit_power, $unit_name = 1300, 'DiggerBull' +! распаковка кортежа +let $name, age, height = %npc_fields +``` + +:::tip +Данный оператор считается устаревшим. Используйте вместо него оператор `set`, и только в тех случаях, когда это улучшит читаемость кода. + +```qsp +! присвоение можно проводить без операторов `set` или `let`: +$text = "text string" +``` + +::: + +## LOCAL + +`LOCAL` — объявляет локальную переменную (или несколько переменных) в текущем блоке кода. + +Общая запись: + +```qsp +LOCAL [переменная 1], [переменная 2], ... +LOCAL [переменная 1], [переменная 2], ... = [значение 1], [значение 2], ... +``` + +, где `[переменная 1]`, `[переменная 2]` и т.д. — это имена переменных/массивов, записанные прямо (не в кавычках), а `[значение 1]`, `[значние 2]` и т.д. — любые значения, константы, значения выражений, функций или других переменных. + +Число переменных и значений должно совпадать (кроме случаев распаковки). + +```qsp +! объявляем одну локальную переменную +local tempora = 12 +! объявляем несколько локальных переменных +local x, y, $item = 11, 19, "Старый меч" +! объявляение с распаковкой +local i, j = %map_cell +local z, $a = [13, '37'] +``` + +В отличие от операторов `set` и `let` переменную можно объявить, но значение ей не присваивать. + +```qsp +local tempora +local x, y, $item, %map_cell +``` + +При этом, несмотря на то, что переменная создаётся, `arrsize` для неё будет возвращать `0`. Т.е. проверить, объявлена ли переменная нельзя. + +```qsp +local arr +*pl arrsize('arr') & ! выведет 0 +``` + +Собственные локальные переменные можно создавать в следующих блоках кода: + +- Локации сами по себе. +- Код, передаваемый оператору `DYNAMIC`, или функции `DYNEVAL`, в виде текста. +- Код, выполняемый при нажатии на гиперссылку. +- Код каждого отдельного Действия ([ACT](qsp-keyword-statements.md#act)). +- Код каждого отдельного Цикла ([LOOP](qsp-keyword-statements.md#loop)) + +:::warning[**Внимание!**] +У локальных переменных есть одна особенность, которую нужно очень чётко понимать. Значение объявленной в данном блоке кода локальной переменной транслируется и во все вложенные, или вызванные из данного, блоки кода. Например, если на локации объявлена локальная переменная, то её значение транслируется во все вызываемые с помощью `GOSUB` или `FUNC` локации, в блоки кода для `DYNAMIC`/`DYNEVAL`, в блоки циклов и так далее. Пример: + +```qsp +# start +! из этой локации мы будем вызывать локацию foo +i = 99 & ! объявляем глобальную переменную +gosub 'foo' +*nl i & ! на экране увидим число 99 +--- start --- + +# foo +! на этой локации объявляем локальную переменную +local i = 0 +! локальная переменная транслируется в цикл +loop while i < 10 step i += 1: + ! в цикле мы вызываем локацию undo + gosub 'undo' + ! и так же в цикле мы работаем с переменной, + ! объявленной на локации foo +end +*nl i & ! на экране увидим число 10 +--- foo --- + +# undo +! в эту локацию из цикла с локации foo +! транслируется всё та же локальная переменная +! объявленная на локации foo +i+=1 & ! увеличиваем значение переменной, влияя на значение в foo +*p 'undo:<>, ' & ! на экране появятся числа 1,3,5,7,9 с припиской undo: +--- undo --- +``` + +**Однако!** Значения локальных переменных не транслируются в действия (в отличие от значений массива `ARGS` на текущей локации): + +```qsp +$args[0] = 'текущая локация' +local $var = 'локальная переменная' +*pl $args[0] +*pl $var +act "Вывести значения": + *pl $args[0] + *pl $var +end +``` + +::: + +### Примеры назначения локальных переменных + +```qsp title="Две локации, на каждой из которых собственная переменная i" +# локация 1 +if i = 0: i = 99 & ! значение переменной i задаётся лишь раз +*pl "Глобальное i = <>" +act "На локацию 2": goto 'локация 2' +--- локация 1 --- + +# локация 2 +*pl "Глобальное i = <>" +local i = 137 & ! значение переменной i задаётся лишь раз +*pl "Локальное i = <>" +act "На локацию 1": goto 'локация 1' +--- локация 2 --- +``` + +```qsp title="Ещё пример с двумя локациями" +! этот код последовательно выведет на экран числа 12, 549 и 99, 549 +# start +x = 99 +z = 4608 +gosub 'foo' +*pl x & *pl z & ! на экран выведутся числа 99 и 549 +--- start --- + +# foo +local x & ! объявляем переменную x локальной для данной локации +x = 12 & ! изменяем значение переменной x +z = 549 +*pl x & *pl z & ! на экран выведутся числа 12 и 549 +--- foo --- +``` + +```qsp title="Пример объявления локальных переменных в коде для DYNEVAL и в цикле" +$chkObjWord = { + ! это код, записанный в виде текста в переменную $chkObjWord + ! в локальную переменную $word записываем слово, + ! по которому производим поиск + local $word = $args[0] + loop local i = 1 while no i > countobj step i += 1: + ! используем локальную переменную i внутри цикла + ! цикл выполняется пока счётчик не превысит число предметов + if instr($getobj(i), $word) <> 0: + ! как только в названии очередного предмета + ! встречается рассматриваемое слово + result = i & ! возвращаем позицию + exit & ! закрываем функцию + end + end +} +object_position = dyneval($chkObjWord, 'граната') +``` + +```qsp title="Локальные переменные можно объявлять и внутри действий" +i=99 +act "Действие с локальной i": + local i = 449933 + *pl i +end +act "Действие с глобальной i": + *pl i +end +``` + +## LOOP + +`LOOP` — оператор цикла. Необходим для организации циклических вычислений. Общая запись однострочной формы: + +```qsp +LOOP {команды до начала цикла} WHILE [условие] STEP {команды в конце итеррации}: {операторы тела цикла} +``` + +Общая запись многострочной формы: + +```qsp +LOOP {команды до начала цикла} WHILE [условие] STEP {команды в конце итеррации}: + {операторы тела цикла} +END +``` + +, где: + +- `{команды до начала цикла}` — это команды, выполняемые до того, как цикл будет запущен. Данные команды относятся к блоку цикла, но не попадают в итерации (проходы), т.е. выполняются только один раз. Здесь можно, например, объявить счётчик цикла. И здесь можно писать множество команд, перечисляя их через разделитель `&` (амперсанд). +- `[условие]` — это выражение, по значению которого проверяется условие. Здесь могут использоваться операции сравнения и логические операции в любых связках. В случае, если значение выражения `[условие]` равно нулю, цикл прерывается. +- `{команды в конце итеррации}` — это команды, выполняемые в конце каждого прохода цикла. Сюда можно помещать команды, которые не относятся напрямую к телу цикла, но тем не менее должны быть выполнены на каждой итерации. Здесь можно, например, изменять значение счётчика цикла. И здесь можно писать на самом деле множество команд, перечисляя их через разделитель `&` (амперсанд). +- `{операторы тела цикла}` — это команды, которые необходимо выполнять на каждом проходе, и являющиеся основными для цикла. То есть мы делаем цикл именно ради этих команд. + +Цикл в QSP является отдельным блоком кода, и это значит, что внутри этого блока кода мы можем объявить локальные переменные. Это очень удобно, потому что мы можем объявить локальную переменную для счётчика, и это не повлияет на остальные переменные на локации: + +```qsp +i = 99 +*pl "i до цикла <>" +loop local i = 0 & *p "i в цикле: " while i < 6 step i += 1: + *p "<>, " +end +*nl "i после цикла <>" +``` + +Циклы очень удобно использовать для перебора массивов. Например, с помощью цикла можно сложить все числа, хранящиеся в массиве: + +```qsp +summ=0 & ! сюда будем записывать сумму чисел +! наши числа лежат в массиве **mass** +loop local i, size = 0, arrsize('mass') while i < size step i += 1: + summ += mass[i] +end +*pl 'Сумма всех элементов массива mass: <>' +``` + +## MENU + +`MENU` — в любом месте игры выводит на экран всплывающее меню, пункты которого прописаны в указанном массиве. Общая запись: + +```qsp +MENU [$название массива] +``` + +Прежде, чем использовать данный оператор, необходимо заполнить массив, на основе содержимого которого будут формироваться пункты меню. Пункты меню — это кортежи из трёх значений, последовательно помещаемые в подряд идущие ячейки массива, начиная с нулевой. Содержимое каждого кортежа должно быть примерно таким: + +```qsp +["название пункта меню", "название локации", "путь к файлу иконки"] +``` + +Название пункта меню — это то, что мы увидим на экране, когда меню будет выведено; название локации — это название локации, код которой будет выполняться при щелчке на соответствующем пункте меню; путь к файлу иконки — это путь к файлу изображения, которое будет выведено рядом с названием пункта меню. + +Зная это, мы можем заполнить массив для того, чтоб создать наши пункты меню: + +```qsp +%stone[0] = ['Взять камень', 'takestone'] +%stone[1] = ['Кинуть камень', 'throwstone'] +%stone[2] = ['Осмотреть камень', 'lookstone'] +``` + +Здесь название массива (`%stone`) - это название меню, а кортежи - действия, для которых указаны названия пунктов и названия локаций-обработчиков выбора пунктов меню. При выборе пункта "Взять камень" произойдёт вызов локации с названием "takestone". Аналогично будет происходить с другими пунктами. + +Чтобы вывести меню на экран, нужно воспользоваться оператором `MENU`: + +```qsp +menu '%stone' +``` + +Пример создания меню с иконками: + +```qsp +! нет иконки +%usr_menu[0] = ['Взять предмет', 'take_item'] +! иконка задана gif-файлом +%usr_menu[1] = ['Положить предмет', 'put_item', 'images/put_item.gif'] +! иконка задана значением $icon_file +%usr_menu[2] = ['Уничтожить предмет','del_item', $icon_file] +! пункт меню задан 3-мя переменными +%usr_menu[3] = [$name, $location, $icon_file] + +menu 'usr_menu' &! покажет меню из 4-х пунктов +``` + +Меню заканчивается на элементе массива со пустым кортежем, либо с кортежем, в котором отсутствует значение для названия пункта меню или локации-обработчика пункта меню. + +Примеры, когда два последних пункта меню не будут созданы: + +```qsp +%usr_menu[0]=['Взять предмет','take_item'] & ! этот пункт мы увидим на экране +$usr_menu[1]=['Осмотреть предмет','look_item'] & ! и этот пункт мы увидим на экране +$usr_menu[2]=[] & ! пустой кортеж, плеер посчитает, что меню кончилось +$usr_menu[3]=['Положить предмет','put_item'] & ! этот пункт мы не увидим +``` + +```qsp +%usr_menu[0]=['Взять предмет','take_item'] & ! этот пункт мы увидим на экране +$usr_menu[1]=['Осмотреть предмет','look_item'] & ! и этот пункт мы увидим на экране +$usr_menu[2]=['уничтожить предмет', ''] & ! не указана локация-обработчик, пункт не увидим +$usr_menu[3]=['Положить предмет','put_item'] & ! и этот пункт мы не увидим +``` + +```qsp +%usr_menu[0]=['Взять предмет','take_item'] & ! этот пункт мы увидим на экране +$usr_menu[1]=['Осмотреть предмет','look_item'] & ! и этот пункт мы увидим на экране +$usr_menu[2]=['', 'del_item'] & ! не указано название, пункт не увидим +$usr_menu[3]=['Положить предмет','put_item'] & ! и этот пункт мы не увидим +``` + +Чтобы вставить разделитель в меню, используйте кортеж со значениями -. Т.е. если нужно поставить разделитель вместо 3-го элемента: + +```qsp +%usr_menu[0]=['Взять предмет','take_item'] +$usr_menu[1]=['Осмотреть предмет','look_item'] +$usr_menu[2]=['-', '-'] & ! разделитель вместо пункта меню +$usr_menu[3]=['Положить предмет','put_item'] +``` + +В локацию-обработчик выбора пункта меню передаётся аргумент (`args[0]`) - позиция выбранного пункта. Позиции элементов меню нумеруются с 1. + +:::note[Устаревший вариант заполнения массива меню. Строки] + +Этот вариант можно использовать, как в плеерах версии 5.9.0, так и в более ранних версиях. + +Здесь пункты меню — это строковые значения массива с особым форматом записи: + +```qsp +"название пункта меню:название локации:путь к файлу иконки" +``` + +- Название пункта меню — это то, что мы увидим на экране, когда меню будет выведено; +- название локации — это название локации-обработчика пункта меню, код которой будет выполняться при щелчке на соответствующем пункте меню; +- путь к файлу иконки — это путь к файлу изображения, которое будет выведено рядом с названием пункта меню. Если путь к файлу иконки не указан или указанный файл недоступен, то пункт меню отобразится без иконки. + +Поиск символов ":" начинается с конца строки, то есть название пункта меню может содержать двоеточия, однако тогда обязательно после названия локации должно стоять двоеточие, даже если вы не используете иконки для пунктов меню. + +```qsp +$stone[0]='Камень: взять:takestone:' +$stone[1]='Камень: кинуть:throwstone:' +$stone[2]='Камень: осмотреть:lookstone:' +``` + +Если путь к файлу иконки не указан или указанный файл недоступен, то пункт меню отобразится без иконки. + +Таким образом мы должны заполнить массив для того, чтоб создать наши пункты меню: + +```qsp +$stone[0]='Взять камень:takestone' +$stone[1]='Кинуть камень:throwstone' +$stone[2]='Осмотреть камень:lookstone' +``` + +Здесь название массива (`$stone`) - это название меню, а текстовые значения массива - действия, для которых указаны названия и названия локаций-обработчиков выбора пунктов меню. При выборе пункта "Взять камень" произойдёт обработка локации с названием "takestone". Аналогично будет происходить с другими пунктами. + +Чтобы вызвать меню на экран нужно воспользоваться оператором `menu`: + +```qsp +menu '$stone' +``` + +Меню можно вызывать в любом месте игры, например, из гиперссылок: + +```qsp +'Камень' +``` + +Пример создания меню с иконками: + +```qsp +! нет иконки +$usr_menu[0] = 'Взять предмет:take_item' +! иконка задана gif-файлом +$usr_menu[1] = 'Положить предмет:put_item:images/put_item.gif' +! иконка задана значением $icon_file +$usr_menu[2] = 'Осмотреть предмет:look_item:<<$icon_file>>' +! пункт меню задан 3-мя переменными +$usr_menu[3] = '<<$name>>:<<$location>>:<<$file>>' + +menu 'usr_menu' &! покажет меню из 4-х пунктов +``` + +Меню заканчивается на элементе массива со значением `''` (пустая строка). Т.е. если массив меню состоит из элементов 'Взять', 'Осмотреть', '', 'Бросить', то 2 последних пункта меню не будут созданы: + +```qsp +$usr_menu[0] = 'Взять предмет:take_item' & ! этот пункт мы увидим на экране +$usr_menu[1] = 'Осмотреть предмет:look_item' & ! и этот пункт мы увидим на экране +$usr_menu[2] = '' & ! здесь пустое значение, плеер посчитает, что меню кончилось +$usr_menu[3] = 'Положить предмет:put_item' & ! этот пункт мы не увидим +``` + +Чтобы вставить разделитель в меню, вместо соответствующего элемента массива напишите `"-:-"`. Т.е. если нужно поставить разделитель вместо 3-го элемента: + +```qsp +$usr_menu[0] = 'Взять предмет:take_item' +$usr_menu[1] = 'Осмотреть предмет:look_item' +$usr_menu[2] = '-:-' +$usr_menu[3] = 'Положить предмет:put_item' +``` + +::: + +## MSG + +`MSG` — вывод указанного сообщения в диалоговом окне. Общая запись: + +```qsp +MSG [сообщение] +``` + +, где `[сообщение]` — любая строка текста, число, выражение любого типа. Примеры: + +Примеры: + +```qsp +! простой вывод сообщения. +msg 'Много спелых груш.' +! получим окно с сообщением 'Много спелых груш' +``` + +```qsp +! Пример сообщения в действии ACT. +act 'Поесть груш': + msg 'Ммм груши очень вкусные.' +end +! Получим вывод сообщения при клике по действию "Поесть груш" +``` + +```qsp +!Пример с условием. +if hlebgotov = 1: + msg 'Похоже хлеб уже готов.' +end +! Получаем вывод сообщения когда условие hlebgotov = 1 +``` + +## NL + +`NL` — переход на новую строку, затем вывод текста в окне дополнительного описания. Общая запись: + +```qsp +NL [$текст] +``` + +, где `[$текст]` — любая строка текста, число, или выражение любого типа. Если `[$текст]` отсутствует, происходит просто переход на новую строку. Пример: + +```qsp +p "Текст без перехода на новую строку." +nl "Переход на новую строку + выведение текста." +p "Текст без перехода на новую строку." +``` + +## OPENGAME + +`OPENGAME` — загрузка указанного файла состояния игры. Общая запись: + +```qsp +OPENGAME [$путь] +``` + +, где `[$путь]` — путь к файлу сохранённого состояния игры. Если параметр `[$путь]` отсутствует, то вызывается окно загрузки состояния игры. + +Пример: + +```qsp +! загрузка состояния из файла 1.sav +opengame "1.sav" +! открываем окно загрузки состояния +opengame +``` + +См. также локацию-обработчик события загрузки состояния игры ([$ongload](qsp-keyword-sys-var.md#ongload)). + +## OPENQST + +`OPENQST` — открытие и запуск указанного файла игры. Общая запись: + +```qsp +OPENQST [$путь] +``` + +, где [$путь] — путь к файлу игры, который требуется запустить. Пример: + +```qsp +openqst "gamespool/cubesgame.qsp" +``` + +При использовании данного оператора, не происходит удаления переменных, удаления предметов инвентаря, очистки дополнительного описания и строки ввода, а также остановки проигрываемых файлов. Если вам нужно очистить экран и значения всех переменных, можно прописать в начале загружаемого файла игры такие команды: + +```qsp +killall & cls & close all +``` + +## P + +`P` — вывод текста в окно дополнительного описания без перехода на новую строку. Вывод текста любым другим оператором сразу после p добавит новый текст сразу после текущего. Общая запись: + +```qsp +P [$текст] +``` + +, где `[$текст]` — любая строка текста, число, или выражение любого типа. `[$текст]` может быть пустой строкой `''`, но не должен отсутствовать. Пример: + +```qsp +p "Текст без перехода на новую строку." +p "Текст без перехода на новую строку." +p "" +p "Текст без перехода на новую строку." +``` + +## PL + +`PL` — вывод текста в окно дополнительного описания, затем переход на новую строку. Общая запись: + +```qsp +PL [$текст] +``` + +, где `[$текст]` — любая строка текста, число, или выражение любого типа. `[$текст]` может отсутствовать, тогда просто переход на новую строку. Пример: + +```qsp +pl "Вывод текста, затем переход на новую строку." +pl & ! переход на новую строку без вывода текста +pl "Вывод текста, затем переход на новую строку." +p "Текст без перехода на новую строку." +pl "Вывод текста, затем переход на новую строку." +``` + +## PLAY + +`PLAY` — проигрывание указанного звукового файла с заданной громкостью. Общая запись: + +```qsp +PLAY [$путь к звуковому файлу],[#громкость] +``` + +, где `[$путь к звуковому файлу]` — путь к звуковому файлу относительно файла игры, `[#громкость]` — громкость воспроизведения в процентах от 0 до 100. Параметр `[#громкость]` может отсутствовать, при этом громкость принимается равной 100%. Примеры: + +```qsp +!Громкость 100% +play 'sound/music.mp3' +!Громкость 50% +play 'sound/music.mp3', 50 +!Громкость 0% (без звука) +play 'sound/music.mp3', 0 +``` + +```qsp +!Проигрывание файла по адресу из переменной $file +! с расширением 'mid' +! и громкостью volume +$file = "melody" +play '<<$file>>.mid', volume +! аналогично: +$file = "melody.mid" +play $file, volume +``` + +Если файл уже проигрывается, то изменяется громкость звучания без его "перезапуска". Поддерживается множество различных аудиоформатов и одновременное звучание до 32-х композиций. + +## REFINT + +`REFINT` — принудительное обновление интерфейса (в т.ч. смена цветов, шрифтов, назначенных с помощью системных переменных). + +По умолчанию обновление интерфейса происходит 2 раза в секунду (каждые 500 мс). Так же см. оператор [`settimer`](#settimer). + +## SAVEGAME + +`SAVEGAME` — сохранение состояния игры в указанный файл. Общая запись: + +```qsp +SAVEGAME [$путь] +``` + +, где `[$путь]` — путь к создаваемому файлу сохранения состояния игры. Если параметр `[$путь]` отсутствует, то вызывается окно сохранения состояния игры. + +Пример: + +```qsp +! сохранение состояния в файл 1.sav +savegame "1.sav" +! открываем окно сохранения состояния +savegame +``` + +См. также [локацию-обработчик события сохранения состояния игры ($ongsave)](qsp-keyword-sys-var.md#ongsave). + +## SCANSTR + +`SCANSTR` — поиск в строке непересекающихся вхождений, соответствующих шаблону, и помещение этих вхождений в массив. Общая запись: + +```qsp +SCANSTR [$имя_массива], [$текст_для_разбора], [$регэксп], [#номер_группы] +``` + +, где `[$имя_массива]` — массив, в который помещаются строки, соответствующие регулярному выражению `[$регэксп]`. поиск производится по строке `[$текст_для_разбора]`. Если указан параметр `[#номер_группы]`, в массив будет помещаться не вся строка, соответствующая регулярному выражению, а лишь часть, соответствующая указанной группе в этом регулярном выражении. + +Примеры: + +```qsp +! вытаскиваем из строки все слова: +$text = 'Шла Саша по шоссе, а Грека через реку.' +scanstr '$words', $text, '\b\w+\b' +!В массиве $words окажутся значения: 'Шла', 'Саша', 'по', 'шоссе', 'а', 'Грека', 'через', 'реку' + +! разбиваем строку по разделителю: +$text = 'утро|день|вечер|ночь' +scanstr '$words', $text, '[^|]+' +!В массиве $words окажутся значения: 'утро', 'день', 'вечер', 'ночь' + +! вытаскиваем из строки все слова, помещённые в квадратные скобки, но без квадратных скобок: +$text = '[first] ignoredtext [second][third] also ignored' +scanstr '$words', $text, '\[(.*?)\]', 1 +!В массиве $words окажутся значения: 'first', 'second', 'third' +``` + +## SET + +`SET` — оператор для установки значений переменных. Общая запись: + +```qsp +SET [название переменной] = [выражение] +SET [переменная 1], [переменная 2], ... = [значение 1], [значение 2], ... +``` + +, где `[название переменной]` — это допустимое имя переменной, `[выражение]` — это допустимое для данной переменной значение. + +Названия числовых переменных записываются без символа `$` в начале. Названия текстовых переменных записываются с символом `$` в начале. Примеры: + +```qsp +! задаём текстовую переменную +set $text = "text string" +! задаём числовую переменную +set abs = 123 +! задаём кортеж +set %tuple = [27, 184, 'steel'] +! множественное присваивание +set unit_power, $unit_name = 1300, 'DiggerBull' +! распаковка кортежа +set $name, age, height = %npc_fields +``` + +:::note[Рекомендация:] +Поскольку присваивание можно делать без оператора `set`, рекомендуем использовать данный оператор лишь для тех случаев, когда это улучшит читаемость кода. Например, при множественном присваивании: + +```qsp +set яблоки_в_кармане, яблоки_в_лукошке, яблоки_у_Лёшки = 58, 11, 19 +set $строка_1, $строка_2 = 'Ехал Грека Через Реку', 'Видит Грека В Реке Рак' +``` + +::: + +## SETTIMER + +`SETTIMER` — задаёт интервал обращения к локации-счётчику. Общая запись: + +```qsp +SETTIMER [#выражение] +``` + +, где `[#выражение]` — период обращения к локации-счётчику в миллисекундах. По умолчанию плеер обращается к локации-счётчику каждые 500 мс., т.е. 2 раза в секунду. + +Установка периода обращения к локации-счётчику влияет и на частоту автоматического обновления настроек интерфейса. + +Примеры: + +```qsp +! локация-счётчик будет запускаться каждые 2 секунды: +settimer 2000 +``` + +```qsp +! локация-счётчик будет запускаться 4 раза в секунду: +settimer 250 +``` + +```qsp +! если мы задаём частоту обращения (раз в секунду) +frequency=10 & ! десять раз в секунду +settimer 1000/frequency +``` + +```qsp +! если мы задаём период обращения (через сколько секунд) +period=2 & ! каждые две секунды +settimer 1000*period +``` + +Минимальное значение периода таким образом может быть 1 миллисекунда: + +```qsp +settimer 1 +``` + +Однако на практике минимальное значение ограничено мощностью вашего компьютера, и оно, как правило, выше 1 миллисекунды. + +## SETVAR + +`SETVAR` — присваивает значение переменной или ячейке массива. + +Данная функция позволит избегать использования `dynamic` в тех случаях, когда нужно присвоить значение переменной, имя которой заранее неизвестно. + +Общая запись: + +```qsp +SETVAR [$имя_массива], [значение], [индекс] +``` + +, где `[$имя_массива]` — название массива или переменной, которой нужно присвоить значение; `[значение]` — значение любого типа: строка, число, кортеж, — однако тип значения, которое будет помещено в переменную определяется по префиксу типа перед именем переменной; `[индекс]` — если значение присваивается ячейке массива, необходимо указать индекс ячейки данным параметром (может быть любого типа). + +Примеры: + +```qsp +SETVAR 'A', 65 +SETVAR '$X', 'name', 4 +SETVAR '$X', 'name', 'string index' +SETVAR '%Q', ['пример', 'кортежа'], 3 +SETVAR '%Q', ['пример', 'кортежа'], [x, y] + +$arr_pref = '%' +$arr_name = 'tuple' +SETVAR $arr_pref+$arr_name, ['кортеж', 1], 3 +``` + +## SHOWACTS + +`SHOWACTS` — управляет отображением окна действий на экране. Общая запись: + +```qsp +SHOWACTS [#выражение] +``` + +, где `[#выражение]` — это число. Обычно используются значения `0` и `1`. Если значение выражения `[#выражение]` отлично от нуля, окно действий отображается. Если значение выражения `[#выражение]` равно нулю, окно действий скрыто. Примеры: + +```qsp +showacts 1 & ! показывает список действий +showacts 0 & ! скрывает список действий +``` + +Для удобства чтения кода можно заранее определить переменные `on` и `off` и использовать их: + +```qsp +on = 1 +off = 0 +showacts on & ! показывает список действий +showacts off & ! скрывает список действий +``` + +## SHOWINPUT + +`SHOWINPUT` — управляет отображением строки ввода на экране. Общая запись: + +```qsp +SHOWINPUT [#выражение] +``` + +, где `[#выражение]` — это число. Обычно используются значения `0` и `1`. Если значение выражения `[#выражение]` отлично от нуля, строка ввода отображается. Если значение выражения `[#выражение]` равно нулю, строка ввода скрыта. Примеры: + +```qsp +showinput 1 & ! показывает строку ввода +showinput 0 & ! скрывает строку ввода +``` + +Для удобства чтения кода можно заранее определить переменные `on` и `off` и использовать их: + +```qsp +on = 1 +off = 0 +showinput on & ! показывает строку ввода +showinput off & ! скрывает строку ввода +``` + +## SHOWOBJS + +`SHOWOBJS` — управляет отображением инвентаря на экране. Общая запись: + +```qsp +SHOWOBJS [#выражение] +``` + +, где `[#выражение]` — это число. Обычно используются значения 0 и 1. Если значение выражения `[#выражение]` отлично от нуля, инвентарь отображается. Если значение выражения `[#выражение]` равно нулю, инвентарь скрыт. Примеры: + +```qsp +showobjs 1 & ! показывает инвентарь +showobjs 0 & ! скрывает инвентарь +``` + +Для удобства чтения кода можно заранее определить переменные `on` и `off` и использовать их: + +```qsp +on = 1 +off = 0 +showobjs on & ! показывает инвентарь +showobjs off & ! скрывает инвентарь +``` + +## SHOWSTAT + +`SHOWSTAT` — управляет отображением окна дополнительного описания на экране. Общая запись: + +```qsp +SHOWSTAT [#выражение] +``` + +, где `[#выражение]` — это число. Обычно используются значения `0` и `1`. Если значение выражения `[#выражение]` отлично от нуля, окно дополнительного описания отображается. Если значение выражения `[#выражение]` равно нулю, окно дополнительного описания скрыто. Примеры: + +```qsp +showstat 1 & ! показывает окно дополнительного описания +showstat 0 & ! скрывает окно дополнительного описания +``` + +Для удобства чтения кода можно заранее определить переменные `on` и `off` и использовать их: + +```qsp +on = 1 +off = 0 +showstat on & ! показывает окно дополнительного описания +showstat off & ! скрывает окно дополнительного описания +``` + +## SORTARR + +`SORTARR` — сортировка указанного массива. Общая запись: + +```qsp +SORTARR [$имя_массива], [#порядок] +``` + + Здесь `[$имя_массива]` — название массива, который нужно отсортировать. Параметр `[#порядок]` можно не указывать. Если не указан или равен `0`, то сортирует массив по возрастанию (от меньшего к большему). Если равен `1`, то сортирует массив по убыванию (от большего к меньшему). + +Может сортировать массивы любых типов (числа, строки, кортежи), но не допускается смешивать значения разных типов в одном массиве. + +Для указания типа сортируемых значений нужно указать префикс типа как часть имени массива (`$`, `%`). + +Пример сортировки текстового массива: + +```qsp +$a[] = 'nn' +$a[] = 'zz' +$a[] = 'aa' +sortarr '$a' + +!проверяем результат сортировки: +loop local i=0 while i`](qsp-keyword-operacion.md#-not-equal) -- [`=` (equal)](qsp-keyword-operacion.md#-equal) -- [`=` (assignment)](qsp-keyword-operacion.md#-assignment) -- [`=<`](qsp-keyword-operacion.md#-equal-or-less) -- [`=>`](qsp-keyword-operacion.md#-equal-or-greater) -- [`>`](qsp-keyword-operacion.md#-greater-than) -- [`>=`](qsp-keyword-operacion.md#-greater-than-or-equal) -- [`ACT`](qsp-keyword-operators.md#act) -- ~~[`ADDLIB`](qsp-keyword-operators.md#inclib)~~ -- [`ADDOBJ`](qsp-keyword-operators.md#addobj) -- ~~[`ADDQST`](qsp-keyword-operators.md#inclib)~~ -- [`AND`](qsp-keyword-operacion.md#and) +- [`*`](qsp-keyword-operators.md#-multiplication) +- [`*=`](qsp-keyword-operators.md#-multiplication-assignment) +- [`+`](qsp-keyword-operators.md#-addition) +- [`+=`](qsp-keyword-operators.md#-addition-assignment) +- ~~[`+` (unary)](qsp-keyword-operators.md#--unary-minus)~~ +- [`-`](qsp-keyword-operators.md#--subtraction) +- [`-=`](qsp-keyword-operators.md#--subtraction-assignment) +- [`-` (unary)](qsp-keyword-operators.md#--unary-minus) +- [`/`](qsp-keyword-operators.md#-division) +- [`/=`](qsp-keyword-operators.md#-division-assignment) +- [`<`](qsp-keyword-operators.md#-less-than) +- [`<=`](qsp-keyword-operators.md#-less-than-or-equal) +- [`<>`](qsp-keyword-operators.md#-not-equal) +- [`=` (equal)](qsp-keyword-operators.md#-equal) +- [`=` (assignment)](qsp-keyword-operators.md#-assignment) +- [`=<`](qsp-keyword-operators.md#-equal-or-less) +- [`=>`](qsp-keyword-operators.md#-equal-or-greater) +- [`>`](qsp-keyword-operators.md#-greater-than) +- [`>=`](qsp-keyword-operators.md#-greater-than-or-equal) +- [`ACT`](qsp-keyword-statements.md#act) +- ~~[`ADDLIB`](qsp-keyword-statements.md#inclib)~~ +- [`ADDOBJ`](qsp-keyword-statements.md#addobj) +- ~~[`ADDQST`](qsp-keyword-statements.md#inclib)~~ +- [`AND`](qsp-keyword-operators.md#and) - [`ARGS`](qsp-keyword-sys-var.md#args) - [`ARRCOMP`](qsp-keyword-functions.md#arrcomp) - [`ARRITEM`](qsp-keyword-functions.md#arritem) - 5.8.0 @@ -57,77 +57,77 @@ Crossed out commands do not work in players version 5.8.0 and above. - [`ARRSIZE`](qsp-keyword-functions.md#arrsize) - [`$BACKIMAGE`](qsp-keyword-sys-var.md#backimage) - [`BCOLOR`](qsp-keyword-sys-var.md#bcolor) -- [`CLA`](qsp-keyword-operators.md#cla) -- [`CLEAR`](qsp-keyword-operators.md#clear-1) -- [`*CLEAR`](qsp-keyword-operators.md#clear) -- [`CLOSE`](qsp-keyword-operators.md#close) -- [`CLOSE ALL`](qsp-keyword-operators.md#close-all) -- [`CLR`](qsp-keyword-operators.md#clear-1) -- [`*CLR`](qsp-keyword-operators.md#clear) -- [`CLS`](qsp-keyword-operators.md#cls) -- [`CMDCLEAR`](qsp-keyword-operators.md#cmdclear) -- [`CMDCLR`](qsp-keyword-operators.md#cmdclear) -- [`COPYARR`](qsp-keyword-operators.md#copyarr) +- [`CLA`](qsp-keyword-statements.md#cla) +- [`CLEAR`](qsp-keyword-statements.md#clear-1) +- [`*CLEAR`](qsp-keyword-statements.md#clear) +- [`CLOSE`](qsp-keyword-statements.md#close) +- [`CLOSE ALL`](qsp-keyword-statements.md#close-all) +- [`CLR`](qsp-keyword-statements.md#clear-1) +- [`*CLR`](qsp-keyword-statements.md#clear) +- [`CLS`](qsp-keyword-statements.md#cls) +- [`CMDCLEAR`](qsp-keyword-statements.md#cmdclear) +- [`CMDCLR`](qsp-keyword-statements.md#cmdclear) +- [`COPYARR`](qsp-keyword-statements.md#copyarr) - [`$COUNTER`](qsp-keyword-sys-var.md#counter) - [`COUNTOBJ`](qsp-keyword-functions.md#countobj) - [`$CURACTS`](qsp-keyword-functions.md#curacts) - [`$CURLOC`](qsp-keyword-functions.md#curloc) - [`$CUROBJS`](qsp-keyword-functions.md#curobjs) - 5.9.0 - [`DEBUG`](qsp-keyword-sys-var.md#debug) -- [`DELACT`](qsp-keyword-operators.md#delact) -- ~~[`DELLIB`](qsp-keyword-operators.md#freelib)~~ -- [`DELOBJ`](qsp-keyword-operators.md#delobj) +- [`DELACT`](qsp-keyword-statements.md#delact) +- ~~[`DELLIB`](qsp-keyword-statements.md#freelib)~~ +- [`DELOBJ`](qsp-keyword-statements.md#delobj) - [`$DESC`](qsp-keyword-functions.md#desc) - [`DISABLESCROLL`](qsp-keyword-sys-var.md#disablescroll) - ~~[`DISABLESUBEX`](qsp-keyword-sys-var.md#disablesubex)~~ -- [`DYNAMIC`](qsp-keyword-operators.md#dynamic) +- [`DYNAMIC`](qsp-keyword-statements.md#dynamic) - [`DYNEVAL`](qsp-keyword-functions.md#dyneval) -- [`ELSE`](qsp-keyword-operators.md#else) -- [`ELSEIF`](qsp-keyword-operators.md#elseif) +- [`ELSE`](qsp-keyword-statements.md#else) +- [`ELSEIF`](qsp-keyword-statements.md#elseif) - [`END`](qsp-keyword-syntaxems.md#end) -- [`EXIT`](qsp-keyword-operators.md#exit) +- [`EXIT`](qsp-keyword-statements.md#exit) - [`FCOLOR`](qsp-keyword-sys-var.md#fcolor) - [`$FNAME`](qsp-keyword-sys-var.md#fname) -- [`FREELIB`](qsp-keyword-operators.md#freelib) - 5.8.0 +- [`FREELIB`](qsp-keyword-statements.md#freelib) - 5.8.0 - [`FSIZE`](qsp-keyword-sys-var.md#fsize) - [`FUNC`](qsp-keyword-functions.md#func) - [`$GETOBJ`](qsp-keyword-functions.md#getobj) -- [`GOSUB`](qsp-keyword-operators.md#gosub) -- [`GOTO`](qsp-keyword-operators.md#goto) -- [`GS`](qsp-keyword-operators.md#gosub) -- [`GT`](qsp-keyword-operators.md#goto) -- [`IF`](qsp-keyword-operators.md#if) +- [`GOSUB`](qsp-keyword-statements.md#gosub) +- [`GOTO`](qsp-keyword-statements.md#goto) +- [`GS`](qsp-keyword-statements.md#gosub) +- [`GT`](qsp-keyword-statements.md#goto) +- [`IF`](qsp-keyword-statements.md#if) - [`IIF`](qsp-keyword-functions.md#iif) -- [`INCLIB`](qsp-keyword-operators.md#inclib) - 5.8.0 +- [`INCLIB`](qsp-keyword-statements.md#inclib) - 5.8.0 - [`$INPUT`](qsp-keyword-functions.md#input) - [`INSTR`](qsp-keyword-functions.md#instr) - [`ISNUM`](qsp-keyword-functions.md#isnum) - [`ISPLAY`](qsp-keyword-functions.md#isplay) -- [`JUMP`](qsp-keyword-operators.md#jump) -- [`KILLALL`](qsp-keyword-operators.md#killall) -- [`KILLOBJ`](qsp-keyword-operators.md#killobj) -- ~~[`KILLQST`](qsp-keyword-operators.md#freelib)~~ -- [`KILLVAR`](qsp-keyword-operators.md#killvar) +- [`JUMP`](qsp-keyword-statements.md#jump) +- [`KILLALL`](qsp-keyword-statements.md#killall) +- [`KILLOBJ`](qsp-keyword-statements.md#killobj) +- ~~[`KILLQST`](qsp-keyword-statements.md#freelib)~~ +- [`KILLVAR`](qsp-keyword-statements.md#killvar) - [`$LCASE`](qsp-keyword-functions.md#lcase) - [`LCOLOR`](qsp-keyword-sys-var.md#lcolor) - [`LEN`](qsp-keyword-functions.md#len) -- [`LET`](qsp-keyword-operators.md#let) -- [`LOC`](qsp-keyword-operacion.md#loc) -- [`LOCAL`](qsp-keyword-operators.md#local) - 5.8.0 -- [`LOOP`](qsp-keyword-operators.md#loop) - 5.8.0 +- [`LET`](qsp-keyword-statements.md#let) +- [`LOC`](qsp-keyword-operators.md#loc) +- [`LOCAL`](qsp-keyword-statements.md#local) - 5.8.0 +- [`LOOP`](qsp-keyword-statements.md#loop) - 5.8.0 - [`$MAINTXT`](qsp-keyword-functions.md#maintxt) - [`MAX`](qsp-keyword-functions.md#max) -- [`MENU`](qsp-keyword-operators.md#menu) +- [`MENU`](qsp-keyword-statements.md#menu) - [`$MID`](qsp-keyword-functions.md#mid) - [`MIN`](qsp-keyword-functions.md#min) -- [`MOD`](qsp-keyword-operacion.md#mod) +- [`MOD`](qsp-keyword-operators.md#mod) - [`MSECSCOUNT`](qsp-keyword-functions.md#msecscount) -- [`MSG`](qsp-keyword-operators.md#msg) -- [`NL`](qsp-keyword-operators.md#nl-1) -- [`*NL`](qsp-keyword-operators.md#nl) -- [`NO`](qsp-keyword-operacion.md#no) +- [`MSG`](qsp-keyword-statements.md#msg) +- [`NL`](qsp-keyword-statements.md#nl-1) +- [`*NL`](qsp-keyword-statements.md#nl) +- [`NO`](qsp-keyword-operators.md#no) - [`NOSAVE`](qsp-keyword-sys-var.md#nosave) -- [`OBJ`](qsp-keyword-operacion.md#obj) +- [`OBJ`](qsp-keyword-operators.md#obj) - [`$ONACTSEL`](qsp-keyword-sys-var.md#onactsel) - [`$ONGLOAD`](qsp-keyword-sys-var.md#ongload) - [`$ONGSAVE`](qsp-keyword-sys-var.md#ongsave) @@ -135,33 +135,33 @@ Crossed out commands do not work in players version 5.8.0 and above. - [`$ONOBJADD`](qsp-keyword-sys-var.md#onobjadd) - [`$ONOBJDEL`](qsp-keyword-sys-var.md#onobjdel) - [`$ONOBJSEL`](qsp-keyword-sys-var.md#onobjsel) -- [`OPENGAME`](qsp-keyword-operators.md#opengame) -- [`OPENQST`](qsp-keyword-operators.md#openqst) -- [`OR`](qsp-keyword-operacion.md#or) -- [`P`](qsp-keyword-operators.md#p-1) -- [`*P`](qsp-keyword-operators.md#p) -- [`PL`](qsp-keyword-operators.md#pl-1) -- [`*PL`](qsp-keyword-operators.md#pl) -- [`PLAY`](qsp-keyword-operators.md#play) +- [`OPENGAME`](qsp-keyword-statements.md#opengame) +- [`OPENQST`](qsp-keyword-statements.md#openqst) +- [`OR`](qsp-keyword-operators.md#or) +- [`P`](qsp-keyword-statements.md#p-1) +- [`*P`](qsp-keyword-statements.md#p) +- [`PL`](qsp-keyword-statements.md#pl-1) +- [`*PL`](qsp-keyword-statements.md#pl) +- [`PLAY`](qsp-keyword-statements.md#play) - [`$QSPVER`](qsp-keyword-functions.md#qspver) - [`RAND`](qsp-keyword-functions.md#rand) -- [`REFINT`](qsp-keyword-operators.md#refint) +- [`REFINT`](qsp-keyword-statements.md#refint) - [`$REPLACE`](qsp-keyword-functions.md#replace) - [`RESULT`](qsp-keyword-sys-var.md#result) - [`RGB`](qsp-keyword-functions.md#rgb) - [`RND`](qsp-keyword-functions.md#rnd) -- [`SAVEGAME`](qsp-keyword-operators.md#savegame) -- [`SCANSTR`](qsp-keyword-operators.md#scanstr) - 5.9.0 +- [`SAVEGAME`](qsp-keyword-statements.md#savegame) +- [`SCANSTR`](qsp-keyword-statements.md#scanstr) - 5.9.0 - [`$SELACT`](qsp-keyword-functions.md#selact) - [`$SELOBJ`](qsp-keyword-functions.md#selobj) -- [`SET`](qsp-keyword-operators.md#set) -- [`SETTIMER`](qsp-keyword-operators.md#settimer) -- [`SETVAR`](qsp-keyword-operators.md#setvar) - 5.9.1 -- [`SHOWACTS`](qsp-keyword-operators.md#showacts) -- [`SHOWINPUT`](qsp-keyword-operators.md#showinput) -- [`SHOWOBJS`](qsp-keyword-operators.md#showobjs) -- [`SHOWSTAT`](qsp-keyword-operators.md#showstat) -- [`SORTARR`](qsp-keyword-operators.md#sortarr) - 5.9.0 +- [`SET`](qsp-keyword-statements.md#set) +- [`SETTIMER`](qsp-keyword-statements.md#settimer) +- [`SETVAR`](qsp-keyword-statements.md#setvar) - 5.9.1 +- [`SHOWACTS`](qsp-keyword-statements.md#showacts) +- [`SHOWINPUT`](qsp-keyword-statements.md#showinput) +- [`SHOWOBJS`](qsp-keyword-statements.md#showobjs) +- [`SHOWSTAT`](qsp-keyword-statements.md#showstat) +- [`SORTARR`](qsp-keyword-statements.md#sortarr) - 5.9.0 - [`$STATTXT`](qsp-keyword-functions.md#stattxt) - [`$STR`](qsp-keyword-functions.md#str) - [`STRCOMP`](qsp-keyword-functions.md#strcomp) @@ -169,15 +169,15 @@ Crossed out commands do not work in players version 5.8.0 and above. - [`STRPOS`](qsp-keyword-functions.md#strpos) - [`$TRIM`](qsp-keyword-functions.md#trim) - [`$UCASE`](qsp-keyword-functions.md#ucase) -- [`UNPACKARR`](qsp-keyword-operators.md#unpackarr) - 5.9.1 -- [`UNSEL`](qsp-keyword-operators.md#unselect) -- [`UNSELECT`](qsp-keyword-operators.md#unselect) +- [`UNPACKARR`](qsp-keyword-statements.md#unpackarr) - 5.9.1 +- [`UNSEL`](qsp-keyword-statements.md#unselect) +- [`UNSELECT`](qsp-keyword-statements.md#unselect) - [`USEHTML`](qsp-keyword-sys-var.md#usehtml) - [`$USERCOM`](qsp-keyword-sys-var.md#usercom) - [`$USER_TEXT`](qsp-keyword-functions.md#user_text) - [`$USRTXT`](qsp-keyword-functions.md#user_text) - [`VAL`](qsp-keyword-functions.md#val) -- [`VIEW`](qsp-keyword-operators.md#view) -- [`WAIT`](qsp-keyword-operators.md#wait) -- [`XGOTO`](qsp-keyword-operators.md#xgoto) -- [`XGT`](qsp-keyword-operators.md#xgoto) \ No newline at end of file +- [`VIEW`](qsp-keyword-statements.md#view) +- [`WAIT`](qsp-keyword-statements.md#wait) +- [`XGOTO`](qsp-keyword-statements.md#xgoto) +- [`XGT`](qsp-keyword-statements.md#xgoto) diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md index 5afb0c1..0cf4d2c 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md @@ -119,7 +119,7 @@ dyneval("code = 123 + 890") code ``` -See also [operator `DYNAMIC`](qsp-keyword-operators.md#dynamic). +See also [operator `DYNAMIC`](qsp-keywords-statements.md#dynamic). ## `$FUNC` diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operacion.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operacion.md deleted file mode 100644 index 2e0457e..0000000 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operacion.md +++ /dev/null @@ -1,1261 +0,0 @@ ---- -sidebar_position: 1 ---- - -# Operations - -List of operations for player version 5.8.0 in ascending order of priority: - -- `OR` -- `AND` -- `NO` -- `=`, `<`, `>`, `!`, `<>`, `<=`, `>=`, `=<`, `=>` (comparison operations) -- `OBJ`, `LOC` -- `&` (concatenation) -- `+`, `-` (addition, subtraction) -- `MOD` -- `*`, `/` (multiplication, division) -- `-` (unary minus) -- `([expr])` - expressions in brackets - -Operations written on one line have equal priority and are executed in order from left to right if present at the same level in an expression. - -Operations in brackets have priority over other operations. - -Function value calculation has priority over all operations. - -A numeric expression whose value is not `0` is considered true. When the value is `0`, the expression is considered false. For the "true" value, it's strongly recommended to use `1` for compatibility with logical operations and functions returning logical values. - -:::note[5.7.0] -In older player versions, the priority order was different. - -- `&` -- `OR` -- `AND` -- `OBJ`, `LOC`, `NO` -- `=`, `<`, `>`, `!`, `<>`, `<=`, `>=`, `=<`, `=>` -- `+`, `-` -- `MOD` -- `*`, `/` -- `+`, `-` (unary) - -::: - -**Some features of comparison operations:** - -- Comparison operations return `1` (true) or `0` (false) depending on the comparison result. -- When comparing numbers, everything is simple: - - of two positive numbers, the positive number with greater magnitude will be considered greater; - - a negative number is always less than a non-negative (positive and zero); - - a positive number is always greater than a non-positive (negative and zero); - - of two negative numbers, the negative number with greater magnitude will be considered smaller. -- When comparing strings, character-by-character comparison occurs from left to right: - - the character that comes later in the character table is considered greater. You can rely on alphabetical sequence of characters to understand which string will be greater. Then character '`z`' will be greater than character '`a`'. Examples: - - ```qsp - 'z' > 'a' & ! returns 1 - 'z' > 'az' & ! returns 1 - 'akz' > 'akk' & ! returns 1 - ``` - - - when comparing any non-empty string with an empty string, the empty string will be considered smaller: - - ```qsp - ' ' > '' & ! returns 1 - 'a' > '' & ! returns 1 - 'z' > '' & ! returns 1 - 'akzakz' > 'akzak' & ! returns 1 - ``` - - :::tip[You can consider] - that missing characters in a string are empty characters (empty strings), which when compared with any other character turn out to be smaller. - ::: - - - when comparing a string with a number, the player will try to convert both values to numbers. If successful, numbers will be compared. If unsuccessful — the number will be converted to a string, and strings will be compared. - - ```qsp - 'zzz' > 123 & ! returns 1 - '123' > 92 & ! returns 1 - '123' > '92' & ! returns 0 - ``` - -- When comparing tuples, element-by-element comparison occurs from left to right: - - the tuple whose element turned out to be greater will be considered greater: - - ```qsp - [1, 2, 3] > [1, 2, 2] & ! returns 1 - [2, 2, 3] > [1, 2, 3] & ! returns 1 - ``` - - - when comparing any non-empty tuple with an empty tuple, the empty tuple will be considered smaller: - - ```qsp - [1] > [] & ! returns 1 - [''] > [] & ! returns 1 - [0] > [] & ! returns 1 - [1, 2] > [1] & ! returns 1 - [1, 2] < [9] & ! returns 1 - ``` - - :::tip[You can consider] - that missing elements in a tuple are empty elements, which when compared with any other element turn out to be smaller. - ::: - - - when comparing tuples with numbers or strings, the number or string will be compared as a tuple of one element. For easier understanding, you can consider that the number or string is converted to a tuple when compared: - - ```qsp - [8] < 9 & ! returns 1 - [9, 8] > 9 & ! returns 1 - [0, 0] > 9 & ! returns 0 - - [8, 9] > '8,9' & ! returns 0 - ['a', 'z'] < 'az' & ! returns 1 - ['a', 'z'] > 'a' & ! returns 1 - (['az'] = "az") & ! returns 1 - ``` - -:::warning[We recommend:] -Not to compare values of different types to avoid confusion. -::: - -## `*` (multiplication) - -`*` — arithmetic operation "MULTIPLICATION". Multiplies two numbers. General syntax: - -```qsp -[#expression 1] * [#expression 2] -``` - -, where `[#expression 1]` and `[#expression 2]` — any two numeric values or expressions. The operation result is the product of two numbers. - -Examples: - -```qsp -2 * 2 & ! returns 4 -4 * 2 & ! returns 8 -17 * 5 & ! returns 85 -37 * 100 & ! returns 3700 -``` - -Can be used with tuples whose values are numbers and/or other tuples containing numbers. General syntax: - -```qsp -[%tuple] * [#number] -``` - -In this case, each tuple element will be multiplied by the specified number. Examples: - -```qsp -%tuple = [4, 10, 16] -%a = %tuple * 2 -! %a will equal [8, 20, 32] - -[4, 10] * 'b' & ! data type mismatch error -``` - -Note the last example. A data type mismatch error occurs because it's impossible to apply multiplication to a string value. The same error will occur if the tuple contains string values. However, you can multiply tuples containing only numeric values: - -```qsp -*pl [2, 3] * [4, 5] -! [2 * [4,5], 3 * [4,5]] -! [[8,10],[12,15]] -``` - -In this case, each element of the first tuple is multiplied by the second tuple. This gives us a new tuple of two tuples as a result. - -## `*=` (multiplication-assignment) - -`*=` — "MULTIPLICATION-ASSIGNMENT" operation. Combines assignment and multiplication operations. Multiplies the specified variable value by a certain number and returns the result to the same variable. General syntax: - -```qsp -ARRAY_NAME *= [#expression 1] -``` - -, where `ARRAY_NAME` — variable name (without quotes) or array name with cell specification, and `[#expression 1]` — any numeric value or expression. - -Analogous to: - -```qsp -ARRAY_NAME = ARRAY_NAME*[#expression 1] -``` - -Example: - -```qsp -! we replace two operations: assignment and multiplication -warrior = warrior * 2 -! with multiplication-assignment (identical action) -warrior *= 2 -``` - -If the `ARRAY_NAME` variable value is a tuple, each tuple element will be multiplied by the specified number, and the resulting tuple will be assigned to the variable. Example: - -```qsp -%tuple = [4, 10, 16] -%tuple *= 2 -! %tuple will equal [8, 20, 32] -``` - -You cannot multiply by a string type value; this will lead to a data type mismatch error. Also, tuple values (and all nested tuples) should not contain string values when performing this operation. However, you can perform multiplication-assignment with another tuple: - -```qsp -%tuple = [2, 3] -%tuple *= [4, 5] -! %tuple will equal [[8,10],[12,15]] -``` - -:::warning[Note] -Multiplication-assignment with a tuple will cause a data type mismatch error if the variable type is not a tuple: - -```qsp -number = 4 -number *= [4,5] & ! data type mismatch error -! this way there will be no error, but the variable will contain an empty tuple: -%number *= [4,5] -``` - -::: - -## `+` (addition) - -`+` — arithmetic operation "ADDITION". Adds two numbers. General syntax: - -```qsp -[expression 1]+[expression 2] -``` - -, where `[expression 1]` and `[expression 2]` — any two values or expressions. The operation result is the sum of two values. - -Examples: - -```qsp -2+2 & ! returns 4 -4+2 & ! returns 6 -17+5 & ! returns 22 -37+100 & ! returns 137 -``` - -When "adding" string values, [concatenation](qsp-keyword-operacion.md#-concatenation) is performed, i.e., "gluing" strings together: - -```qsp -! the string "2627" will be output to screen -"26"+"27" -``` - -If values are "added" to a tuple, each tuple element is summed with the specified value: - -```qsp -%tuple = [4, 10, 16] -%a = %tuple + 2 -! %a will equal [6, 12, 18] -``` - -If two tuples are added, the second tuple is added to the values of each element of the first tuple: - -```qsp -[4, 10] + ['b', 'x'] -! [4 + ['b', 'x'], 10 + ['b', 'x']] -! [['4b','4x'], ['10b','10x']] -``` - -## `+=` (addition-assignment) - -`+=`, `(increment)` — "INCREMENT" operation, combining assignment and addition operations. Adds the specified value to the current variable value. General syntax: - -```qsp -ARRAY_NAME += [expression 1] -``` - -, where `ARRAY_NAME` — variable name (without quotes) or array name with cell specification, and `[expression 1]` — any value or expression. - -Analogous to: - -```qsp -ARRAY_NAME = ARRAY_NAME + [expression 1] -``` - -Example: - -```qsp -! we replace two operations: assignment and addition -warrior = warrior + 15 -! with increment (identical action) -warrior += 15 -``` - -It's also possible to perform increment with string values, works like [concatenation](qsp-keyword-operacion.md#-concatenation): - -```qsp -$text += " (maybe something is written here)" -``` - -If the `ARRAY_NAME` variable value is a tuple, each tuple element will be summed with the specified value, and the resulting tuple will be assigned to the variable. Example: - -```qsp -%tuple = [4, 10, 16] -%tuple += 2 -! %tuple will equal [6, 12, 18] -``` - -You can perform addition-assignment with another tuple: - -```qsp -%tuple = [2, 3] -%tuple += [4, 5] -! %tuple will equal [[6,7],[7,8]] -``` - -:::warning[Note] -Addition-assignment with a tuple will cause a data type mismatch error if the variable type is not a tuple: - -```qsp -number = 4 -number += [4,5] & ! data type mismatch error -! this way there will be no error, but the variable will contain an empty tuple: -%number += [4,5] -``` - -::: - -:::tip[Note] -Increment — in many programming languages this is an operation that performs variable increase. Most often, increment means increasing a variable by `1`. -::: - -## `-` (subtraction) - -`-` — arithmetic operation "SUBTRACTION". Subtracts one number from another. General syntax: - -```qsp -[#expression 1] - [#expression 2] -``` - -, where `[#expression 1]` and `[#expression 2]` — two numeric values or expressions. The operation result is the difference of two values. - -Examples: - -```qsp -2 - 2 & ! returns 0 -4 - 2 & ! returns 2 -17 - 5 & ! returns 12 -37 - 100 & ! returns -63 -``` - -Can be used with tuples whose values are numbers and/or other tuples containing numbers. General syntax: - -```qsp -[%tuple] - [#number] -``` - -In this case, the specified number will be subtracted from each tuple element. Examples: - -```qsp -%tuple = [4, 10, 16] -%a = %tuple - 2 -! %a will equal [2, 8, 14] - -[4, 10] - 'b' & ! data type mismatch error -``` - -Note the last example. A data type mismatch error occurs because it's impossible to apply subtraction to a string value. The same error will occur if the tuple contains string values. However, you can subtract one tuple from another if both tuples contain only numeric values: - -```qsp -*pl [2, 3] - [4, 5] -! [2 - [4,5], 3 - [4,5]] -! [2 + ([4,5] * -1), 3 + ([4,5] * -1)] -! [[-4, -5] + 2, [-4,-5] + 3] -! [[-2,-3],[-1,-2]] -``` - -In this case, the second tuple is subtracted from each element of the first tuple. If you sequentially expand brackets and perform all necessary mathematical operations, you get a new tuple containing other tuples with results. - -## `-=` (subtraction-assignment) - -**`-=`, `(decrement)`** — "DECREMENT" operation, combining assignment and subtraction operations. Subtracts the specified value from the current variable value. General syntax: - -```qsp -ARRAY_NAME -= [#expression 1] -``` - -, where `ARRAY_NAME` — variable name (without quotes) or array name with cell specification, and `[#expression 1]` — any numeric value or expression. - -Analogous to: - -```qsp -ARRAY_NAME = ARRAY_NAME - [#expression 1] -``` - -Example: - -```qsp -! we replace two operations: assignment and subtraction -warrior = warrior - 15 -! with decrement (identical action) -warrior -= 15 -``` - -If the `ARRAY_NAME` variable value is a tuple, the specified number will be subtracted from each tuple element, and the resulting tuple will be assigned to the variable. Example: - -```qsp -%tuple = [4, 10, 16] -%tuple -= 2 -! %tuple will equal [2, 8, 14] -``` - -You cannot subtract a string type value; this will lead to a data type mismatch error. Also, tuple values (and all nested tuples) should not contain string values when performing this operation. However, you can perform subtraction-assignment with another tuple: - -```qsp -%tuple = [2, 3] -%tuple -= [4, 5] -! %tuple will equal [[-2,-3],[-1,-2]] -``` - -:::warning[Note] -Subtraction-assignment with a tuple will cause a data type mismatch error if the variable type is not a tuple: - -```qsp -number = 4 -number -= [4,5] & ! data type mismatch error -! this way there will be no error, but the variable will contain an empty tuple: -%number -= [4,5] -``` - -::: - -:::tip[Note] -Decrement — in many programming languages this is an operation that performs variable decrease. Most often, decrement means decreasing a variable by `1`. -::: - -## `-` (unary minus) - -**unary `-`** — unary operation. General syntax: - -```qsp --[#expression] -``` - -, where `[#expression]` — any numeric value or expression. The result of this operation is the same value but with opposite sign. - -Examples: - -```qsp --2 & ! returns -2 --(3+6) & ! returns -9 --(-27) & ! returns 27 -``` - -Unary minus can be used before a tuple containing only numeric values. This expression will return a new tuple where the sign of each element is changed to opposite: - -```qsp -- [2, 3, -1, -17, 5] -! [-2, -3, 1, 17, -5] -``` - -:::note[5.7.0] - -In earlier player versions, there was a "unary plus" operation: - -```qsp -+(6+7) -``` - -Essentially, it did nothing, so it was decided to abandon it. -::: - -## `/` (division) - -`/` — arithmetic operation "DIVISION". General syntax: - -```qsp -[#expression 1] / [#expression 2] -``` - -, where `[#expression 1]` and `[#expression 2]` — any two numeric values or expressions. The value `[#expression 2]` must not equal zero. The operation result is the quotient of dividing two numbers. - -Since QSP supports only integer values, division is also performed as integer division, without rounding, with truncation of the fractional part. - -Examples: - -```qsp -2 / 2 & ! returns 1 -4 / 2 & ! returns 2 -17 / 5 & ! returns 3 -37 / 100 & ! returns 0 -``` - -Can be used with tuples whose values are numbers and/or other tuples containing numbers. General syntax: - -```qsp -[%tuple] / [#number] -``` - -In this case, each tuple element will be divided by the specified number. Examples: - -```qsp -%tuple = [4, 10, 16] -%a = %tuple / 2 -! %a will equal [2, 5, 8] - -[4, 10] / 'b' & ! data type mismatch error -``` - -Note the last example. A data type mismatch error occurs because it's impossible to apply division to a string value. The same error will occur if the tuple contains string values. However, you can divide tuples containing only numbers: - -```qsp -*pl [30, 60] / [2, 6] -! [30 / [2,6], 60 / [2,6]] -! [[15,5],[30,10]] -``` - -In this case, each element of the first tuple is "divided" by the second tuple. This gives us a new tuple of two tuples as a result. - -## `/=` (division-assignment) - -`/=` — "DIVISION-ASSIGNMENT" operation. Combines assignment and division operations. Divides the specified variable value by a certain number and returns the result to the same variable. General syntax: - -```qsp -ARRAY_NAME /= [#expression 1] -``` - -, where `ARRAY_NAME` — variable name (without quotes) or array name with cell specification, and `[#expression 1]` — any numeric value or expression. - -Analogous to: - -```qsp -ARRAY_NAME = ARRAY_NAME / [#expression 1] -``` - -Example: - -```qsp -! we replace two operations: assignment and division -warrior = warrior / 2 -! with division-assignment (identical action) -warrior /= 2 -``` - -If the `ARRAY_NAME` variable value is a tuple, each tuple element will be divided by the specified number, and the resulting tuple will be assigned to the variable. Example: - -```qsp -%tuple = [4, 10, 16] -%tuple /= 2 -! %tuple will equal [2, 5, 8] -``` - -You cannot divide by a string type value; this will lead to a data type mismatch error. Also, tuple values (and all nested tuples) should not contain string values when performing this operation. However, you can perform division-assignment with another tuple: - -```qsp -%tuple = [10, 30] -%tuple /= [5, 2] -! %tuple will equal [[2,5],[6,15]] -``` - -:::warning[Note] -Division-assignment with a tuple will cause a data type mismatch error if the variable type is not a tuple: - -```qsp -number = 4 -number /= [4,5] & ! data type mismatch error -! this way there will be no error, but the variable will contain an empty tuple: -%number /= [4,5] -``` - -::: - -## MOD - -`MOD` — operation calculates the remainder from dividing two numbers. General syntax: - -```qsp -[#expression 1] MOD [#expression 2] -``` - -, where `[#expression 1]` — dividend, `[#expression 2]` — divisor. - -Examples: - -```qsp -! 4 divides by 2 evenly -4 mod 2 & ! returns 0 -! 5 doesn't divide by 2 evenly -5 mod 2 & ! returns 1 -! 13 doesn't divide by 10 evenly -13 mod 10 & ! returns 3 -``` - -The remainder from dividing a negative number will be a negative number. - -## `<` (less than) - -`<` — comparison operation "LESS THAN". General syntax: - -```qsp -[expression_1] < [expression_2] -``` - -If the value of expression `[expression_1]` is less than the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns `0`. In other words: true if the first is less than the second. - -Examples: - -```qsp -! 2 is less than 4 — returns 1 -2 < 4 -! 5 is not less than 5 — returns 0 -5 < 5 -! 7 is not less than 3 — returns 0 -7 < 3 -``` - -You can compare text values: - -```qsp -"a" < "z" & ! true -"z" < "zz" & ! true -"aaaaaa" < "z" & ! true -``` - -And you can compare tuples: - -```qsp -[1, 2, 3] < [1, 2, 9] & ! true -[1, 2, 3] < [2, 2, 3] & ! true -[1, 2] < [1, 2, 3] & ! true -``` - -## `<=` (less than or equal) - -`<=` — comparison operation "LESS THAN OR EQUAL". General syntax: - -```qsp -[expression_1] <= [expression_2] -``` - -If the value of expression `[expression_1]` is less than or equal to the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns `0`. In other words: true if the first is less than the second, or equal to it. - -Examples: - -```qsp -! 2 is less than 4 — returns 1 -2 <= 4 -! 5 equals 5 — returns 1 -5 <= 5 -! 7 is not less than three and not equal to it -7 <= 3 & ! returns 0 -``` - -Analogous to "`=<`" and constructs: - -```qsp -([expression_1] < [expression_2]) or ([expression_1] = [expression_2]) - -no [expression_1] > [expression_2] -``` - -You can also compare text values: - -```qsp -"a" <= "z" & ! true -"z" <= "zz" & ! true -"aaaaaa" <= "z" & ! true -"z" <= "z" & ! true -``` - -And tuples: - -```qsp -[1, 2, 3] <= [1, 2, 9] & ! true -[1, 2, 3] <= [2, 2, 3] & ! true -[1, 2] <= [1, 2, 3] & ! true -[1, 2, 3] <= [1, 2, 3] & ! true -``` - -## `<>` (not equal) - -`<>` — comparison operation "NOT EQUAL". General syntax: - -```qsp -[expression_1] <> [expression_2] -``` - -If the value of expression `[expression_1]` is not equal to the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns `0`. In other words: true if the expressions are not equal. - -Analogous to "`!`", or construct: - -```qsp -no [expression_1] = [expression_2] -``` - -Examples: - -```qsp -! 2 is not equal to 4 — returns 1 -2 <> 4 -! 5 equals 5 — returns 0 -5 <> 5 -``` - -You can compare string values: - -```qsp -"abc" <> "def" & ! returns 1 -"abc" <> "abc" & ! returns 0 -``` - -You can compare tuples: - -```qsp -[1, 2, 3] <> [4, 6, 7] & ! returns 1 -[1, 2, 3] <> [1, 2, 3] & ! returns 0 -``` - -## `=` (equal) - -`=` — comparison operation "EQUAL". General syntax: - -```qsp -[expression_1] = [expression_2] -``` - -If the value of expression `[expression_1]` equals the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns `0`. In other words: true if the expressions are equal. - -Analogous to construct: - -```qsp -no [expression_1] <> [expression_2] -``` - -Examples: - -```qsp -! 2 is not equal to 4 — returns 0 -(2 = 4) -! 5 equals 5 — returns 1 -(5 = 5) -``` - -You can compare string values: - -```qsp -("abc" = "def") & ! returns 0 -("abc" = "abc") & ! returns 1 -``` - -You can compare tuples: - -```qsp -([1, 2, 3] = [4, 6, 7]) & ! returns 0 -([1, 2, 3] = [1, 2, 3]) & ! returns 1 -``` - -:::warning[Attention!] -Don't confuse with the [assignment operation](#-assignment). -::: - -## `=` (assignment) - -`=` — assignment operation. General syntax: - -```qsp -ARRAY_NAME = [value] -``` - -, where `ARRAY_NAME` — variable name (not in quotes) or array name with cell specification (not in quotes), `[value]` — any value or expression. - -Examples: - -```qsp -! assign value 13 to variable BOX -BOX = 13 -! assign value "Text string" to variable $text -$text = "Text string" -! assign value 365 to zero cell of array day -day[0] = 365 -! assign tuple [1, 'unit', 3] to variable tuple: -%tuple = [1, 'unit', 3] -``` - -String variable/array names must start with the `$` symbol. - -Variable/array names containing tuples must start with the `%` symbol. - -:::warning[Attention!] -The assignment operation should not be confused with the "EQUAL TO" comparison operation, although they look very similar: - -```qsp -! assignment operation -alukard = 1000 -! comparison operation -(alukard = 1000) -``` - -In this case, the player understands that inside the brackets is a comparison operation because brackets are used for writing expressions. The notation: - -```qsp -"abc" = "abc" -``` - -is syntactically incorrect. The player will give an error: invalid variable/array name. Since in this case it doesn't understand that this is a comparison operation. - -If an operator explicitly precedes the comparison operation, brackets can be omitted: - -```qsp -if alukard = 150: *pl "Not enough strength" -*pl "abc" = "abc" -``` - -::: - -### Multiple Assignment - -Multiple assignment allows assigning values to several variables or array cells with one `=` command. General syntax: - -```qsp -ARRAY_NAME_1, ARRAY_NAME_2, ... , ARRAY_NAME_N = [VALUE_1], [VALUE_2], ... , [VALUE_N] -``` - -, where variable names (or array names with cell index specification in square brackets) are written to the left of the `=` sign, and values to be assigned to variables or array cells are listed to the right of the `=` sign. - -:::warning[Important to remember!] -There must be as many variables to the left of the equals sign as there are values to the right. The number of variables and the number of assigned values must match. - -This rule is not followed when unpacking tuples. -::: - -Examples: - -```qsp -apples_in_pocket, apples_in_basket, apples_at_lyoshka = 58, 11, 19 -$string_1, $string_2 = 'Grekha rode across the river', 'Grekha sees a crab in the river' -$name, count = 'Old sword', 2 -``` - -Instead of directly specifying values, you can assign values of other variables, expressions, functions: - -```qsp -! three variables = three values -red, green, blue = rand(0,255), rand(0,255), rand(0,255) -! two variables = two values -apples_in_pocket, apples_in_basket = apples_at_lyoshka, apples_on_tree+15 -``` - -Thanks to the ability to simultaneously assign values to several variables, you can swap data in two variables without using a third: - -```qsp -! assign variables x and y values 12 and 99 -x, y = 12, 99 -! swap values. Now x contains number 99, and y — 12 -x, y = y, x -``` - -### Tuple Unpacking - -Since tuples contain several values at once, the notation for assigning values to variables from tuples can differ from the usual: - -```qsp -! %unit = [187, 94, 'steel', [0, 2]] -height, weight, $material, %coordinates = %unit -``` - -As you can see, here we have four variable names on the left, but only one tuple variable name on the right. Such assignment is called unpacking — values are extracted from the tuple and placed in the specified variables. - -A tuple not placed in a variable is unpacked the same way: - -```qsp -height, weight, $material, %coordinates = [187, 94, 'steel', [0, 2]] -``` - -Such notation differs little from multiple assignment, so external square brackets are not required: - -```qsp -height, weight, $material, %coordinates = 187, 94, 'steel', [0, 2] -``` - -It should be emphasized that **multiple assignment is essentially tuple unpacking**. - -Since if there are more variables to the left of the equals sign than values in the tuple, default values for those variables will be written to the "extra" variables, the same will happen with multiple assignment. - -```qsp -r, g, b, a = [255, 188, 19] -! r = 255, g = 188, b = 19, a = 0 -raz, dva, tri, chetyre = 137, 61 -! raz = 137, dva = 61, tri = 0, chetyre = 0 -``` - -At the same time, if there are fewer variables to the left of the equals sign than values to the right in multiple assignment, this will cause a data type mismatch error: - -```qsp title="Data type mismatch" -coords = 23, 34 -age, weight, material = 27, 94, 'steel', 'biorobot' -``` - -If the type of the last listed variable is a tuple, such assignment won't cause an error: - -```qsp -age, weight, %type = 27, 94, 'steel', 'biorobot' -! age = 27, weight = 94, %type = ['steel', 'biorobot'] -``` - -## `=<` (equal or less) - -:::warning[Attention!] -This notation, although acceptable in QSP, is not recommended for use. Use "`<=` (less than or equal)" instead. -::: - -`=<` — comparison operation "EQUAL OR LESS". General syntax: - -```qsp -[expression_1] =< [expression_2] -``` - -If the value of expression `[expression_1]` is less than or equal to the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns 0. In other words: true if the first is less than the second, or equal to it. - -Examples: - -```qsp -! 2 is less than 4 — returns 1 -2 =< 4 -! 5 equals 5 — returns 1 -5 =< 5 -! 7 is not less than three and not equal to it -7 =< 3 & ! returns 0 -``` - -Analogous to "`<=`" and constructs: - -```qsp -([expression_1] < [expression_2]) or ([expression_1] = [expression_2]) - -no [expression_1] > [expression_2] -``` - -## `=>` (equal or greater) - -:::warning[Attention!] -This notation, although acceptable in QSP, is not recommended for use. Use "`>=` (greater than or equal)" instead. -::: - -`=>` — comparison operation "EQUAL OR GREATER". General syntax: - -```qsp -[expression_1] => [expression_2] -``` - -If the value of expression `[expression_1]` is greater than or equal to the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns 0. In other words: true if the first is greater than the second, or equal to it. - -Examples: - -```qsp -! 2 is not greater than and not equal to 4 — returns 0 -2 => 4 -! 5 equals 5 — returns 1 -5 => 5 -! 7 is greater than 3 -7 => 3 & ! returns 1 -``` - -Analogous to "`>=`" and constructs: - -```qsp -([expression_1] > [expression_2]) or ([expression_1] = [expression_2]) -no [expression_1] < [expression_2] -``` - -## `>` (greater than) - -`>` — comparison operation "GREATER THAN". General syntax: - -```qsp -[expression_1] > [expression_2] -``` - -If the value of expression `[expression_1]` is greater than the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns `0`. In other words: true if the first is greater than the second. - -Examples: - -```qsp -! 2 is not greater than 4 — returns 0 -2 > 4 -! 5 is not greater than 5 — returns 0 -5 > 5 -! 7 is greater than 3 — returns 1 -7 > 3 -``` - -You can compare text values, where characters are compared sequentially, and the character closer to the end of the alphabet is considered greater. - -```qsp -"z" > "a" & ! true -"zz" > "z" & ! true -"z" > "aaaaaa" & ! true -``` - -And you can compare tuples: - -```qsp -[1, 2, 9] > [1, 2, 3] & ! true -[1, 2, 3] > [2, 2, 3] & ! false -[1, 2, 3] > [1, 2] & ! true -``` - -## `>=` (greater than or equal) - -`>=` — comparison operation "GREATER THAN OR EQUAL". General syntax: - -```qsp -[expression_1] >= [expression_2] -``` - -If the value of expression `[expression_1]` is greater than or equal to the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns 0. In other words: true if the first is greater than the second, or equal to it. - -Examples: - -```qsp -! 2 is not greater than and not equal to 4 — returns 0 -2 >= 4 -! 5 equals 5 — returns 1 -5 >= 5 -! 7 is greater than 3 -7 >= 3 & ! returns 1 -``` - -Analogous to "`=>`" and constructs: - -```qsp -([expression_1] > [expression_2]) or ([expression_1] = [expression_2]) -no [expression_1] < [expression_2] -``` - -You can compare text values, where characters are compared sequentially, and the character closer to the end of the alphabet is considered greater. - -```qsp -"z" >= "a" & ! true -"zz" >= "z" & ! true -"z" >= "aaaaaa" & ! true -"z" >= "z" & ! true -``` - -And tuples: - -```qsp -[1, 2, 9] >= [1, 2, 3] & ! true -[1, 2, 3] >= [2, 2, 3] & ! false -[1, 2] >= [1, 2, 3] & ! false -[1, 2, 3] >= [1, 2, 3] & ! true -``` - -## `!` (not equal) - -:::warning[Attention!] -Don't confuse with the comment operator. - -For better code readability, we recommend using `<>`. -::: - -`!` — comparison operation "NOT EQUAL". General syntax: - -```qsp -[expression_1]![expression_2] -``` - -If the value of expression `[expression_1]` is not equal to the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns `0`. In other words: true if the expressions are not equal. - -Analogous to "`<>`", or construct: - -```qsp -no [expression_1] = [expression_2] -``` - -Examples: - -```qsp -! 2 is not equal to 4 — returns 1 -2 ! 4 -! 5 equals 5 — returns 0 -5 ! 5 -``` - -## `&` (concatenation) - -`&` — concatenation, operation for combining string expressions or tuples. General syntax: - -```qsp -([$expression 1] & [$expression 2]) -([%expression 1] & [%expression 2]) -``` - -:::warning[Attention!] -Concatenation must always be enclosed in brackets! -::: - -If you try to combine numeric values, they will be converted to strings, and then the strings will be combined. - -Examples: - -```qsp -*pl ('hello, ' & 'World!') -! we'll see the string 'hello, World!' on screen -*pl ([1, 2, 3] & [4, 5, 6]) -! we'll see the tuple [1, 2, 3, 4, 5, 6] on screen -``` - -:::warning[Attention!] -Don't confuse with the command enumeration symbol: - -```qsp -! in this case, strings "26" and "27" will be -! output to screen sequentially -"26" & "27" -! and here the string "2627" will be output to screen -("26" & "27") -``` - -::: - -:::tip -It's not recommended to use this operation for combining strings, since strings can be combined through [`+`](qsp-keyword-operacion.md#-addition): - -```qsp -! the string "2627" will be output to screen -"26"+"27" -``` - -Such notation creates less confusion when reading code and works similarly. - -You can't join two tuples into one using the `+` operation: - -```qsp -[2, 5] + [3, 7] -! the tuple [[5,9],[8,12]] will be on screen -``` - -::: - -## AND - -`AND` — logical "AND". General syntax: - -```qsp -[#expression 1] AND [#expression 2] -``` - -The entire expression will be true if both `[#expression 1]` and `[#expression 2]` are true. - -Examples: - -```qsp -! both parts of expression are true, so entire expression is true -(2 = 2) and (3 <> 2) & ! expression returns 1 (true) -! one part of expression is not true, so entire expression is false -(2 <> 2) and (3 <> 2) & ! expression returns 0 (false) -! both parts of expression are not true, so entire expression is not true -(2 <> 2) and (3 = 2) & ! expression returns 0 (false) -``` - -:::note[5.7.0] -In older player versions, the operation was bitwise. -::: - -## LOC - -`LOC` — operation checks for location existence and returns `1` if location exists, and `0` if location doesn't exist. General syntax: - -```qsp -LOC([$location]) -``` - -, where `[$location]` — location name whose existence needs to be checked in the game. Expression is true if location exists in the game. - -Examples: - -```qsp -! checks if location "start" exists in game -loc("start") & ! if location exists, returns 1 - -! if location "street" is not added to game -if loc("street") = 0: - act "Go outside": *pl "I can't go outside, the door won't open." -end -``` - -## NO - -`NO` — negation operation. General syntax: - -```qsp -NO [#expression] -``` - -If `[#expression]` is true, then the entire expression is false, and vice versa. In other words, returns `0` if the expression value is not zero, and returns `1` if the expression value equals `0`. - -Example: - -```qsp -! 4 equals 4 is true, so entire expression is false -no (4 = 4) & ! returns 0 (false) -! can be read as question: four does not equal four? No — false. - -! that 5 equals 3 is false, so entire expression is true -no (5 = 3) & ! returns 1 (true) -! can be read as question: five does not equal three? Yes — true. -``` - -:::note[5.7.0] -In older player versions, the operation was bitwise. -::: - -## OBJ - -`OBJ` — operation checks for item presence in inventory and returns `1` if item exists, and `0` if item doesn't exist. General syntax: - -```qsp -OBJ([$name]) -``` - -, where `[$name]` — item name whose presence needs to be checked in the objects window. Expression is true if item is added to the objects window. - -Examples: - -```qsp -! checks if "Screwdriver" item is added to objects window -obj("Screwdriver") & ! if item exists, returns 1 - -! depending on presence of this or that item -! this or that action is output -if obj("Full jug") = 1: - act "Empty jug": - delobj "Full jug" - addobj "Empty jug" - goto $curloc - end -elseif obj("Empty jug") = 1: - act "Fill jug": - addobj "Full jug" - delobj "Empty jug" - goto $curloc - end -end -``` - -## OR - -`OR` — logical "OR". General syntax: - -```qsp -[#expression 1] OR [#expression 2] -``` - -The entire expression will be true if at least one of expressions `[#expression 1]` and `[#expression 2]` is true. - -Examples: - -```qsp -! both parts of expression are true, so entire expression is true -(2 = 2) or (3 <> 2) & ! expression returns 1 (true) -! one part of expression is true, so entire expression is true -(2 <> 2) or (3 <> 2) & ! expression returns 1 (true) -! both parts of expression are not true, so entire expression is not true -(2 <> 2) or (3 = 2) & ! expression returns 0 (false) -``` - -:::note[5.7.0] -In older player versions, the operation was bitwise. -::: diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md index ff1c8a8..78a03d8 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md @@ -1,2033 +1,1261 @@ --- -sidebar_position: 2 +sidebar_position: 1 --- -# Operators +# Operators of operations -## Implicit operator +List of operators for player version 5.8.0 in ascending order of priority: -The implicit operator is an operator that is not written in QSP code but outputs values to the screen. It is implied wherever an expression without an operator is present in a command. The implicit operator outputs values to the **Main Description Window** in the same way as if you used explicit specification of the `*pl` operator, i.e., it outputs the value and makes a line break. Examples: +- `OR` +- `AND` +- `NO` +- `=`, `<`, `>`, `!`, `<>`, `<=`, `>=`, `=<`, `=>` (comparison operations) +- `OBJ`, `LOC` +- `&` (concatenation) +- `+`, `-` (addition, subtraction) +- `MOD` +- `*`, `/` (multiplication, division) +- `-` (unary minus) +- `([expr])` - expressions in brackets -```qsp -$AAA + '989' -'You are in the park' -'Preformatted - - string' -$curloc & ! will output the location name to the screen -``` - -Unlike the `*pl` operator, the implicit operator does not output an empty line with a line break to the screen if no value is passed to it. This means that if a function returns no value, the implicit operator is simply ignored. Example: - -```qsp -# start -! this is the code of a location calling a location-function -$curloc -$func('foo') -$func('foo') -$curloc -- start - -# foo -! this is the code of the location-function -local i = 0 -- foo -``` - -In this case, the location-function `foo` returns nothing, so we will see two lines with the word "start" on the screen, with no empty lines between them, since the implicit operator in the lines with `$func` at location `start` will be simply ignored. Compare with: +Operations written on one line have equal priority and are executed in order from left to right if present at the same level in an expression. -```qsp -# start -! this is the code of a location calling a location-function -*pl $curloc -*pl $func('foo') -*pl $func('foo') -*pl $curloc -- start +Operations in brackets have priority over other operations. -# foo -! this is the code of the location-function -local i=0 -- foo -``` +Function value calculation has priority over all operations. -## `!` (comment) +A numeric expression whose value is not `0` is considered true. When the value is `0`, the expression is considered false. For the "true" value, it's strongly recommended to use `1` for compatibility with logical operations and functions returning logical values. -`!` — comment operator. What is in the line after the comment operator and until the end of the line is ignored by the interpreter. The comment operator allows you to "comment out" (disable) an unnecessary operator/function temporarily during game debugging. In addition, writing comments to program code is one of the signs of good programming style. - -It is necessary to clearly understand that this is an operator, so if you are commenting some line of code, then `!` should come after `&`: - -```qsp -*pl "Hello, world!" & ! comment -``` - -Comments can be single-line, i.e., end on the same line where the comment operator is located: - -```qsp -! single-line comment -*pl "text string" & ! also a single-line comment -``` - -:::tip[Exception] -The only exception to this rule is writing a comment after a colon in multi-line operators: +:::note[5.7.0] +In older player versions, the priority order was different. + +- `&` +- `OR` +- `AND` +- `OBJ`, `LOC`, `NO` +- `=`, `<`, `>`, `!`, `<>`, `<=`, `>=`, `=<`, `=>` +- `+`, `-` +- `MOD` +- `*`, `/` +- `+`, `-` (unary) -```qsp -act "Multi-line action": ! comment - *pl "Text on screen" -end -``` +::: +**Some features of comparison operations:** + +- Comparison operations return `1` (true) or `0` (false) depending on the comparison result. +- When comparing numbers, everything is simple: + - of two positive numbers, the positive number with greater magnitude will be considered greater; + - a negative number is always less than a non-negative (positive and zero); + - a positive number is always greater than a non-positive (negative and zero); + - of two negative numbers, the negative number with greater magnitude will be considered smaller. +- When comparing strings, character-by-character comparison occurs from left to right: + - the character that comes later in the character table is considered greater. You can rely on alphabetical sequence of characters to understand which string will be greater. Then character '`z`' will be greater than character '`a`'. Examples: + + ```qsp + 'z' > 'a' & ! returns 1 + 'z' > 'az' & ! returns 1 + 'akz' > 'akk' & ! returns 1 + ``` + + - when comparing any non-empty string with an empty string, the empty string will be considered smaller: + + ```qsp + ' ' > '' & ! returns 1 + 'a' > '' & ! returns 1 + 'z' > '' & ! returns 1 + 'akzakz' > 'akzak' & ! returns 1 + ``` + + :::tip[You can consider] + that missing characters in a string are empty characters (empty strings), which when compared with any other character turn out to be smaller. + ::: + + - when comparing a string with a number, the player will try to convert both values to numbers. If successful, numbers will be compared. If unsuccessful — the number will be converted to a string, and strings will be compared. + + ```qsp + 'zzz' > 123 & ! returns 1 + '123' > 92 & ! returns 1 + '123' > '92' & ! returns 0 + ``` + +- When comparing tuples, element-by-element comparison occurs from left to right: + - the tuple whose element turned out to be greater will be considered greater: + + ```qsp + [1, 2, 3] > [1, 2, 2] & ! returns 1 + [2, 2, 3] > [1, 2, 3] & ! returns 1 + ``` + + - when comparing any non-empty tuple with an empty tuple, the empty tuple will be considered smaller: + + ```qsp + [1] > [] & ! returns 1 + [''] > [] & ! returns 1 + [0] > [] & ! returns 1 + [1, 2] > [1] & ! returns 1 + [1, 2] < [9] & ! returns 1 + ``` + + :::tip[You can consider] + that missing elements in a tuple are empty elements, which when compared with any other element turn out to be smaller. + ::: + + - when comparing tuples with numbers or strings, the number or string will be compared as a tuple of one element. For easier understanding, you can consider that the number or string is converted to a tuple when compared: + + ```qsp + [8] < 9 & ! returns 1 + [9, 8] > 9 & ! returns 1 + [0, 0] > 9 & ! returns 0 + + [8, 9] > '8,9' & ! returns 0 + ['a', 'z'] < 'az' & ! returns 1 + ['a', 'z'] > 'a' & ! returns 1 + (['az'] = "az") & ! returns 1 + ``` + +:::warning[We recommend:] +Not to compare values of different types to avoid confusion. ::: -Comments can be multi-line. For this, after the comment operator, you need to write quotes, apostrophes, or curly braces. For example: +## `*` (multiplication) -```qsp -! "this is the first line of the comment - this is the second line of the comment - this is the third line of the comment -" -``` - -Multi-line comments can take various forms: +`*` — arithmetic operation "MULTIPLICATION". Multiplies two numbers. General syntax: ```qsp -! line before quotes " text inside quotes -can move to other lines " as well as { -you can use other character groups to -continue the multi-line comment -} and the comment won't end until the line ends +[#expression 1] * [#expression 2] ``` -## `*CLEAR` - -`*CLEAR` — clears the main description window. Has a short form `*clr`. - -## `*NL` - -`*NL` — line break, then text output in the main description window. General syntax: - -```qsp -*NL [$text] -``` +, where `[#expression 1]` and `[#expression 2]` — any two numeric values or expressions. The operation result is the product of two numbers. -where `[$text]` is any text string, number, or expression of any type. If `[$text]` is absent, a simple line break occurs. Example: +Examples: ```qsp -*p "Text without line break." -*nl "Line break + text output." -*p "Text without line break." +2 * 2 & ! returns 4 +4 * 2 & ! returns 8 +17 * 5 & ! returns 85 +37 * 100 & ! returns 3700 ``` -## `*P` - -`*P` — text output to the main description window without line break. Text output by any other operator immediately after `*p` will add new text immediately after the current text. General syntax: +Can be used with tuples whose values are numbers and/or other tuples containing numbers. General syntax: ```qsp -*P [$text] +[%tuple] * [#number] ``` -where `[$text]` is any text string, number, or expression of any type. `[$text]` can be an empty string `''`, but should not be absent. Example: +In this case, each tuple element will be multiplied by the specified number. Examples: ```qsp -*p "Text without line break." -*p "Text without line break." -*p "" -*p "Text without line break." -``` +%tuple = [4, 10, 16] +%a = %tuple * 2 +! %a will equal [8, 20, 32] -## `*PL` - -`*PL` — text output to the main description window, then line break. General syntax: - -```qsp -*PL [$text] +[4, 10] * 'b' & ! data type mismatch error ``` -where `[$text]` is any text string, number, or expression of any type. `[$text]` can be absent, then just a line break. Example: +Note the last example. A data type mismatch error occurs because it's impossible to apply multiplication to a string value. The same error will occur if the tuple contains string values. However, you can multiply tuples containing only numeric values: ```qsp -*pl "Text output, then line break." -*pl "Text output, then line break." -*p "Text without line break." -*pl "Text output, then line break." +*pl [2, 3] * [4, 5] +! [2 * [4,5], 3 * [4,5]] +! [[8,10],[12,15]] ``` -You can output text in the same way by simply writing the needed expression instead of this operator. For example, the lines: +In this case, each element of the first tuple is multiplied by the second tuple. This gives us a new tuple of two tuples as a result. -```qsp -*pl $AAA + '989' -*pl 'You are in the park' -*pl 'Preformatted - - string' -``` +## `*=` (multiplication-assignment) -and: +`*=` — "MULTIPLICATION-ASSIGNMENT" operation. Combines assignment and multiplication operations. Multiplies the specified variable value by a certain number and returns the result to the same variable. General syntax: ```qsp -$AAA + '989' -'You are in the park' -'Preformatted - - string' +ARRAY_NAME *= [#expression 1] ``` -will work identically. +, where `ARRAY_NAME` — variable name (without quotes) or array name with cell specification, and `[#expression 1]` — any numeric value or expression. -## ACT - -`ACT` — creates and outputs a new action to the actions window. - -General syntax in single-line form: +Analogous to: ```qsp -ACT [$name], [$path to image file]: [operator] & [operator] & [operator] +ARRAY_NAME = ARRAY_NAME*[#expression 1] ``` -General syntax in multi-line form: - -```qsp -ACT [$name], [$path to image file]: - [operator] - [operator] - [operator] -END -``` - -A new action with name `[$name]` and image located at `[$path to image file]` is added to the actions list in the actions window. When the action is clicked, the specified operators are executed. - -The `[$path to image file]` parameter can be absent, in which case the action is added without an image. - -Examples: +Example: ```qsp -! action in single-line form -act "Pick apple from birch": apple += 1 & *pl "You picked a ripe white apple." - -! action in multi-line form, with image -act "Pick watermelon from bush", "img/watermelon.png": - watermelon += 1 - *pl "You picked a watermelon from the bush" -end +! we replace two operations: assignment and multiplication +warrior = warrior * 2 +! with multiplication-assignment (identical action) +warrior *= 2 ``` -If there is already an action with the specified name in the actions list, no new action is created, and it does not replace the existing one, the player simply ignores the `act` command. Thus, you cannot output actions with identical names. Example: +If the `ARRAY_NAME` variable value is a tuple, each tuple element will be multiplied by the specified number, and the resulting tuple will be assigned to the variable. Example: ```qsp -act "Action 1": *pl "Old action." -act "Action 1": *pl "New action." +%tuple = [4, 10, 16] +%tuple *= 2 +! %tuple will equal [8, 20, 32] ``` -However, you can simulate actions with identical names in HTML recognition mode by adding HTML tags to action names: +You cannot multiply by a string type value; this will lead to a data type mismatch error. Also, tuple values (and all nested tuples) should not contain string values when performing this operation. However, you can perform multiplication-assignment with another tuple: ```qsp -usehtml = 1 -act 'Action 1': *pl "Old action." -act 'Action 1': *pl "New action." +%tuple = [2, 3] +%tuple *= [4, 5] +! %tuple will equal [[8,10],[12,15]] ``` -## ADDOBJ - -`ADDOBJ` — adding a new object to the objects window. General syntax: +:::warning[Note] +Multiplication-assignment with a tuple will cause a data type mismatch error if the variable type is not a tuple: ```qsp -ADDOBJ [$name], [$path to image file], [#position] -``` - -where `[$name]` is the object name, `[$path to image file]` is the path to the object's image file (displayed next to the object name), and `[#position]` is the position in the inventory where the object is added. The `[#position]` parameter can be absent. By default, objects are added to the end of the list. Object numbering in the inventory starts from `1`. The `[$path to image file]` parameter can be absent, default value is `''`, in which case the object is added without an image. - -:::note[Allowed but not recommended, deprecated form:] - -```qsp -ADD OBJ [$name],[$path to image file],[#index] +number = 4 +number *= [4,5] & ! data type mismatch error +! this way there will be no error, but the variable will contain an empty tuple: +%number *= [4,5] ``` ::: -You can add objects with the same name, but if you plan to add many identical objects, it's better to use an additional variable to count these objects and add one object to the objects window to avoid cluttering the inventory with a list of 137 Ruble / Cartridge objects: - -```qsp -if obj('Cartridges'): -! if object "Cartridges" is already added, just increase their number - cartridges += 10 -else -! if object "Cartridges" is not yet added, add it and increase the number - addobj 'Cartridges' - cartridges += 10 -end -``` - -You can use arrays indexed by strings to store object counts: - -```qsp -objects['money'] = 12 -objects['cartridges'] = 137 -'Quantity: <>' -``` - -Example of adding an object to the very top of the list (all other objects will shift down): - -```qsp -addobj "Screwdriver", "", 1 -``` - -## CLA - -`CLA` - clearing the list of current actions (removing all actions from the actions window). - -## CLEAR - -`CLEAR` — clears the additional description window. Has a short form `clr`. - -## CLOSE +## `+` (addition) -`CLOSE` — stops playing the specified sound file. General syntax: +`+` — arithmetic operation "ADDITION". Adds two numbers. General syntax: ```qsp -CLOSE [$path to sound file] +[expression 1]+[expression 2] ``` -where `[$path to sound file]` is the path to the sound file relative to the game file. If the `[$path to sound file]` parameter is not specified, all sound files stop playing. - -## CLOSE ALL - -`CLOSE ALL` — stops playing all active sound files. Has a short form `close`. - -## CLS - -`CLS` — clears all windows except the objects list. Equivalent to the construction: - -```qsp -clear & *clear & cla & cmdclear -``` - -## CMDCLEAR - -`CMDCLEAR` — clearing the input line. Has a short form `cmdclr`. - -## COPYARR - -`COPYARR` — copying the contents of one array to another. General syntax: - -```qsp -COPYARR [$receiver], [$source], [#start], [#count] -``` - -where: `[$receiver]` is the array to which copying is performed, size and content don't matter; `[$source]` is the array from which copying is performed; `[#start]` is the element number from which to start copying; `[#count]` is how many elements to copy. The `[#count]` parameter is optional; by default — until the end of the source array. The `[#start]` parameter is optional; by default — 0. +, where `[expression 1]` and `[expression 2]` — any two values or expressions. The operation result is the sum of two values. Examples: ```qsp -! copy all elements of array '$b' to array '$a' -copyarr '$a', '$b' -! at the same time, all elements of array 'b' were also copied to array 'a' - -! copy elements of array 'd' starting from the sixth to array 'c' -copyarr 'c', 'd', 6 - -! copy the first six elements of array 'd' to array 'c' -copyarr 'c', 'd', 0, 6 +2+2 & ! returns 4 +4+2 & ! returns 6 +17+5 & ! returns 22 +37+100 & ! returns 137 ``` -Due to player peculiarities, when copying, for example, numeric array `mass1` to `mass2`, text array `$mass1` is also copied to `$mass2`. - -Other examples: +When "adding" string values, [concatenation](qsp-keywords-operators.md#-concatenation) is performed, i.e., "gluing" strings together: ```qsp -copyarr $arrname1, $arrname2, 10, 5 -copyarr 'a<<$arrname1>>', 'a<<$arrname2>>' +! the string "2627" will be output to screen +"26"+"27" ``` -## DELACT - -`DELACT` — removes an action from the actions list (if such action exists). General syntax: +If values are "added" to a tuple, each tuple element is summed with the specified value: ```qsp -DELACT [$name] +%tuple = [4, 10, 16] +%a = %tuple + 2 +! %a will equal [6, 12, 18] ``` -where `[$name]` is the name of the action we want to remove. - -Examples: - -```qsp -! remove action with specific name -delact 'Go forward' -! remove selected action -delact $selact -``` - -:::note[Allowed but not recommended, deprecated form:] +If two tuples are added, the second tuple is added to the values of each element of the first tuple: ```qsp -DEL ACT [$name] +[4, 10] + ['b', 'x'] +! [4 + ['b', 'x'], 10 + ['b', 'x']] +! [['4b','4x'], ['10b','10x']] ``` -::: - -## DELOBJ +## `+=` (addition-assignment) -`DELOBJ` — removing an object from inventory by name (if such object exists). General syntax: +`+=`, `(increment)` — "INCREMENT" operation, combining assignment and addition operations. Adds the specified value to the current variable value. General syntax: ```qsp -DELOBJ [$name] +ARRAY_NAME += [expression 1] ``` -where `[$name]` is the name of the object we want to remove. - -If there are identical objects in the inventory, the command will remove the topmost one with the specified index. +, where `ARRAY_NAME` — variable name (without quotes) or array name with cell specification, and `[expression 1]` — any value or expression. -Examples: +Analogous to: ```qsp -! remove object with specific name -delobj "Screwdriver" -! remove selected object -delobj $selobj +ARRAY_NAME = ARRAY_NAME + [expression 1] ``` -:::note[Allowed but not recommended, deprecated form:] +Example: ```qsp -DEL OBJ [$name] +! we replace two operations: assignment and addition +warrior = warrior + 15 +! with increment (identical action) +warrior += 15 ``` -::: - -## DYNAMIC - -`DYNAMIC` — executes code passed as a text string. General syntax: +It's also possible to perform increment with string values, works like [concatenation](qsp-keywords-operators.md#-concatenation): ```qsp - DYNAMIC([$code], [argument 0], [argument 1], ... , [argument 18]) +$text += " (maybe something is written here)" ``` -where `[$code]` is regular QSP code written as text. Execution of such code is similar to executing `GOSUB` operator code. Arguments `[argument 0]`, `[argument 1]`, etc. can be used inside `[$code]`, their values are automatically placed in variables `args[0]`, `args[1]`, etc. respectively. After execution, old `args` parameters are restored, then code execution continues from the next command after `dynamic`. - -Examples: +If the `ARRAY_NAME` variable value is a tuple, each tuple element will be summed with the specified value, and the resulting tuple will be assigned to the variable. Example: ```qsp -dynamic '$a = "string<<$b>>"' -dynamic '$a' -dynamic 'if $a = "string": "text!"' -dynamic " - $args[0] - addobj $args[1] -", 'Text', 'Fork' +%tuple = [4, 10, 16] +%tuple += 2 +! %tuple will equal [6, 12, 18] ``` -The following information is also true for the [`dyneval`](qsp-keyword-functions.md#dyneval) function. - -**Important!** If code is specified using apostrophes (`''`) or quotes (`""`), sub-expressions are evaluated in the text: +You can perform addition-assignment with another tuple: ```qsp -$args[0] = 'qwerty' -$code = ' - *pl "<<$args[0]>>" - *pl $args[0] -' - -dynamic $code, 'asdfg' +%tuple = [2, 3] +%tuple += [4, 5] +! %tuple will equal [[6,7],[7,8]] ``` -In this case, when setting the `$code` variable, the sub-expression will be evaluated, so the first line will output 'qwerty', the second line will output 'asdfg'. - -Curly braces are the third type of quotes used specifically for writing dynamic code. Here, bracket nesting is supported, and sub-expressions are not evaluated before code execution: +:::warning[Note] +Addition-assignment with a tuple will cause a data type mismatch error if the variable type is not a tuple: ```qsp -$args[0]='qwerty' -$code = { - *pl "<<$args[0]>>" - *pl $args[0] -} - -dynamic $code, 'asdfg' +number = 4 +number += [4,5] & ! data type mismatch error +! this way there will be no error, but the variable will contain an empty tuple: +%number += [4,5] ``` -In this case, two lines 'asdfg' will be output. - -## EXIT - -`EXIT` — termination of the current code block execution (premature exit from subroutine, function, event handler, etc.). - -A code block can be a location, action, code passed to `dynamic` or `dyneval`, or code in a hyperlink. - -Example: - -```qsp -if args[1] = 0: - exit -else - if args[0] mod args[1] = 0: - result = 1 - else - result = 0 - end -end -``` - -:::warning[Attention!!!] -In players version 5.8.0, the `loop` operator appeared. - -The loop body is also considered a separate code block, but the `exit` operator interrupts not only the loop itself, but also the code block in which the loop is located. ::: -## FREELIB - -`FREELIB` — removes all locations added with the `inclib` operator. - -:::note[5.7.0] -In older player versions, the command was called `dellib` and `killqst`. +:::tip[Note] +Increment — in many programming languages this is an operation that performs variable increase. Most often, increment means increasing a variable by `1`. ::: -## GOSUB - -`GOSUB` — executing code of the specified location without directly going to it. +## `-` (subtraction) -General syntax: +`-` — arithmetic operation "SUBTRACTION". Subtracts one number from another. General syntax: ```qsp -GOSUB [$location],[argument 0],[argument 1], ... ,[argument 8] +[#expression 1] - [#expression 2] ``` -where `[$location]` is the name of the location whose code we want to execute without directly going to it. Arguments `[argument 0]`, `[argument 1]`, etc. can be used on this location, their values are automatically placed in variables `args[0]`, `args[1]`, etc. respectively. After processing the location, previous `args` values are restored. Using arguments is not mandatory. - -When accessing a location via `gosub`, the base description of the location is added to the current description, base actions are added to current actions, and operators in the "Execute on visit" field are executed, then return to the original line (continuing code execution after `gosub`). - -Examples of calling locations via `gosub`: - -```qsp -!processing location "move". The args[] array is empty. -gosub 'move' - -!processing location with name from variable $location -!One parameter is passed - args[0] equals 1. -gosub $location,1 - -!processing location "move" with passing 3 parameters. -! $args[0] = $var (value), args[1] = 2, -! $args[2] = "data". Note the '$' symbols. -gosub 'move',$var,2,'data' -``` - -Another example: - -```qsp -! this is the code for calling location "transition" -gosub 'transition', 'location' - -! and this is the code of the location "transition" itself -# transition -*pl $args[0] & ! the text 'location' will be output to the screen -! a new action will appear in the actions window: -act 'go': - goto "street" -end -- transition -``` +, where `[#expression 1]` and `[#expression 2]` — two numeric values or expressions. The operation result is the difference of two values. -The operator has a short form `gs`: +Examples: ```qsp -GS [$location], [argument 0], [argument 1], ... , [argument 18] +2 - 2 & ! returns 0 +4 - 2 & ! returns 2 +17 - 5 & ! returns 12 +37 - 100 & ! returns -63 ``` -## GOTO - -`GOTO` — transition to the specified location. General syntax: +Can be used with tuples whose values are numbers and/or other tuples containing numbers. General syntax: ```qsp -GOTO [$location], [argument 0], [argument 1], ... , [argument 18] +[%tuple] - [#number] ``` -where `[$location]` is the name of the location to which the transition should be made. Arguments `[argument 0]`, `[argument 1]`, etc. can be used on this location, their values are automatically placed in variables `args[0]`, `args[1]`, etc. respectively. Using arguments is not mandatory. - -When transitioning to a new location using `goto`, the main description window is cleared, as well as the list of current actions, then the base description text is output to the main description window, base actions to the actions window, and code from the "Execute on visit" field of location `[$location]` is executed. Also, when transitioning to a new location, the value returned by the `$curloc` function changes. - -Examples: +In this case, the specified number will be subtracted from each tuple element. Examples: ```qsp -! transition to location "house". -! The args array at location "house" will be empty. -goto 'house' +%tuple = [4, 10, 16] +%a = %tuple - 2 +! %a will equal [2, 8, 14] -! transition to location "street" with passing 2 parameters. -! at location "street" args[0] equals 1, -! $args[1] contains string "data". -goto 'street',1,'data' +[4, 10] - 'b' & ! data type mismatch error ``` -The operator has a short form `gt`: +Note the last example. A data type mismatch error occurs because it's impossible to apply subtraction to a string value. The same error will occur if the tuple contains string values. However, you can subtract one tuple from another if both tuples contain only numeric values: ```qsp -GT [$location],[argument 0],[argument 1], ... ,[argument 8] +*pl [2, 3] - [4, 5] +! [2 - [4,5], 3 - [4,5]] +! [2 + ([4,5] * -1), 3 + ([4,5] * -1)] +! [[-4, -5] + 2, [-4,-5] + 3] +! [[-2,-3],[-1,-2]] ``` -## IF +In this case, the second tuple is subtracted from each element of the first tuple. If you sequentially expand brackets and perform all necessary mathematical operations, you get a new tuple containing other tuples with results. -`IF` — the main operator for writing conditional constructions. Constructions written using this operator (let's call them "simple conditions") have two forms: single-line and multi-line, and generally look like this: +## `-=` (subtraction-assignment) -General form: +**`-=`, `(decrement)`** — "DECREMENT" operation, combining assignment and subtraction operations. Subtracts the specified value from the current variable value. General syntax: ```qsp -! single-line form -IF [#expression]: {command 1} & {command 2} & ... - -! multi-line form -IF [#expression]: - {command 1} - {command 2} - ... -END +ARRAY_NAME -= [#expression 1] ``` -In this case, if condition `[#expression]` is true, commands `{command 1}`, `{command 2}`, etc. are executed. - -- For **single-line form**, these will be only those commands that are on the same line as the `IF` operator until the end of the line; -- and for **multi-line form**, these will be those commands that are in subsequent lines after the colon and until the special keyword `END`. - -Comparison operations, logical operations, and other expressions returning numeric values can serve as conditions. +, where `ARRAY_NAME` — variable name (without quotes) or array name with cell specification, and `[#expression 1]` — any numeric value or expression. -The `END` keyword in multi-line form must be on a separate line. - -If condition `[#expression]` is not true, commands will not be executed. - -Examples of single-line conditional forms: +Analogous to: ```qsp -! if the sum of a and b equals two, -! variable c is assigned value 30 -if a + b = 2: c = 30 -! If there's no orange in inventory, text is output -if no obj("Orange"): pl "You don't have an orange." -! this is also a simple single-line form -if ((a+b)/c)=45+54 or (b<5 or c>45) and no obj 'shovel' and $f=$vvv+'RRRRR': p 'OK' & goto 'Next' +ARRAY_NAME = ARRAY_NAME - [#expression 1] ``` -Examples of multi-line conditional forms: +Example: ```qsp -if library = 0: - learned_about_party = 0 - library_returned = 1 - gt 'library' -end -if a+b=2: - c=30 -end +! we replace two operations: assignment and subtraction +warrior = warrior - 15 +! with decrement (identical action) +warrior -= 15 ``` -:::warning[Pay attention!!!] - -In multi-line form, after the colon on the same line where the IF operator is located, there should be no commands, otherwise the player will consider such a conditional operator single-line, and commands in subsequent lines will be executed in any case, regardless of whether the condition turns out to be true or not. Example of such erroneous notation: +If the `ARRAY_NAME` variable value is a tuple, the specified number will be subtracted from each tuple element, and the resulting tuple will be assigned to the variable. Example: ```qsp -if library = 0: learned_about_party = 0 - library_returned = 1 &! this line will be executed regardless of the condition's truth - gt 'library' &! and this one too -end &! the end keyword is simply ignored +%tuple = [4, 10, 16] +%tuple -= 2 +! %tuple will equal [2, 8, 14] ``` -The exception is the comment operator written after the colon: +You cannot subtract a string type value; this will lead to a data type mismatch error. Also, tuple values (and all nested tuples) should not contain string values when performing this operation. However, you can perform subtraction-assignment with another tuple: ```qsp -if library = 0: ! if haven't visited library - learned_about_party = 0 - library_returned = 1 - gt 'library' -end +%tuple = [2, 3] +%tuple -= [4, 5] +! %tuple will equal [[-2,-3],[-1,-2]] ``` -But if the comment is separated by an ampersand, the condition will be considered single-line: +:::warning[Note] +Subtraction-assignment with a tuple will cause a data type mismatch error if the variable type is not a tuple: ```qsp -if library = 0: & ! such a comment makes the condition single-line! - learned_about_party = 0 & ! this line will be executed regardless of the condition's truth - library_returned = 1 & ! and this one - gt 'library' &! and this one too -end &! the end keyword is simply ignored +number = 4 +number -= [4,5] & ! data type mismatch error +! this way there will be no error, but the variable will contain an empty tuple: +%number -= [4,5] ``` ::: -For multi-line forms, unlimited depth nesting is allowed. Each nesting level must end with its own `end` line. +:::tip[Note] +Decrement — in many programming languages this is an operation that performs variable decrease. Most often, decrement means decreasing a variable by `1`. +::: -Examples: +## `-` (unary minus) -```qsp -if a+b<3 or y=8: - p 'A+B<3 or Y=8' - nl - if j=88: nl & p 'NEXT' - if $h='ooo': - p 'loo' & jump 'lll' - end -end -``` +**unary `-`** — unary operation. General syntax: ```qsp -if a=0: - 'abc1234' - if b=0: '0' else '1' - if j=88: nl & p 'NEXT' - if $h='ooo': - p 'loo' & jump 'lll' - else - p 'sample text' - v=8 - end - 1234 -else - '01234' - g=78 -end -``` - -Several examples of incorrect notation: - -```qsp {4} -! in this case, if the condition is not met, -! the player will ignore only the command `k1=34` -! since it will consider this a single-line condition -if abcd=3: k1=34 - k2=35 & ! this command will always be executed - k3=36 & ! this command will always be executed -end & ! this end will be ignored -``` - -```qsp {3,9} -! this line will output an error unknown action -! since single-line forms should not end with end -if abcd=3: k1=34 else k1=25 end +-[#expression] ``` -## ELSE +, where `[#expression]` — any numeric value or expression. The result of this operation is the same value but with opposite sign. -`ELSE` — keyword used together with the `IF` operator, which serves to provide an alternative if the condition is not met. The `ELSE` keyword also has two forms: single-line and multi-line. - -- Multi-line form of `ELSE` can only be used in multi-line construction of the `IF` operator, -- single-line form can be used both in single-line and multi-line constructions of the `IF` operator. General form: +Examples: ```qsp -! single-line form -IF [#expression]: {command y1} & {command y2} & ... ELSE {command n1} & {command n2} & ... - -! in multi-line IF: - -! multi-line form of ELSE -IF [#expression]: - {command y1} - {command y2} - ... -ELSE - {command n1} - {command n2} - ... -END - -! single-line form of ELSE -IF [#expression]: - {command y1} - {command y2} - ... -ELSE {command n1} & {command n2} & ... - ! commands in following lines - ! until END are ignored -END +-2 & ! returns -2 +-(3+6) & ! returns -9 +-(-27) & ! returns 27 ``` -Here, if condition `[#expression]` is true, commands from the colon to the `ELSE` keyword are executed, and if condition `[#expression]` is not true, commands from the `ELSE` keyword to the end of the conditional construction are executed. - -After `ELSE` you can put or not put a colon. - -**For single-line form:** - -- both commands and the `ELSE` keyword must be written on one line -- the end of the alternative command list is the end of the line. -- if single-line form of `ELSE` is used in multi-line form of `IF`, all commands that follow in subsequent lines after `ELSE` until `END` are ignored. - -Examples of single-line notation: +Unary minus can be used before a tuple containing only numeric values. This expression will return a new tuple where the sign of each element is changed to opposite: ```qsp -! if the sum of a and b equals two, variable c is assigned value 30 -! otherwise (i.e., if the sum of a and b does not equal two) -! variable c is assigned value 10 -if a+b=2: c=30 else c=10 - -! depending on whether there's an orange in inventory -! corresponding text is output -if obj("Orange"): pl "You have an orange." else pl "You don't have an orange." - -! single-line form of else inside multi-line if -if $left_hand = 'Great sword': - gosub 'atack', 300 - gosub 'health.prove' - gosub 'win.prove' -else gosub 'atack', atack_power -end +- [2, 3, -1, -17, 5] +! [-2, -3, 1, 17, -5] ``` -**For multi-line form:** - -- all commands must be in subsequent lines after `ELSE`; +:::note[5.7.0] -Examples of multi-line notation: +In earlier player versions, there was a "unary plus" operation: ```qsp -if a+b=2: - c=30 -else - c=10 -end - -if obj("Orange"): - pl "You have an orange." -else - pl "You don't have an orange." -end - -if len($curtoken) > 0: - $tokens[curtoken_num] = $curtoken tokens_count = curtoken_num + 1 -else - tokens_count = curtoken_num -end ++(6+7) ``` -## ELSEIF - -`ELSEIF` — keyword used together with the `IF` operator and allows defining sequentially-exclusive conditions at one nesting level. Has single-line and multi-line forms. +Essentially, it did nothing, so it was decided to abandon it. +::: -- Multi-line form can only be used in multi-line constructions with the `IF` operator, -- single-line form can be used in both multi-line and single-line constructions with the `IF` operator. +## `/` (division) -General forms: +`/` — arithmetic operation "DIVISION". General syntax: ```qsp -! single-line in single-line condition -IF [#expression 1]: {command set 1} ELSEIF [#expression 2]: {command set 2} ELSE {last command set} - -! multi-line in multi-line condition -IF [#expression 1]: - {command set 1} - ... -ELSEIF [#expression 2]: - {command set 2} - ... -ELSEIF ... : - ... -ELSE - {last command set} - ... -END - -! single-line in multi-line condition -IF [#expression 1]: - {command set 1} - ... -ELSEIF [#expression 2]: {command set 2} -ELSEIF ... : ... -ELSE {last command set} -END +[#expression 1] / [#expression 2] ``` -This works as follows. If `[#expression 1]` is true, commands `{command set 1}` are executed. If `[#expression 1]` is false, but `[#expression 2]` is true, commands `{command set 2}` are executed, and so on. And only if all expressions in the current conditional construction are false, commands after `ELSE` will be executed. The truth of expression `[#expression 1]` does not exclude the truth of expression `[#expression 2]`, but the truth of expression `[#expression 2]` excludes the truth of expression `[#expression 1]`. - -Features of `ELSEIF` notation: +, where `[#expression 1]` and `[#expression 2]` — any two numeric values or expressions. The value `[#expression 2]` must not equal zero. The operation result is the quotient of dividing two numbers. -- The variant `ELSE IF` can be used. Works exactly the same. -- If in multi-line `IF` construction after `ELSEIF` operators are on the same line (single-line form), then all subsequent lines are ignored until the next `ELSEIF`, or until `ELSE` or `END`. -- In `IF` construction with `ELSEIF`, the part with `ELSE` can be either present or absent. +Since QSP supports only integer values, division is also performed as integer division, without rounding, with truncation of the fractional part. Examples: ```qsp -if obj('Health potion'): health += 100 esleif obj('Apple'): health += 15 else *pl 'Nothing to restore strength!' - -IF POINTS>124: - GOTO 'END3' -ELSEIF POINTS>99: - GOTO 'END4' -ELSE - GOTO 'END5' -END - -if money mod 10=1 and money mod 100<>11: - *pl "You have <> coin." -elseif money mod 10>1 and money mod 10<5 and (money mod 100<5 or money mod 100>20): - *pl "You have <> coins." -elseif money mod 10=0 or money mod 10>4 or (money mod 100>10 and money mod 100<21): - *pl "You have <> coins." -end +2 / 2 & ! returns 1 +4 / 2 & ! returns 2 +17 / 5 & ! returns 3 +37 / 100 & ! returns 0 ``` -Example of `ELSEIF` notation with operators on the same line: +Can be used with tuples whose values are numbers and/or other tuples containing numbers. General syntax: ```qsp -! implementing switch/case in QSP -if r = 0: - 'Option 0' - elseif r = 1: 'Option 1' - elseif r = 2: 'Option 2' - elseif r = 3: 'Option 3' - else: 'No options' -end +[%tuple] / [#number] ``` -:::tip[Note:] - -For better code readability, it's recommended to use constructions with `elseif` only in multi-line form of the `if` operator. - -::: - -## INCLIB - -`INCLIB` — from the specified game file, adds all locations whose names are absent among the current game locations. Loaded locations are fully equivalent to locations from the main game file. General syntax: +In this case, each tuple element will be divided by the specified number. Examples: ```qsp -INCLIB [$path to game file] +%tuple = [4, 10, 16] +%a = %tuple / 2 +! %a will equal [2, 5, 8] + +[4, 10] / 'b' & ! data type mismatch error ``` -Example: +Note the last example. A data type mismatch error occurs because it's impossible to apply division to a string value. The same error will occur if the tuple contains string values. However, you can divide tuples containing only numbers: ```qsp -inclib "lib/easy.math.qsp" -inclib "lib/easy.title.qsp" -inclib "res/drive.qsp" -inclib "res/base.qsp" -inclib "res/intro.qsp" +*pl [30, 60] / [2, 6] +! [30 / [2,6], 60 / [2,6]] +! [[15,5],[30,10]] ``` -:::note[5.7.0] -In older player versions, the command was called `addqst` and `addlib`. -::: +In this case, each element of the first tuple is "divided" by the second tuple. This gives us a new tuple of two tuples as a result. -## JUMP +## `/=` (division-assignment) -`JUMP` — jump in the current code block to the specified label. General syntax: +`/=` — "DIVISION-ASSIGNMENT" operation. Combines assignment and division operations. Divides the specified variable value by a certain number and returns the result to the same variable. General syntax: ```qsp -JUMP [$label] +ARRAY_NAME /= [#expression 1] ``` -where `[$label]` is a label below or above in the code (see section ["Labels"](qsp-keyword-syntaxems.md#labels-)). - -`jump` finds a label only within the current code block, i.e., labels are local. - -Separate code blocks in QSP are: +, where `ARRAY_NAME` — variable name (without quotes) or array name with cell specification, and `[#expression 1]` — any numeric value or expression. -- "Execute on visit" code of a specific location (each location is a separate code block), -- action code even if the action is added programmatically, -- code in a hyperlink, -- `DYNAMIC`/`DYNEVAL` code - -Example: +Analogous to: ```qsp -jump 'End' -p 'This message will not be output' -:end -p 'But this message the user will see' +ARRAY_NAME = ARRAY_NAME / [#expression 1] ``` -:::note[5.7.0] -Using the `jump` operator in older player versions, you could organize loops: +Example: ```qsp -:loop -if s<9: - s=s+1 - pl s - jump 'loop' -end -p 'Done!' +! we replace two operations: assignment and division +warrior = warrior / 2 +! with division-assignment (identical action) +warrior /= 2 ``` -Double loop with one label: +If the `ARRAY_NAME` variable value is a tuple, each tuple element will be divided by the specified number, and the resulting tuple will be assigned to the variable. Example: ```qsp -:loop -if y<9: - if x<9: - *p "<> - " - x=x+1 - jump 'loop' - end - *pl ":<>" - y=y+1 - x=0 - jump 'loop' -end +%tuple = [4, 10, 16] +%tuple /= 2 +! %tuple will equal [2, 5, 8] ``` -Starting from version 5.8.0, the `loop` operator was introduced for loops. -::: - -## KILLALL - -`KILLALL` — destroys all variables and removes all objects from the objects window. Equivalent to the construction: +You cannot divide by a string type value; this will lead to a data type mismatch error. Also, tuple values (and all nested tuples) should not contain string values when performing this operation. However, you can perform division-assignment with another tuple: ```qsp -killvar & killobj +%tuple = [10, 30] +%tuple /= [5, 2] +! %tuple will equal [[2,5],[6,15]] ``` -:::warning[Attention!] -Remember that `killall` is not equivalent to the construction: +:::warning[Note] +Division-assignment with a tuple will cause a data type mismatch error if the variable type is not a tuple: ```qsp -killobj & killvar +number = 4 +number /= [4,5] & ! data type mismatch error +! this way there will be no error, but the variable will contain an empty tuple: +%number /= [4,5] ``` -since in this case variable values are deleted after object deletion, meaning the object deletion handler location code has time to execute (see `$onobjdel`). ::: -Usually `killall` is used at the beginning of the game if there's a "Start over" action at the end of the game. - -## KILLOBJ - -`KILLOBJ` — removing an object located at the specified position. General syntax: - -```qsp -KILLOBJ [#number] -``` - -where `[#number]` is the object number in the inventory window. Object numbering starts from 1. If the `[#number]` parameter is not specified, all objects are removed. When removing each object using `killobj`, the object deletion handler location code is executed (see `$onobjdel`). - -Example: - -```qsp -! remove the topmost object in the list -killobj 1 -! remove the bottommost object in the list -killobj countobj -! remove all objects -killobj -``` - -## KILLVAR +## MOD -`KILLVAR` — removing the specified array element. General syntax: +`MOD` — operation calculates the remainder from dividing two numbers. General syntax: ```qsp -KILLVAR [$array name], [element index] +[#expression 1] MOD [#expression 2] ``` -where `[$array name]` is the name of the array from which we want to remove an element, and `[element index]` is the number, text index, or multi-dimensional index of the array element we want to remove. Array element numbering starts from 0. - -If the element index is not specified, the entire array is cleared. If the operator is called without arguments, all variables and arrays are deleted. +, where `[#expression 1]` — dividend, `[#expression 2]` — divisor. Examples: ```qsp -killvar 'a', 3 & ! will delete element with index 3 from array 'a'. -killvar 'unit', 'Paratrooper' & ! deletes element with index 'Paratrooper' from array -killvar 'a' & ! deletes array 'a' -killvar & ! deletes all variables, arrays -killvar '$map_cell', (3, 4) & ! deletion by multi-dimensional index +! 4 divides by 2 evenly +4 mod 2 & ! returns 0 +! 5 doesn't divide by 2 evenly +5 mod 2 & ! returns 1 +! 13 doesn't divide by 10 evenly +13 mod 10 & ! returns 3 ``` -When deleting an element, all elements following it shift up one position. +The remainder from dividing a negative number will be a negative number. -Example: +## `<` (less than) -```qsp -a[0] = 4 -a[1] = 3 -a[2] = 23 -a[3] = 15 -KILLVAR 'a', 1 -! now the array looks like this: -! a[0] = 4 -! a[1] = 23 -! a[2] = 15 -``` - -## LET - -`LET` — deprecated operator for setting variables values. General syntax: +`<` — comparison operation "LESS THAN". General syntax: ```qsp -LET [variable name] = [expression] -LET [variable 1], [variable 2], ... = [value 1], [value 2], ... +[expression_1] < [expression_2] ``` -where `[variable name]` is a valid variable name, `[expression]` is a valid value for this variable. - -- Numeric variable names are written without `$` and `%` symbols at the beginning. -- Text variable names are written with `$` symbol at the beginning. -- Variable names containing tuples are written with `%` symbol at the beginning. +If the value of expression `[expression_1]` is less than the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns `0`. In other words: true if the first is less than the second. Examples: ```qsp -! set text variable -let $text = "text string" -! set numeric variable -let abs = 123 -! set tuple -let %tuple = [123, "text string"] -! multiple assignment -let unit_power, $unit_name = 1300, 'DiggerBull' -! unpack the tuple -let $name, age, height = %npc_fields +! 2 is less than 4 — returns 1 +2 < 4 +! 5 is not less than 5 — returns 0 +5 < 5 +! 7 is not less than 3 — returns 0 +7 < 3 ``` -:::tip -This operator is considered deprecated. Use the `set` operator instead, and only in cases when it improves code readability. +You can compare text values: ```qsp -! assignment can be done without set or let operators: -$text = "text string" +"a" < "z" & ! true +"z" < "zz" & ! true +"aaaaaa" < "z" & ! true ``` -::: - -## LOCAL - -`LOCAL` — declares a local variable (or several variables) in the current code block. - -General syntax: +And you can compare tuples: ```qsp -LOCAL [variable 1], [variable 2], ... -LOCAL [variable 1], [variable 2], ... = [value 1], [value 2], ... +[1, 2, 3] < [1, 2, 9] & ! true +[1, 2, 3] < [2, 2, 3] & ! true +[1, 2] < [1, 2, 3] & ! true ``` -where `[variable 1]`, `[variable 2]`, etc. are variable/array names written directly (not in quotes), and `[value 1]`, `[value 2]`, etc. are any values, constants, expression values, functions, or other variables. +## `<=` (less than or equal) -The number of variables and values must match (except for unpacking cases). +`<=` — comparison operation "LESS THAN OR EQUAL". General syntax: ```qsp -! declare one local variable -local tempora = 12 -! declare several local variables -local x, y, $item = 11, 19, "Old sword" -! declaration with unpacking -local i, j = %map_cell -local z, $a = [13, '37'] +[expression_1] <= [expression_2] ``` -Unlike `set` and `let` operators, you can declare a variable but not assign it a value. - -```qsp -local tempora -local x, y, $item, %map_cell -``` +If the value of expression `[expression_1]` is less than or equal to the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns `0`. In other words: true if the first is less than the second, or equal to it. -However, despite the variable being created, `arrsize` will return `0` for it. I.e., you cannot check if a variable is declared. +Examples: ```qsp -local arr -*pl arrsize('arr') & ! will output 0 +! 2 is less than 4 — returns 1 +2 <= 4 +! 5 equals 5 — returns 1 +5 <= 5 +! 7 is not less than three and not equal to it +7 <= 3 & ! returns 0 ``` -You can create your own local variables in the following code blocks: - -- Locations themselves. -- Code passed to the `DYNAMIC` operator or `DYNEVAL` function as text. -- Code executed when clicking on a hyperlink. -- Code of each separate Action ([ACT](qsp-keyword-operators.md#act)). -- Code of each separate Loop ([LOOP](qsp-keyword-operators.md#loop)) - -:::warning[**Attention!**] -Local variables have one feature that needs to be very clearly understood. The value of a local variable declared in a given code block is translated to all nested or called code blocks from this one. For example, if a local variable is declared on a location, its value is translated to all locations called using `GOSUB` or `FUNC`, to code blocks for `DYNAMIC`/`DYNEVAL`, to loop blocks, and so on. Example: +Analogous to "`=<`" and constructs: ```qsp -# start -! from this location we will call location foo -i = 99 & ! declare global variable -gosub 'foo' -*nl i & ! we'll see number 99 on screen ---- start --- - -# foo -! on this location we declare a local variable -local i = 0 -! local variable is translated to the loop -loop while i < 10 step i += 1: - ! in the loop we call location undo - gosub 'undo' - ! and also in the loop we work with the variable - ! declared on location foo -end -*nl i & ! we'll see number 10 on screen ---- foo --- +([expression_1] < [expression_2]) or ([expression_1] = [expression_2]) -# undo -! to this location from the loop on location foo -! the same local variable declared on location foo is translated -i+=1 & ! increase variable value, affecting the value in foo -*p 'undo:<>, ' & ! numbers 1,3,5,7,9 with prefix undo: will appear on screen ---- undo --- +no [expression_1] > [expression_2] ``` -**However!** Local variable values are not translated to actions (unlike `ARGS` array values at the current location): +You can also compare text values: ```qsp -$args[0] = 'current location' -local $var = 'local variable' -*pl $args[0] -*pl $var -act "Output values": - *pl $args[0] - *pl $var -end +"a" <= "z" & ! true +"z" <= "zz" & ! true +"aaaaaa" <= "z" & ! true +"z" <= "z" & ! true ``` -::: - -### Examples of local variable assignment - -```qsp title="Two locations, each with its own variable i" -# location 1 -if i = 0: i = 99 & ! variable i value is set only once -*pl "Global i = <>" -act "To location 2": goto 'location 2' ---- location 1 --- - -# location 2 -*pl "Global i = <>" -local i = 137 & ! variable i value is set only once -*pl "Local i = <>" -act "To location 1": goto 'location 1' ---- location 2 --- -``` - -```qsp title="Another example with two locations" -! this code will sequentially output numbers 12, 549 and 99, 549 -# start -x = 99 -z = 4608 -gosub 'foo' -*pl x & *pl z & ! numbers 99 and 549 will be output to screen ---- start --- - -# foo -local x & ! declare variable x local for this location -x = 12 & ! change variable x value -z = 549 -*pl x & *pl z & ! numbers 12 and 549 will be output to screen ---- foo --- -``` - -```qsp title="Example of declaring local variables in DYNEVAL code and in loop" -$chkObjWord = { - ! this is code written as text in variable $chkObjWord - ! in local variable $word we write the word - ! by which we search - local $word = $args[0] - loop local i = 1 while no i > countobj step i += 1: - ! use local variable i inside the loop - ! loop executes while counter doesn't exceed number of objects - if instr($getobj(i), $word) <> 0: - ! as soon as the considered word is found - ! in the name of the next object - result = i & ! return position - exit & ! close function - end - end -} -object_position = dyneval($chkObjWord, 'grenade') -``` - -```qsp title="Local variables can also be declared inside actions" -i=99 -act "Action with local i": - local i = 449933 - *pl i -end -act "Action with global i": - *pl i -end -``` - -## LOOP - -`LOOP` — loop operator. Necessary for organizing cyclic calculations. General syntax of single-line form: +And tuples: ```qsp -LOOP {commands before loop start} WHILE [condition] STEP {commands at end of iteration}: {loop body operators} +[1, 2, 3] <= [1, 2, 9] & ! true +[1, 2, 3] <= [2, 2, 3] & ! true +[1, 2] <= [1, 2, 3] & ! true +[1, 2, 3] <= [1, 2, 3] & ! true ``` -General syntax of multi-line form: +## `<>` (not equal) + +`<>` — comparison operation "NOT EQUAL". General syntax: ```qsp -LOOP {commands before loop start} WHILE [condition] STEP {commands at end of iteration}: - {loop body operators} -END +[expression_1] <> [expression_2] ``` -where: - -- `{commands before loop start}` — these are commands executed before the loop is started. These commands belong to the loop block but don't fall into iterations (passes), i.e., are executed only once. Here you can, for example, declare a loop counter. And here you can write multiple commands, listing them with the `&` (ampersand) separator. -- `[condition]` — this is an expression by whose value the condition is checked. Comparison operations and logical operations in any combinations can be used here. If the value of expression `[condition]` equals zero, the loop is interrupted. -- `{commands at end of iteration}` — these are commands executed at the end of each loop pass. Commands that don't directly relate to the loop body but nevertheless should be executed on each iteration can be placed here. Here you can, for example, change the loop counter value. And here you can actually write multiple commands, listing them with the `&` (ampersand) separator. -- `{loop body operators}` — these are commands that need to be executed on each pass and are the main ones for the loop. I.e., we make the loop specifically for these commands. +If the value of expression `[expression_1]` is not equal to the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns `0`. In other words: true if the expressions are not equal. -The loop in QSP is a separate code block, which means we can declare local variables inside this code block. This is very convenient because we can declare a local variable for the counter, and this won't affect other variables at the location: +Analogous to "`!`", or construct: ```qsp -i = 99 -*pl "i before loop <>" -loop local i = 0 & *p "i in loop: " while i < 6 step i += 1: - *p "<>, " -end -*nl "i after loop <>" +no [expression_1] = [expression_2] ``` -Loops are very convenient for iterating through arrays. For example, you can use a loop to add all numbers stored in an array: +Examples: ```qsp -summ=0 & ! here we'll write the sum of numbers -! our numbers are in array **mass** -loop local i, size = 0, arrsize('mass') while i < size step i += 1: - summ += mass[i] -end -*pl 'Sum of all elements in array mass: <>' +! 2 is not equal to 4 — returns 1 +2 <> 4 +! 5 equals 5 — returns 0 +5 <> 5 ``` -## MENU - -`MENU` — displays a popup menu anywhere in the game, whose items are written in the specified array. General syntax: +You can compare string values: ```qsp -MENU [$array name] +"abc" <> "def" & ! returns 1 +"abc" <> "abc" & ! returns 0 ``` -Before using this operator, you need to fill the array based on whose contents the menu items will be formed. Menu items are tuples of three values, sequentially placed in consecutive array cells starting from zero. The contents of each tuple should be approximately like this: +You can compare tuples: ```qsp -["menu item name", "location name", "path to icon file"] +[1, 2, 3] <> [4, 6, 7] & ! returns 1 +[1, 2, 3] <> [1, 2, 3] & ! returns 0 ``` -Menu item name is what we'll see on screen when the menu is displayed; location name is the name of the location whose code will be executed when clicking on the corresponding menu item; path to icon file is the path to the image file that will be displayed next to the menu item name. +## `=` (equal) -Knowing this, we can fill the array to create our menu items: +`=` — comparison operation "EQUAL". General syntax: ```qsp -%stone[0] = ['Take stone', 'takestone'] -%stone[1] = ['Throw stone', 'throwstone'] -%stone[2] = ['Examine stone', 'lookstone'] +[expression_1] = [expression_2] ``` -Here the array name (`%stone`) is the menu name, and the tuples are actions for which item names and handler location names for menu item selection are specified. When selecting the "Take stone" item, the location named "takestone" will be called. Similarly for other items. - -To display the menu on screen, use the `MENU` operator: - -```qsp -menu '%stone' -``` +If the value of expression `[expression_1]` equals the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns `0`. In other words: true if the expressions are equal. -Example of creating a menu with icons: +Analogous to construct: ```qsp -! no icon -%usr_menu[0] = ['Take item', 'take_item'] -! icon specified by gif file -%usr_menu[1] = ['Put item', 'put_item', 'images/put_item.gif'] -! icon specified by $icon_file value -%usr_menu[2] = ['Destroy item','del_item', $icon_file] -! menu item specified by 3 variables -%usr_menu[3] = [$name, $location, $icon_file] - -menu 'usr_menu' &! will show menu of 4 items +no [expression_1] <> [expression_2] ``` -The menu ends on an array element with an empty tuple, or with a tuple missing a value for the menu item name or item handler location. - -Examples where the last two menu items won't be created: +Examples: ```qsp -%usr_menu[0]=['Take item','take_item'] & ! we'll see this item on screen -$usr_menu[1]=['Examine item','look_item'] & ! and we'll see this item on screen -$usr_menu[2]=[] & ! empty tuple, player will consider menu ended -$usr_menu[3]=['Put item','put_item'] & ! we won't see this item +! 2 is not equal to 4 — returns 0 +(2 = 4) +! 5 equals 5 — returns 1 +(5 = 5) ``` -```qsp -%usr_menu[0]=['Take item','take_item'] & ! we'll see this item on screen -$usr_menu[1]=['Examine item','look_item'] & ! and we'll see this item on screen -$usr_menu[2]=['destroy item', ''] & ! no handler location specified, won't see item -$usr_menu[3]=['Put item','put_item'] & ! and we won't see this item -``` +You can compare string values: ```qsp -%usr_menu[0]=['Take item','take_item'] & ! we'll see this item on screen -$usr_menu[1]=['Examine item','look_item'] & ! and we'll see this item on screen -$usr_menu[2]=['', 'del_item'] & ! no name specified, won't see item -$usr_menu[3]=['Put item','put_item'] & ! and we won't see this item +("abc" = "def") & ! returns 0 +("abc" = "abc") & ! returns 1 ``` -To insert a separator in the menu, use a tuple with "-" values. I.e., if you need to put a separator instead of the 3rd element: +You can compare tuples: ```qsp -%usr_menu[0]=['Take item','take_item'] -$usr_menu[1]=['Examine item','look_item'] -$usr_menu[2]=['-', '-'] & ! separator instead of menu item -$usr_menu[3]=['Put item','put_item'] +([1, 2, 3] = [4, 6, 7]) & ! returns 0 +([1, 2, 3] = [1, 2, 3]) & ! returns 1 ``` -An argument (`args[0]`) - the position of the selected item - is passed to the menu item selection handler location. Menu item positions are numbered from 1. - -:::note[Deprecated array filling variant. Strings] - -This variant can be used both in players version 5.9.0 and in earlier versions. - -Here menu items are string values of an array with a special format: - -```qsp -"menu item name:location name:path to icon file" -``` +:::warning[Attention!] +Don't confuse with the [assignment operation](#-assignment). +::: -- Menu item name is what we'll see on screen when the menu is displayed; -- location name is the name of the menu item handler location whose code will be executed when clicking on the corresponding menu item; -- path to icon file is the path to the image file that will be displayed next to the menu item name. If the path to icon file is not specified or the specified file is unavailable, the menu item will be displayed without an icon. +## `=` (assignment) -The search for ":" symbols starts from the end of the string, meaning the menu item name can contain colons, but then there must be a colon after the location name, even if you don't use icons for menu items. +`=` — assignment operation. General syntax: ```qsp -$stone[0]='Stone: take:takestone:' -$stone[1]='Stone: throw:throwstone:' -$stone[2]='Stone: examine:lookstone:' +ARRAY_NAME = [value] ``` -If the path to icon file is not specified or the specified file is unavailable, the menu item will be displayed without an icon. +, where `ARRAY_NAME` — variable name (not in quotes) or array name with cell specification (not in quotes), `[value]` — any value or expression. -Thus we should fill the array to create our menu items: +Examples: ```qsp -$stone[0]='Take stone:takestone' -$stone[1]='Throw stone:throwstone' -$stone[2]='Examine stone:lookstone' +! assign value 13 to variable BOX +BOX = 13 +! assign value "Text string" to variable $text +$text = "Text string" +! assign value 365 to zero cell of array day +day[0] = 365 +! assign tuple [1, 'unit', 3] to variable tuple: +%tuple = [1, 'unit', 3] ``` -Here the array name (`$stone`) is the menu name, and the text array values are actions for which names and handler location names for menu item selection are specified. When selecting "Take stone", the location named "takestone" will be processed. Similarly for other items. +String variable/array names must start with the `$` symbol. -To call the menu on screen, use the `menu` operator: +Variable/array names containing tuples must start with the `%` symbol. -```qsp -menu '$stone' -``` - -Menus can be called anywhere in the game, for example, from hyperlinks: +:::warning[Attention!] +The assignment operation should not be confused with the "EQUAL TO" comparison operation, although they look very similar: ```qsp -'Stone' +! assignment operation +alukard = 1000 +! comparison operation +(alukard = 1000) ``` -Example of creating a menu with icons: +In this case, the player understands that inside the brackets is a comparison operation because brackets are used for writing expressions. The notation: ```qsp -! no icon -$usr_menu[0] = 'Take item:take_item' -! icon specified by gif file -$usr_menu[1] = 'Put item:put_item:images/put_item.gif' -! icon specified by $icon_file value -$usr_menu[2] = 'Examine item:look_item:<<$icon_file>>' -! menu item specified by 3 variables -$usr_menu[3] = '<<$name>>:<<$location>>:<<$file>>' - -menu 'usr_menu' &! will show menu of 4 items +"abc" = "abc" ``` -The menu ends on an array element with value `''` (empty string). I.e., if the menu array consists of elements 'Take', 'Examine', '', 'Throw', then the last 2 menu items won't be created: - -```qsp -$usr_menu[0] = 'Take item:take_item' & ! we'll see this item on screen -$usr_menu[1] = 'Examine item:look_item' & ! and we'll see this item on screen -$usr_menu[2] = '' & ! empty value here, player will consider menu ended -$usr_menu[3] = 'Put item:put_item' & ! we won't see this item -``` +is syntactically incorrect. The player will give an error: invalid variable/array name. Since in this case it doesn't understand that this is a comparison operation. -To insert a separator in the menu, write `"-:-"` instead of the corresponding array element. I.e., if you need to put a separator instead of the 3rd element: +If an operator explicitly precedes the comparison operation, brackets can be omitted: ```qsp -$usr_menu[0] = 'Take item:take_item' -$usr_menu[1] = 'Examine item:look_item' -$usr_menu[2] = '-:-' -$usr_menu[3] = 'Put item:put_item' +if alukard = 150: *pl "Not enough strength" +*pl "abc" = "abc" ``` ::: -## MSG - -`MSG` — displays the specified message in a dialog box. General syntax: - -```qsp -MSG [message] -``` +### Multiple Assignment -where `[message]` is any text string, number, expression of any type. Examples: - -Examples: +Multiple assignment allows assigning values to several variables or array cells with one `=` command. General syntax: ```qsp -! simple message output. -msg 'Many ripe pears.' -! we get a window with message 'Many ripe pears' +ARRAY_NAME_1, ARRAY_NAME_2, ... , ARRAY_NAME_N = [VALUE_1], [VALUE_2], ... , [VALUE_N] ``` -```qsp -! Example of message in ACT action. -act 'Eat pears': - msg 'Mmm pears are very tasty.' -end -! We get message output when clicking on action "Eat pears" -``` +, where variable names (or array names with cell index specification in square brackets) are written to the left of the `=` sign, and values to be assigned to variables or array cells are listed to the right of the `=` sign. -```qsp -!Example with condition. -if breadready = 1: - msg 'Looks like the bread is ready.' -end -! We get message output when condition breadready = 1 -``` +:::warning[Important to remember!] +There must be as many variables to the left of the equals sign as there are values to the right. The number of variables and the number of assigned values must match. -## NL +This rule is not followed when unpacking tuples. +::: -`NL` — line break, then text output in the additional description window. General syntax: +Examples: ```qsp -NL [$text] +apples_in_pocket, apples_in_basket, apples_at_lyoshka = 58, 11, 19 +$string_1, $string_2 = 'Grekha rode across the river', 'Grekha sees a crab in the river' +$name, count = 'Old sword', 2 ``` -where `[$text]` is any text string, number, or expression of any type. If `[$text]` is absent, a simple line break occurs. Example: +Instead of directly specifying values, you can assign values of other variables, expressions, functions: ```qsp -p "Text without line break." -nl "Line break + text output." -p "Text without line break." +! three variables = three values +red, green, blue = rand(0,255), rand(0,255), rand(0,255) +! two variables = two values +apples_in_pocket, apples_in_basket = apples_at_lyoshka, apples_on_tree+15 ``` -## OPENGAME - -`OPENGAME` — loading the specified game state file. General syntax: +Thanks to the ability to simultaneously assign values to several variables, you can swap data in two variables without using a third: ```qsp -OPENGAME [$path] +! assign variables x and y values 12 and 99 +x, y = 12, 99 +! swap values. Now x contains number 99, and y — 12 +x, y = y, x ``` -where `[$path]` is the path to the saved game state file. If the `[$path]` parameter is absent, the game state loading window is called. +### Tuple Unpacking -Example: +Since tuples contain several values at once, the notation for assigning values to variables from tuples can differ from the usual: ```qsp -! load state from file 1.sav -opengame "1.sav" -! open state loading window -opengame +! %unit = [187, 94, 'steel', [0, 2]] +height, weight, $material, %coordinates = %unit ``` -See also the game state loading event handler location ([$ongload](qsp-keyword-sys-var.md#ongload)). - -## OPENQST +As you can see, here we have four variable names on the left, but only one tuple variable name on the right. Such assignment is called unpacking — values are extracted from the tuple and placed in the specified variables. -`OPENQST` — opening and running the specified game file. General syntax: +A tuple not placed in a variable is unpacked the same way: ```qsp -OPENQST [$path] +height, weight, $material, %coordinates = [187, 94, 'steel', [0, 2]] ``` -where [$path] is the path to the game file to be run. Example: +Such notation differs little from multiple assignment, so external square brackets are not required: ```qsp -openqst "gamespool/cubesgame.qsp" +height, weight, $material, %coordinates = 187, 94, 'steel', [0, 2] ``` -When using this operator, variables are not deleted, inventory objects are not removed, the additional description and input line are not cleared, and playing files are not stopped. If you need to clear the screen and all variable values, you can write such commands at the beginning of the loaded game file: +It should be emphasized that **multiple assignment is essentially tuple unpacking**. -```qsp -killall & cls & close all -``` - -## P - -`P` — text output to the additional description window without line break. Text output by any other operator immediately after p will add new text immediately after the current text. General syntax: +Since if there are more variables to the left of the equals sign than values in the tuple, default values for those variables will be written to the "extra" variables, the same will happen with multiple assignment. ```qsp -P [$text] +r, g, b, a = [255, 188, 19] +! r = 255, g = 188, b = 19, a = 0 +raz, dva, tri, chetyre = 137, 61 +! raz = 137, dva = 61, tri = 0, chetyre = 0 ``` -where `[$text]` is any text string, number, or expression of any type. `[$text]` can be an empty string `''`, but should not be absent. Example: +At the same time, if there are fewer variables to the left of the equals sign than values to the right in multiple assignment, this will cause a data type mismatch error: -```qsp -p "Text without line break." -p "Text without line break." -p "" -p "Text without line break." +```qsp title="Data type mismatch" +coords = 23, 34 +age, weight, material = 27, 94, 'steel', 'biorobot' ``` -## PL - -`PL` — text output to the additional description window, then line break. General syntax: +If the type of the last listed variable is a tuple, such assignment won't cause an error: ```qsp -PL [$text] +age, weight, %type = 27, 94, 'steel', 'biorobot' +! age = 27, weight = 94, %type = ['steel', 'biorobot'] ``` -where `[$text]` is any text string, number, or expression of any type. `[$text]` can be absent, then just a line break. Example: - -```qsp -pl "Text output, then line break." -pl & ! line break without text output -pl "Text output, then line break." -p "Text without line break." -pl "Text output, then line break." -``` +## `=<` (equal or less) -## PLAY +:::warning[Attention!] +This notation, although acceptable in QSP, is not recommended for use. Use "`<=` (less than or equal)" instead. +::: -`PLAY` — playing the specified sound file with given volume. General syntax: +`=<` — comparison operation "EQUAL OR LESS". General syntax: ```qsp -PLAY [$path to sound file],[#volume] +[expression_1] =< [expression_2] ``` -where `[$path to sound file]` is the path to the sound file relative to the game file, `[#volume]` is playback volume as percentage from 0 to 100. The `[#volume]` parameter can be absent, in which case volume is taken as 100%. Examples: +If the value of expression `[expression_1]` is less than or equal to the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns 0. In other words: true if the first is less than the second, or equal to it. -```qsp -!Volume 100% -play 'sound/music.mp3' -!Volume 50% -play 'sound/music.mp3', 50 -!Volume 0% (no sound) -play 'sound/music.mp3', 0 -``` +Examples: ```qsp -!Playing file by address from variable $file -! with extension 'mid' -! and volume volume -$file = "melody" -play '<<$file>>.mid', volume -! similarly: -$file = "melody.mid" -play $file, volume +! 2 is less than 4 — returns 1 +2 =< 4 +! 5 equals 5 — returns 1 +5 =< 5 +! 7 is not less than three and not equal to it +7 =< 3 & ! returns 0 ``` -If the file is already playing, the volume changes without "restarting" it. Multiple audio formats are supported and simultaneous playback of up to 32 compositions. - -## REFINT - -`REFINT` — forced interface update (including color and font changes assigned using system variables). - -By default, interface update occurs 2 times per second (every 500 ms). See also the [`settimer`](#settimer) operator. - -## SAVEGAME - -`SAVEGAME` — saving game state to the specified file. General syntax: +Analogous to "`<=`" and constructs: ```qsp -SAVEGAME [$path] -``` - -where `[$path]` is the path to the created game state save file. If the `[$path]` parameter is absent, the game state save window is called. - -Example: +([expression_1] < [expression_2]) or ([expression_1] = [expression_2]) -```qsp -! save state to file 1.sav -savegame "1.sav" -! open state save window -savegame +no [expression_1] > [expression_2] ``` -See also [game state save event handler location ($ongsave)](qsp-keyword-sys-var.md#ongsave). +## `=>` (equal or greater) -## SCANSTR +:::warning[Attention!] +This notation, although acceptable in QSP, is not recommended for use. Use "`>=` (greater than or equal)" instead. +::: -`SCANSTR` — searching for non-overlapping occurrences in a string that match a pattern, and placing these occurrences in an array. General syntax: +`=>` — comparison operation "EQUAL OR GREATER". General syntax: ```qsp -SCANSTR [$array_name], [$text_to_parse], [$regexp], [#group_number] +[expression_1] => [expression_2] ``` -where `[$array_name]` is the array where strings matching the regular expression `[$regexp]` are placed. The search is performed on string `[$text_to_parse]`. If parameter `[#group_number]` is specified, not the entire string matching the regular expression will be placed in the array, but only the part corresponding to the specified group in this regular expression. +If the value of expression `[expression_1]` is greater than or equal to the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns 0. In other words: true if the first is greater than the second, or equal to it. Examples: ```qsp -! extract all words from string: -$text = 'Sasha walked down the highway, and Greka across the river.' -scanstr '$words', $text, '\b\w+\b' -!The $words array will contain values: 'Sasha', 'walked', 'down', 'highway', 'and', 'Greka', 'across', 'river' - -! split string by delimiter: -$text = 'morning|day|evening|night' -scanstr '$words', $text, '[^|]+' -!The $words array will contain values: 'morning', 'day', 'evening', 'night' - -! extract all words placed in square brackets from string, but without square brackets: -$text = '[first] ignoredtext [second][third] also ignored' -scanstr '$words', $text, '\[(.*?)\]', 1 -!The $words array will contain values: 'first', 'second', 'third' -``` - -## SET - -`SET` — operator for setting variables values. General syntax: - -```qsp -SET [variable name] = [expression] -SET [variable 1], [variable 2], ... = [value 1], [value 2], ... -``` - -where `[variable name]` is a valid variable name, `[expression]` is a valid value for this variable. - -Numeric variable names are written without the `$` symbol at the beginning. Text variable names are written with the `$` symbol at the beginning. Examples: - -```qsp -! set text variable -set $text = "text string" -! set numeric variable -set abs = 123 -! set tuple -set %tuple = [27, 184, 'steel'] -! multiple assignment -set unit_power, $unit_name = 1300, 'DiggerBull' -! unpack the tuple -set $name, age, height = %npc_fields +! 2 is not greater than and not equal to 4 — returns 0 +2 => 4 +! 5 equals 5 — returns 1 +5 => 5 +! 7 is greater than 3 +7 => 3 & ! returns 1 ``` -:::note[Recommendation:] -Since assignment can be done without the `set` operator, we recommend using this operator only for cases when it improves code readability. For example, with multiple assignment: +Analogous to "`>=`" and constructs: ```qsp -set apples_in_pocket, apples_in_basket, apples_at_Lyosha = 58, 11, 19 -set $string_1, $string_2 = 'Greka Rode Across River', 'Greka Sees Crab In River' +([expression_1] > [expression_2]) or ([expression_1] = [expression_2]) +no [expression_1] < [expression_2] ``` -::: - -## SETTIMER +## `>` (greater than) -`SETTIMER` — sets the interval for accessing the counter location. General syntax: +`>` — comparison operation "GREATER THAN". General syntax: ```qsp -SETTIMER [#expression] +[expression_1] > [expression_2] ``` -where `[#expression]` is the period of accessing the counter location in milliseconds. By default, the player accesses the counter location every 500 ms, i.e., 2 times per second. - -Setting the counter location access period also affects the frequency of automatic interface settings update. +If the value of expression `[expression_1]` is greater than the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns `0`. In other words: true if the first is greater than the second. Examples: ```qsp -! counter location will be launched every 2 seconds: -settimer 2000 +! 2 is not greater than 4 — returns 0 +2 > 4 +! 5 is not greater than 5 — returns 0 +5 > 5 +! 7 is greater than 3 — returns 1 +7 > 3 ``` -```qsp -! counter location will be launched 4 times per second: -settimer 250 -``` +You can compare text values, where characters are compared sequentially, and the character closer to the end of the alphabet is considered greater. ```qsp -! if we set frequency of access (times per second) -frequency=10 & ! ten times per second -settimer 1000/frequency +"z" > "a" & ! true +"zz" > "z" & ! true +"z" > "aaaaaa" & ! true ``` -```qsp -! if we set access period (after how many seconds) -period=2 & ! every two seconds -settimer 1000*period -``` - -The minimum period value can thus be 1 millisecond: +And you can compare tuples: ```qsp -settimer 1 +[1, 2, 9] > [1, 2, 3] & ! true +[1, 2, 3] > [2, 2, 3] & ! false +[1, 2, 3] > [1, 2] & ! true ``` -However, in practice, the minimum value is limited by your computer's power, and it's usually higher than 1 millisecond. - -## SETVAR - -`SETVAR` — assigns a value to a variable or array cell. +## `>=` (greater than or equal) -This function allows avoiding the use of `dynamic` in cases where you need to assign a value to a variable whose name is not known in advance. - -General syntax: +`>=` — comparison operation "GREATER THAN OR EQUAL". General syntax: ```qsp -SETVAR [$array_name], [value], [index] +[expression_1] >= [expression_2] ``` -where `[$array_name]` is the name of the array or variable to which the value should be assigned; `[value]` is a value of any type: string, number, tuple — however, the type of value that will be placed in the variable is determined by the type prefix before the variable name; `[index]` is if the value is assigned to an array cell, you need to specify the cell index with this parameter (can be of any type). +If the value of expression `[expression_1]` is greater than or equal to the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns 0. In other words: true if the first is greater than the second, or equal to it. Examples: ```qsp -SETVAR 'A', 65 -SETVAR '$X', 'name', 4 -SETVAR '$X', 'name', 'string index' -SETVAR '%Q', ['example', 'tuple'], 3 -SETVAR '%Q', ['example', 'tuple'], [x, y] - -$arr_pref = '%' -$arr_name = 'tuple' -SETVAR $arr_pref+$arr_name, ['tuple', 1], 3 +! 2 is not greater than and not equal to 4 — returns 0 +2 >= 4 +! 5 equals 5 — returns 1 +5 >= 5 +! 7 is greater than 3 +7 >= 3 & ! returns 1 ``` -## SHOWACTS - -`SHOWACTS` — controls the display of the actions window on screen. General syntax: +Analogous to "`=>`" and constructs: ```qsp -SHOWACTS [#expression] +([expression_1] > [expression_2]) or ([expression_1] = [expression_2]) +no [expression_1] < [expression_2] ``` -where `[#expression]` is a number. Usually values `0` and `1` are used. If the value of expression `[#expression]` is not zero, the actions window is displayed. If the value of expression `[#expression]` equals zero, the actions window is hidden. Examples: +You can compare text values, where characters are compared sequentially, and the character closer to the end of the alphabet is considered greater. ```qsp -showacts 1 & ! shows actions list -showacts 0 & ! hides actions list +"z" >= "a" & ! true +"zz" >= "z" & ! true +"z" >= "aaaaaa" & ! true +"z" >= "z" & ! true ``` -For code readability, you can pre-define `on` and `off` variables and use them: +And tuples: ```qsp -on = 1 -off = 0 -showacts on & ! shows actions list -showacts off & ! hides actions list +[1, 2, 9] >= [1, 2, 3] & ! true +[1, 2, 3] >= [2, 2, 3] & ! false +[1, 2] >= [1, 2, 3] & ! false +[1, 2, 3] >= [1, 2, 3] & ! true ``` -## SHOWINPUT +## `!` (not equal) -`SHOWINPUT` — controls the display of the input line on screen. General syntax: +:::warning[Attention!] +Don't confuse with the comment operator. -```qsp -SHOWINPUT [#expression] -``` +For better code readability, we recommend using `<>`. +::: -where `[#expression]` is a number. Usually values `0` and `1` are used. If the value of expression `[#expression]` is not zero, the input line is displayed. If the value of expression `[#expression]` equals zero, the input line is hidden. Examples: +`!` — comparison operation "NOT EQUAL". General syntax: ```qsp -showinput on & ! shows input line -showinput off & ! hides input line +[expression_1]![expression_2] ``` -## SHOWOBJS +If the value of expression `[expression_1]` is not equal to the value of expression `[expression_2]`, the operation returns `1`, otherwise it returns `0`. In other words: true if the expressions are not equal. -`SHOWOBJS` — controls the display of inventory on screen. General syntax: +Analogous to "`<>`", or construct: ```qsp -SHOWOBJS [#expression] +no [expression_1] = [expression_2] ``` -where `[#expression]` is a number. Usually values 0 and 1 are used. If the value of expression `[#expression]` is not zero, inventory is displayed. If the value of expression `[#expression]` equals zero, inventory is hidden. Examples: - -```qsp -showobjs 1 & ! shows inventory -showobjs 0 & ! hides inventory -``` - -For code readability, you can pre-define `on` and `off` variables and use them: +Examples: ```qsp -on = 1 -off = 0 -showobjs on & ! shows inventory -showobjs off & ! hides inventory +! 2 is not equal to 4 — returns 1 +2 ! 4 +! 5 equals 5 — returns 0 +5 ! 5 ``` -## SHOWSTAT +## `&` (concatenation) -`SHOWSTAT` — controls the display of the additional description window on screen. General syntax: +`&` — concatenation, operation for combining string expressions or tuples. General syntax: ```qsp -SHOWSTAT [#expression] +([$expression 1] & [$expression 2]) +([%expression 1] & [%expression 2]) ``` -where `[#expression]` is a number. Usually values `0` and `1` are used. If the value of expression `[#expression]` is not zero, the additional description window is displayed. If the value of expression `[#expression]` equals zero, the additional description window is hidden. Examples: +:::warning[Attention!] +Concatenation must always be enclosed in brackets! +::: -```qsp -showstat 1 & ! shows additional description window -showstat 0 & ! hides additional description window -``` +If you try to combine numeric values, they will be converted to strings, and then the strings will be combined. -For code readability, you can pre-define `on` and `off` variables and use them: +Examples: ```qsp -on = 1 -off = 0 -showstat on & ! shows additional description window -showstat off & ! hides additional description window +*pl ('hello, ' & 'World!') +! we'll see the string 'hello, World!' on screen +*pl ([1, 2, 3] & [4, 5, 6]) +! we'll see the tuple [1, 2, 3, 4, 5, 6] on screen ``` -## SORTARR - -`SORTARR` — sorting the specified array. General syntax: +:::warning[Attention!] +Don't confuse with the command enumeration symbol: ```qsp -SORTARR [$array_name], [#order] +! in this case, strings "26" and "27" will be +! output to screen sequentially +"26" & "27" +! and here the string "2627" will be output to screen +("26" & "27") ``` -Here `[$array_name]` is the name of the array to be sorted. The `[#order]` parameter can be omitted. If not specified or equals `0`, sorts the array in ascending order (from smaller to larger). If equals `1`, sorts the array in descending order (from larger to smaller). - -Can sort arrays of any types (numbers, strings, tuples), but mixing values of different types in one array is not allowed. - -To specify the type of sorted values, you need to specify the type prefix as part of the array name (`$`, `%`). +::: -Example of sorting a text array: +:::tip +It's not recommended to use this operation for combining strings, since strings can be combined through [`+`](qsp-keywords-operators.md#-addition): ```qsp -$a[] = 'nn' -$a[] = 'zz' -$a[] = 'aa' -sortarr '$a' - -!check sorting result: -loop local i=0 while i 2) & ! expression returns 1 (true) +! one part of expression is not true, so entire expression is false +(2 <> 2) and (3 <> 2) & ! expression returns 0 (false) +! both parts of expression are not true, so entire expression is not true +(2 <> 2) and (3 = 2) & ! expression returns 0 (false) ``` -## VIEW +:::note[5.7.0] +In older player versions, the operation was bitwise. +::: -`VIEW` — displays the specified image on screen. In the classic player, the image is displayed in a separate window (preview window), in qSpider the image is displayed as a layer. General syntax: +## LOC + +`LOC` — operation checks for location existence and returns `1` if location exists, and `0` if location doesn't exist. General syntax: ```qsp -VIEW [$path to graphics file] +LOC([$location]) ``` -where `[$path to graphics file]` is the path to the image file. If the `[$path to graphics file]` parameter is absent, or specified as `''` (empty string), the preview window closes. +, where `[$location]` — location name whose existence needs to be checked in the game. Expression is true if location exists in the game. Examples: ```qsp -! display image in preview window -view 'content/monster.png' -! close preview window -view '' +! checks if location "start" exists in game +loc("start") & ! if location exists, returns 1 -! preview window can also be closed like this -view +! if location "street" is not added to game +if loc("street") = 0: + act "Go outside": *pl "I can't go outside, the door won't open." +end ``` -## WAIT +## NO -`WAIT` — pausing program code execution for the specified number of milliseconds. General syntax: +`NO` — negation operation. General syntax: ```qsp -WAIT [#milliseconds] +NO [#expression] ``` -where `[#milliseconds]` is the time in milliseconds for which program code execution should be stopped. +If `[#expression]` is true, then the entire expression is false, and vice versa. In other words, returns `0` if the expression value is not zero, and returns `1` if the expression value equals `0`. Example: ```qsp -! stop program execution for 5 seconds -wait 5000 +! 4 equals 4 is true, so entire expression is false +no (4 = 4) & ! returns 0 (false) +! can be read as question: four does not equal four? No — false. + +! that 5 equals 3 is false, so entire expression is true +no (5 = 3) & ! returns 1 (true) +! can be read as question: five does not equal three? Yes — true. ``` -:::warning[Caution!] -This operator should be used with caution, since pausing code execution blocks the player's ability to interact with the game. +:::note[5.7.0] +In older player versions, the operation was bitwise. ::: -`WAIT` not only interrupts code execution but also forces the player to output information from the screen buffer. During normal location code execution, all text for operators `*pl`, `*p` `pl`, `nl`, etc. is placed in a special screen buffer, and only after executing all code on the location is it output to the screen. When using `WAIT`, text from the buffer is output immediately at the moment `WAIT` is executed, which is sometimes useful because it allows tracking changes in some values step by step. +## OBJ -In the example below, numbers will first be written to the screen buffer and only then appear on screen: +`OBJ` — operation checks for item presence in inventory and returns `1` if item exists, and `0` if item doesn't exist. General syntax: ```qsp -loop i=0 while i<5 step i+=1: - *p i -end -*pl +OBJ([$name]) ``` -In the next example, they will be output one after another with an interval of about 100 ms. +, where `[$name]` — item name whose presence needs to be checked in the objects window. Expression is true if item is added to the objects window. + +Examples: ```qsp -loop i=0 while i<5 step i+=1: - wait 100 - *p i +! checks if "Screwdriver" item is added to objects window +obj("Screwdriver") & ! if item exists, returns 1 + +! depending on presence of this or that item +! this or that action is output +if obj("Full jug") = 1: + act "Empty jug": + delobj "Full jug" + addobj "Empty jug" + goto $curloc + end +elseif obj("Empty jug") = 1: + act "Fill jug": + addobj "Full jug" + delobj "Empty jug" + goto $curloc + end end -*pl ``` -## XGOTO +## OR -`XGOTO` — transition to the specified location without clearing the main description window. General syntax: +`OR` — logical "OR". General syntax: ```qsp -XGOTO [$location], [argument 0], [argument 1], ... , [argument 18] +[#expression 1] OR [#expression 2] ``` -where `[$location]` is the name of the location to which the transition should be made. Arguments `[argument 0]`, `[argument 1]`, etc. can be used on this location, their values are automatically placed in variables `args[0]`, `args[1]`, etc. respectively. Using arguments is not mandatory. - -When transitioning to a new location using `xgoto`, the main description window is not cleared, and the base description of the new location is added to the existing text in the main description window. The actions list is cleared, then base actions are output to the actions window, and code from the "Execute on visit" field of location `[$location]` is executed. Also, when transitioning to a new location, the value returned by the `$curloc` function changes. +The entire expression will be true if at least one of expressions `[#expression 1]` and `[#expression 2]` is true. Examples: ```qsp -! transition to location "house". -! The args array at location "house" will be empty. -xgoto 'house' +! both parts of expression are true, so entire expression is true +(2 = 2) or (3 <> 2) & ! expression returns 1 (true) +! one part of expression is true, so entire expression is true +(2 <> 2) or (3 <> 2) & ! expression returns 1 (true) +! both parts of expression are not true, so entire expression is not true +(2 <> 2) or (3 = 2) & ! expression returns 0 (false) ``` -```qsp -! transition to location "street" with passing 2 parameters. -! at location "street" args[0] equals 1, -! $args[1] contains string "data". -xgoto 'street', 1, 'data' -``` - -The operator has a short form `xgt`: - -```qsp -XGT [$location], [argument 0], [argument 1], ... , [argument 18] -``` +:::note[5.7.0] +In older player versions, the operation was bitwise. +::: diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-statements.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-statements.md new file mode 100644 index 0000000..523a217 --- /dev/null +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-statements.md @@ -0,0 +1,2033 @@ +--- +sidebar_position: 2 +--- + +# Statements + +## Implicit statement + +The implicit statement is an statement that is not written in QSP code but outputs values to the screen. It is implied wherever an expression without an statement is present in a command. The implicit statement outputs values to the **Main Description Window** in the same way as if you used explicit specification of the `*pl` statement, i.e., it outputs the value and makes a line break. Examples: + +```qsp +$AAA + '989' +'You are in the park' +'Preformatted + + string' +$curloc & ! will output the location name to the screen +``` + +Unlike the `*pl` statement, the implicit statement does not output an empty line with a line break to the screen if no value is passed to it. This means that if a function returns no value, the implicit statement is simply ignored. Example: + +```qsp +# start +! this is the code of a location calling a location-function +$curloc +$func('foo') +$func('foo') +$curloc +- start + +# foo +! this is the code of the location-function +local i = 0 +- foo +``` + +In this case, the location-function `foo` returns nothing, so we will see two lines with the word "start" on the screen, with no empty lines between them, since the implicit statement in the lines with `$func` at location `start` will be simply ignored. Compare with: + +```qsp +# start +! this is the code of a location calling a location-function +*pl $curloc +*pl $func('foo') +*pl $func('foo') +*pl $curloc +- start + +# foo +! this is the code of the location-function +local i=0 +- foo +``` + +## `!` (comment) + +`!` — comment statement. What is in the line after the comment statement and until the end of the line is ignored by the interpreter. The comment statement allows you to "comment out" (disable) an unnecessary statement/function temporarily during game debugging. In addition, writing comments to program code is one of the signs of good programming style. + +It is necessary to clearly understand that this is an statement, so if you are commenting some line of code, then `!` should come after `&`: + +```qsp +*pl "Hello, world!" & ! comment +``` + +Comments can be single-line, i.e., end on the same line where the comment statement is located: + +```qsp +! single-line comment +*pl "text string" & ! also a single-line comment +``` + +:::tip[Exception] +The only exception to this rule is writing a comment after a colon in multi-line Statements: + +```qsp +act "Multi-line action": ! comment + *pl "Text on screen" +end +``` + +::: + +Comments can be multi-line. For this, after the comment statement, you need to write quotes, apostrophes, or curly braces. For example: + +```qsp +! "this is the first line of the comment + this is the second line of the comment + this is the third line of the comment +" +``` + +Multi-line comments can take various forms: + +```qsp +! line before quotes " text inside quotes +can move to other lines " as well as { +you can use other character groups to +continue the multi-line comment +} and the comment won't end until the line ends +``` + +## `*CLEAR` + +`*CLEAR` — clears the main description window. Has a short form `*clr`. + +## `*NL` + +`*NL` — line break, then text output in the main description window. General syntax: + +```qsp +*NL [$text] +``` + +where `[$text]` is any text string, number, or expression of any type. If `[$text]` is absent, a simple line break occurs. Example: + +```qsp +*p "Text without line break." +*nl "Line break + text output." +*p "Text without line break." +``` + +## `*P` + +`*P` — text output to the main description window without line break. Text output by any other statement immediately after `*p` will add new text immediately after the current text. General syntax: + +```qsp +*P [$text] +``` + +where `[$text]` is any text string, number, or expression of any type. `[$text]` can be an empty string `''`, but should not be absent. Example: + +```qsp +*p "Text without line break." +*p "Text without line break." +*p "" +*p "Text without line break." +``` + +## `*PL` + +`*PL` — text output to the main description window, then line break. General syntax: + +```qsp +*PL [$text] +``` + +where `[$text]` is any text string, number, or expression of any type. `[$text]` can be absent, then just a line break. Example: + +```qsp +*pl "Text output, then line break." +*pl "Text output, then line break." +*p "Text without line break." +*pl "Text output, then line break." +``` + +You can output text in the same way by simply writing the needed expression instead of this statement. For example, the lines: + +```qsp +*pl $AAA + '989' +*pl 'You are in the park' +*pl 'Preformatted + + string' +``` + +and: + +```qsp +$AAA + '989' +'You are in the park' +'Preformatted + + string' +``` + +will work identically. + +## ACT + +`ACT` — creates and outputs a new action to the actions window. + +General syntax in single-line form: + +```qsp +ACT [$name], [$path to image file]: [statement] & [statement] & [statement] +``` + +General syntax in multi-line form: + +```qsp +ACT [$name], [$path to image file]: + [statement] + [statement] + [statement] +END +``` + +A new action with name `[$name]` and image located at `[$path to image file]` is added to the actions list in the actions window. When the action is clicked, the specified Statements are executed. + +The `[$path to image file]` parameter can be absent, in which case the action is added without an image. + +Examples: + +```qsp +! action in single-line form +act "Pick apple from birch": apple += 1 & *pl "You picked a ripe white apple." + +! action in multi-line form, with image +act "Pick watermelon from bush", "img/watermelon.png": + watermelon += 1 + *pl "You picked a watermelon from the bush" +end +``` + +If there is already an action with the specified name in the actions list, no new action is created, and it does not replace the existing one, the player simply ignores the `act` command. Thus, you cannot output actions with identical names. Example: + +```qsp +act "Action 1": *pl "Old action." +act "Action 1": *pl "New action." +``` + +However, you can simulate actions with identical names in HTML recognition mode by adding HTML tags to action names: + +```qsp +usehtml = 1 +act 'Action 1': *pl "Old action." +act 'Action 1': *pl "New action." +``` + +## ADDOBJ + +`ADDOBJ` — adding a new object to the objects window. General syntax: + +```qsp +ADDOBJ [$name], [$path to image file], [#position] +``` + +where `[$name]` is the object name, `[$path to image file]` is the path to the object's image file (displayed next to the object name), and `[#position]` is the position in the inventory where the object is added. The `[#position]` parameter can be absent. By default, objects are added to the end of the list. Object numbering in the inventory starts from `1`. The `[$path to image file]` parameter can be absent, default value is `''`, in which case the object is added without an image. + +:::note[Allowed but not recommended, deprecated form:] + +```qsp +ADD OBJ [$name],[$path to image file],[#index] +``` + +::: + +You can add objects with the same name, but if you plan to add many identical objects, it's better to use an additional variable to count these objects and add one object to the objects window to avoid cluttering the inventory with a list of 137 Ruble / Cartridge objects: + +```qsp +if obj('Cartridges'): +! if object "Cartridges" is already added, just increase their number + cartridges += 10 +else +! if object "Cartridges" is not yet added, add it and increase the number + addobj 'Cartridges' + cartridges += 10 +end +``` + +You can use arrays indexed by strings to store object counts: + +```qsp +objects['money'] = 12 +objects['cartridges'] = 137 +'Quantity: <>' +``` + +Example of adding an object to the very top of the list (all other objects will shift down): + +```qsp +addobj "Screwdriver", "", 1 +``` + +## CLA + +`CLA` - clearing the list of current actions (removing all actions from the actions window). + +## CLEAR + +`CLEAR` — clears the additional description window. Has a short form `clr`. + +## CLOSE + +`CLOSE` — stops playing the specified sound file. General syntax: + +```qsp +CLOSE [$path to sound file] +``` + +where `[$path to sound file]` is the path to the sound file relative to the game file. If the `[$path to sound file]` parameter is not specified, all sound files stop playing. + +## CLOSE ALL + +`CLOSE ALL` — stops playing all active sound files. Has a short form `close`. + +## CLS + +`CLS` — clears all windows except the objects list. Equivalent to the construction: + +```qsp +clear & *clear & cla & cmdclear +``` + +## CMDCLEAR + +`CMDCLEAR` — clearing the input line. Has a short form `cmdclr`. + +## COPYARR + +`COPYARR` — copying the contents of one array to another. General syntax: + +```qsp +COPYARR [$receiver], [$source], [#start], [#count] +``` + +where: `[$receiver]` is the array to which copying is performed, size and content don't matter; `[$source]` is the array from which copying is performed; `[#start]` is the element number from which to start copying; `[#count]` is how many elements to copy. The `[#count]` parameter is optional; by default — until the end of the source array. The `[#start]` parameter is optional; by default — 0. + +Examples: + +```qsp +! copy all elements of array '$b' to array '$a' +copyarr '$a', '$b' +! at the same time, all elements of array 'b' were also copied to array 'a' + +! copy elements of array 'd' starting from the sixth to array 'c' +copyarr 'c', 'd', 6 + +! copy the first six elements of array 'd' to array 'c' +copyarr 'c', 'd', 0, 6 +``` + +Due to player peculiarities, when copying, for example, numeric array `mass1` to `mass2`, text array `$mass1` is also copied to `$mass2`. + +Other examples: + +```qsp +copyarr $arrname1, $arrname2, 10, 5 +copyarr 'a<<$arrname1>>', 'a<<$arrname2>>' +``` + +## DELACT + +`DELACT` — removes an action from the actions list (if such action exists). General syntax: + +```qsp +DELACT [$name] +``` + +where `[$name]` is the name of the action we want to remove. + +Examples: + +```qsp +! remove action with specific name +delact 'Go forward' +! remove selected action +delact $selact +``` + +:::note[Allowed but not recommended, deprecated form:] + +```qsp +DEL ACT [$name] +``` + +::: + +## DELOBJ + +`DELOBJ` — removing an object from inventory by name (if such object exists). General syntax: + +```qsp +DELOBJ [$name] +``` + +where `[$name]` is the name of the object we want to remove. + +If there are identical objects in the inventory, the command will remove the topmost one with the specified index. + +Examples: + +```qsp +! remove object with specific name +delobj "Screwdriver" +! remove selected object +delobj $selobj +``` + +:::note[Allowed but not recommended, deprecated form:] + +```qsp +DEL OBJ [$name] +``` + +::: + +## DYNAMIC + +`DYNAMIC` — executes code passed as a text string. General syntax: + +```qsp + DYNAMIC([$code], [argument 0], [argument 1], ... , [argument 18]) +``` + +where `[$code]` is regular QSP code written as text. Execution of such code is similar to executing `GOSUB` statement code. Arguments `[argument 0]`, `[argument 1]`, etc. can be used inside `[$code]`, their values are automatically placed in variables `args[0]`, `args[1]`, etc. respectively. After execution, old `args` parameters are restored, then code execution continues from the next command after `dynamic`. + +Examples: + +```qsp +dynamic '$a = "string<<$b>>"' +dynamic '$a' +dynamic 'if $a = "string": "text!"' +dynamic " + $args[0] + addobj $args[1] +", 'Text', 'Fork' +``` + +The following information is also true for the [`dyneval`](qsp-keyword-functions.md#dyneval) function. + +**Important!** If code is specified using apostrophes (`''`) or quotes (`""`), sub-expressions are evaluated in the text: + +```qsp +$args[0] = 'qwerty' +$code = ' + *pl "<<$args[0]>>" + *pl $args[0] +' + +dynamic $code, 'asdfg' +``` + +In this case, when setting the `$code` variable, the sub-expression will be evaluated, so the first line will output 'qwerty', the second line will output 'asdfg'. + +Curly braces are the third type of quotes used specifically for writing dynamic code. Here, bracket nesting is supported, and sub-expressions are not evaluated before code execution: + +```qsp +$args[0]='qwerty' +$code = { + *pl "<<$args[0]>>" + *pl $args[0] +} + +dynamic $code, 'asdfg' +``` + +In this case, two lines 'asdfg' will be output. + +## EXIT + +`EXIT` — termination of the current code block execution (premature exit from subroutine, function, event handler, etc.). + +A code block can be a location, action, code passed to `dynamic` or `dyneval`, or code in a hyperlink. + +Example: + +```qsp +if args[1] = 0: + exit +else + if args[0] mod args[1] = 0: + result = 1 + else + result = 0 + end +end +``` + +:::warning[Attention!!!] +In players version 5.8.0, the `loop` statement appeared. + +The loop body is also considered a separate code block, but the `exit` statement interrupts not only the loop itself, but also the code block in which the loop is located. +::: + +## FREELIB + +`FREELIB` — removes all locations added with the `inclib` statement. + +:::note[5.7.0] +In older player versions, the command was called `dellib` and `killqst`. +::: + +## GOSUB + +`GOSUB` — executing code of the specified location without directly going to it. + +General syntax: + +```qsp +GOSUB [$location],[argument 0],[argument 1], ... ,[argument 8] +``` + +where `[$location]` is the name of the location whose code we want to execute without directly going to it. Arguments `[argument 0]`, `[argument 1]`, etc. can be used on this location, their values are automatically placed in variables `args[0]`, `args[1]`, etc. respectively. After processing the location, previous `args` values are restored. Using arguments is not mandatory. + +When accessing a location via `gosub`, the base description of the location is added to the current description, base actions are added to current actions, and Statements in the "Execute on visit" field are executed, then return to the original line (continuing code execution after `gosub`). + +Examples of calling locations via `gosub`: + +```qsp +!processing location "move". The args[] array is empty. +gosub 'move' + +!processing location with name from variable $location +!One parameter is passed - args[0] equals 1. +gosub $location,1 + +!processing location "move" with passing 3 parameters. +! $args[0] = $var (value), args[1] = 2, +! $args[2] = "data". Note the '$' symbols. +gosub 'move',$var,2,'data' +``` + +Another example: + +```qsp +! this is the code for calling location "transition" +gosub 'transition', 'location' + +! and this is the code of the location "transition" itself +# transition +*pl $args[0] & ! the text 'location' will be output to the screen +! a new action will appear in the actions window: +act 'go': + goto "street" +end +- transition +``` + +The statement has a short form `gs`: + +```qsp +GS [$location], [argument 0], [argument 1], ... , [argument 18] +``` + +## GOTO + +`GOTO` — transition to the specified location. General syntax: + +```qsp +GOTO [$location], [argument 0], [argument 1], ... , [argument 18] +``` + +where `[$location]` is the name of the location to which the transition should be made. Arguments `[argument 0]`, `[argument 1]`, etc. can be used on this location, their values are automatically placed in variables `args[0]`, `args[1]`, etc. respectively. Using arguments is not mandatory. + +When transitioning to a new location using `goto`, the main description window is cleared, as well as the list of current actions, then the base description text is output to the main description window, base actions to the actions window, and code from the "Execute on visit" field of location `[$location]` is executed. Also, when transitioning to a new location, the value returned by the `$curloc` function changes. + +Examples: + +```qsp +! transition to location "house". +! The args array at location "house" will be empty. +goto 'house' + +! transition to location "street" with passing 2 parameters. +! at location "street" args[0] equals 1, +! $args[1] contains string "data". +goto 'street',1,'data' +``` + +The statement has a short form `gt`: + +```qsp +GT [$location],[argument 0],[argument 1], ... ,[argument 8] +``` + +## IF + +`IF` — the main statement for writing conditional constructions. Constructions written using this statement (let's call them "simple conditions") have two forms: single-line and multi-line, and generally look like this: + +General form: + +```qsp +! single-line form +IF [#expression]: {command 1} & {command 2} & ... + +! multi-line form +IF [#expression]: + {command 1} + {command 2} + ... +END +``` + +In this case, if condition `[#expression]` is true, commands `{command 1}`, `{command 2}`, etc. are executed. + +- For **single-line form**, these will be only those commands that are on the same line as the `IF` statement until the end of the line; +- and for **multi-line form**, these will be those commands that are in subsequent lines after the colon and until the special keyword `END`. + +Comparison operations, logical operations, and other expressions returning numeric values can serve as conditions. + +The `END` keyword in multi-line form must be on a separate line. + +If condition `[#expression]` is not true, commands will not be executed. + +Examples of single-line conditional forms: + +```qsp +! if the sum of a and b equals two, +! variable c is assigned value 30 +if a + b = 2: c = 30 +! If there's no orange in inventory, text is output +if no obj("Orange"): pl "You don't have an orange." +! this is also a simple single-line form +if ((a+b)/c)=45+54 or (b<5 or c>45) and no obj 'shovel' and $f=$vvv+'RRRRR': p 'OK' & goto 'Next' +``` + +Examples of multi-line conditional forms: + +```qsp +if library = 0: + learned_about_party = 0 + library_returned = 1 + gt 'library' +end +if a+b=2: + c=30 +end +``` + +:::warning[Pay attention!!!] + +In multi-line form, after the colon on the same line where the IF statement is located, there should be no commands, otherwise the player will consider such a conditional statement single-line, and commands in subsequent lines will be executed in any case, regardless of whether the condition turns out to be true or not. Example of such erroneous notation: + +```qsp +if library = 0: learned_about_party = 0 + library_returned = 1 &! this line will be executed regardless of the condition's truth + gt 'library' &! and this one too +end &! the end keyword is simply ignored +``` + +The exception is the comment statement written after the colon: + +```qsp +if library = 0: ! if haven't visited library + learned_about_party = 0 + library_returned = 1 + gt 'library' +end +``` + +But if the comment is separated by an ampersand, the condition will be considered single-line: + +```qsp +if library = 0: & ! such a comment makes the condition single-line! + learned_about_party = 0 & ! this line will be executed regardless of the condition's truth + library_returned = 1 & ! and this one + gt 'library' &! and this one too +end &! the end keyword is simply ignored +``` + +::: + +For multi-line forms, unlimited depth nesting is allowed. Each nesting level must end with its own `end` line. + +Examples: + +```qsp +if a+b<3 or y=8: + p 'A+B<3 or Y=8' + nl + if j=88: nl & p 'NEXT' + if $h='ooo': + p 'loo' & jump 'lll' + end +end +``` + +```qsp +if a=0: + 'abc1234' + if b=0: '0' else '1' + if j=88: nl & p 'NEXT' + if $h='ooo': + p 'loo' & jump 'lll' + else + p 'sample text' + v=8 + end + 1234 +else + '01234' + g=78 +end +``` + +Several examples of incorrect notation: + +```qsp {4} +! in this case, if the condition is not met, +! the player will ignore only the command `k1=34` +! since it will consider this a single-line condition +if abcd=3: k1=34 + k2=35 & ! this command will always be executed + k3=36 & ! this command will always be executed +end & ! this end will be ignored +``` + +```qsp {3,9} +! this line will output an error unknown action +! since single-line forms should not end with end +if abcd=3: k1=34 else k1=25 end +``` + +## ELSE + +`ELSE` — keyword used together with the `IF` statement, which serves to provide an alternative if the condition is not met. The `ELSE` keyword also has two forms: single-line and multi-line. + +- Multi-line form of `ELSE` can only be used in multi-line construction of the `IF` statement, +- single-line form can be used both in single-line and multi-line constructions of the `IF` statement. General form: + +```qsp +! single-line form +IF [#expression]: {command y1} & {command y2} & ... ELSE {command n1} & {command n2} & ... + +! in multi-line IF: + +! multi-line form of ELSE +IF [#expression]: + {command y1} + {command y2} + ... +ELSE + {command n1} + {command n2} + ... +END + +! single-line form of ELSE +IF [#expression]: + {command y1} + {command y2} + ... +ELSE {command n1} & {command n2} & ... + ! commands in following lines + ! until END are ignored +END +``` + +Here, if condition `[#expression]` is true, commands from the colon to the `ELSE` keyword are executed, and if condition `[#expression]` is not true, commands from the `ELSE` keyword to the end of the conditional construction are executed. + +After `ELSE` you can put or not put a colon. + +**For single-line form:** + +- both commands and the `ELSE` keyword must be written on one line +- the end of the alternative command list is the end of the line. +- if single-line form of `ELSE` is used in multi-line form of `IF`, all commands that follow in subsequent lines after `ELSE` until `END` are ignored. + +Examples of single-line notation: + +```qsp +! if the sum of a and b equals two, variable c is assigned value 30 +! otherwise (i.e., if the sum of a and b does not equal two) +! variable c is assigned value 10 +if a+b=2: c=30 else c=10 + +! depending on whether there's an orange in inventory +! corresponding text is output +if obj("Orange"): pl "You have an orange." else pl "You don't have an orange." + +! single-line form of else inside multi-line if +if $left_hand = 'Great sword': + gosub 'atack', 300 + gosub 'health.prove' + gosub 'win.prove' +else gosub 'atack', atack_power +end +``` + +**For multi-line form:** + +- all commands must be in subsequent lines after `ELSE`; + +Examples of multi-line notation: + +```qsp +if a+b=2: + c=30 +else + c=10 +end + +if obj("Orange"): + pl "You have an orange." +else + pl "You don't have an orange." +end + +if len($curtoken) > 0: + $tokens[curtoken_num] = $curtoken tokens_count = curtoken_num + 1 +else + tokens_count = curtoken_num +end +``` + +## ELSEIF + +`ELSEIF` — keyword used together with the `IF` statement and allows defining sequentially-exclusive conditions at one nesting level. Has single-line and multi-line forms. + +- Multi-line form can only be used in multi-line constructions with the `IF` statement, +- single-line form can be used in both multi-line and single-line constructions with the `IF` statement. + +General forms: + +```qsp +! single-line in single-line condition +IF [#expression 1]: {command set 1} ELSEIF [#expression 2]: {command set 2} ELSE {last command set} + +! multi-line in multi-line condition +IF [#expression 1]: + {command set 1} + ... +ELSEIF [#expression 2]: + {command set 2} + ... +ELSEIF ... : + ... +ELSE + {last command set} + ... +END + +! single-line in multi-line condition +IF [#expression 1]: + {command set 1} + ... +ELSEIF [#expression 2]: {command set 2} +ELSEIF ... : ... +ELSE {last command set} +END +``` + +This works as follows. If `[#expression 1]` is true, commands `{command set 1}` are executed. If `[#expression 1]` is false, but `[#expression 2]` is true, commands `{command set 2}` are executed, and so on. And only if all expressions in the current conditional construction are false, commands after `ELSE` will be executed. The truth of expression `[#expression 1]` does not exclude the truth of expression `[#expression 2]`, but the truth of expression `[#expression 2]` excludes the truth of expression `[#expression 1]`. + +Features of `ELSEIF` notation: + +- The variant `ELSE IF` can be used. Works exactly the same. +- If in multi-line `IF` construction after `ELSEIF` Statements are on the same line (single-line form), then all subsequent lines are ignored until the next `ELSEIF`, or until `ELSE` or `END`. +- In `IF` construction with `ELSEIF`, the part with `ELSE` can be either present or absent. + +Examples: + +```qsp +if obj('Health potion'): health += 100 esleif obj('Apple'): health += 15 else *pl 'Nothing to restore strength!' + +IF POINTS>124: + GOTO 'END3' +ELSEIF POINTS>99: + GOTO 'END4' +ELSE + GOTO 'END5' +END + +if money mod 10=1 and money mod 100<>11: + *pl "You have <> coin." +elseif money mod 10>1 and money mod 10<5 and (money mod 100<5 or money mod 100>20): + *pl "You have <> coins." +elseif money mod 10=0 or money mod 10>4 or (money mod 100>10 and money mod 100<21): + *pl "You have <> coins." +end +``` + +Example of `ELSEIF` notation with Statements on the same line: + +```qsp +! implementing switch/case in QSP +if r = 0: + 'Option 0' + elseif r = 1: 'Option 1' + elseif r = 2: 'Option 2' + elseif r = 3: 'Option 3' + else: 'No options' +end +``` + +:::tip[Note:] + +For better code readability, it's recommended to use constructions with `elseif` only in multi-line form of the `if` statement. + +::: + +## INCLIB + +`INCLIB` — from the specified game file, adds all locations whose names are absent among the current game locations. Loaded locations are fully equivalent to locations from the main game file. General syntax: + +```qsp +INCLIB [$path to game file] +``` + +Example: + +```qsp +inclib "lib/easy.math.qsp" +inclib "lib/easy.title.qsp" +inclib "res/drive.qsp" +inclib "res/base.qsp" +inclib "res/intro.qsp" +``` + +:::note[5.7.0] +In older player versions, the command was called `addqst` and `addlib`. +::: + +## JUMP + +`JUMP` — jump in the current code block to the specified label. General syntax: + +```qsp +JUMP [$label] +``` + +where `[$label]` is a label below or above in the code (see section ["Labels"](qsp-keyword-syntaxems.md#labels-)). + +`jump` finds a label only within the current code block, i.e., labels are local. + +Separate code blocks in QSP are: + +- "Execute on visit" code of a specific location (each location is a separate code block), +- action code even if the action is added programmatically, +- code in a hyperlink, +- `DYNAMIC`/`DYNEVAL` code + +Example: + +```qsp +jump 'End' +p 'This message will not be output' +:end +p 'But this message the user will see' +``` + +:::note[5.7.0] +Using the `jump` statement in older player versions, you could organize loops: + +```qsp +:loop +if s<9: + s=s+1 + pl s + jump 'loop' +end +p 'Done!' +``` + +Double loop with one label: + +```qsp +:loop +if y<9: + if x<9: + *p "<> - " + x=x+1 + jump 'loop' + end + *pl ":<>" + y=y+1 + x=0 + jump 'loop' +end +``` + +Starting from version 5.8.0, the `loop` statement was introduced for loops. +::: + +## KILLALL + +`KILLALL` — destroys all variables and removes all objects from the objects window. Equivalent to the construction: + +```qsp +killvar & killobj +``` + +:::warning[Attention!] +Remember that `killall` is not equivalent to the construction: + +```qsp +killobj & killvar +``` + +since in this case variable values are deleted after object deletion, meaning the object deletion handler location code has time to execute (see `$onobjdel`). +::: + +Usually `killall` is used at the beginning of the game if there's a "Start over" action at the end of the game. + +## KILLOBJ + +`KILLOBJ` — removing an object located at the specified position. General syntax: + +```qsp +KILLOBJ [#number] +``` + +where `[#number]` is the object number in the inventory window. Object numbering starts from 1. If the `[#number]` parameter is not specified, all objects are removed. When removing each object using `killobj`, the object deletion handler location code is executed (see `$onobjdel`). + +Example: + +```qsp +! remove the topmost object in the list +killobj 1 +! remove the bottommost object in the list +killobj countobj +! remove all objects +killobj +``` + +## KILLVAR + +`KILLVAR` — removing the specified array element. General syntax: + +```qsp +KILLVAR [$array name], [element index] +``` + +where `[$array name]` is the name of the array from which we want to remove an element, and `[element index]` is the number, text index, or multi-dimensional index of the array element we want to remove. Array element numbering starts from 0. + +If the element index is not specified, the entire array is cleared. If the statement is called without arguments, all variables and arrays are deleted. + +Examples: + +```qsp +killvar 'a', 3 & ! will delete element with index 3 from array 'a'. +killvar 'unit', 'Paratrooper' & ! deletes element with index 'Paratrooper' from array +killvar 'a' & ! deletes array 'a' +killvar & ! deletes all variables, arrays +killvar '$map_cell', (3, 4) & ! deletion by multi-dimensional index +``` + +When deleting an element, all elements following it shift up one position. + +Example: + +```qsp +a[0] = 4 +a[1] = 3 +a[2] = 23 +a[3] = 15 +KILLVAR 'a', 1 +! now the array looks like this: +! a[0] = 4 +! a[1] = 23 +! a[2] = 15 +``` + +## LET + +`LET` — deprecated statement for setting variables values. General syntax: + +```qsp +LET [variable name] = [expression] +LET [variable 1], [variable 2], ... = [value 1], [value 2], ... +``` + +where `[variable name]` is a valid variable name, `[expression]` is a valid value for this variable. + +- Numeric variable names are written without `$` and `%` symbols at the beginning. +- Text variable names are written with `$` symbol at the beginning. +- Variable names containing tuples are written with `%` symbol at the beginning. + +Examples: + +```qsp +! set text variable +let $text = "text string" +! set numeric variable +let abs = 123 +! set tuple +let %tuple = [123, "text string"] +! multiple assignment +let unit_power, $unit_name = 1300, 'DiggerBull' +! unpack the tuple +let $name, age, height = %npc_fields +``` + +:::tip +This statement is considered deprecated. Use the `set` statement instead, and only in cases when it improves code readability. + +```qsp +! assignment can be done without set or let Statements: +$text = "text string" +``` + +::: + +## LOCAL + +`LOCAL` — declares a local variable (or several variables) in the current code block. + +General syntax: + +```qsp +LOCAL [variable 1], [variable 2], ... +LOCAL [variable 1], [variable 2], ... = [value 1], [value 2], ... +``` + +where `[variable 1]`, `[variable 2]`, etc. are variable/array names written directly (not in quotes), and `[value 1]`, `[value 2]`, etc. are any values, constants, expression values, functions, or other variables. + +The number of variables and values must match (except for unpacking cases). + +```qsp +! declare one local variable +local tempora = 12 +! declare several local variables +local x, y, $item = 11, 19, "Old sword" +! declaration with unpacking +local i, j = %map_cell +local z, $a = [13, '37'] +``` + +Unlike `set` and `let` Statements, you can declare a variable but not assign it a value. + +```qsp +local tempora +local x, y, $item, %map_cell +``` + +However, despite the variable being created, `arrsize` will return `0` for it. I.e., you cannot check if a variable is declared. + +```qsp +local arr +*pl arrsize('arr') & ! will output 0 +``` + +You can create your own local variables in the following code blocks: + +- Locations themselves. +- Code passed to the `DYNAMIC` statement or `DYNEVAL` function as text. +- Code executed when clicking on a hyperlink. +- Code of each separate Action ([ACT](qsp-keywords-statements.md#act)). +- Code of each separate Loop ([LOOP](qsp-keywords-statements.md#loop)) + +:::warning[**Attention!**] +Local variables have one feature that needs to be very clearly understood. The value of a local variable declared in a given code block is translated to all nested or called code blocks from this one. For example, if a local variable is declared on a location, its value is translated to all locations called using `GOSUB` or `FUNC`, to code blocks for `DYNAMIC`/`DYNEVAL`, to loop blocks, and so on. Example: + +```qsp +# start +! from this location we will call location foo +i = 99 & ! declare global variable +gosub 'foo' +*nl i & ! we'll see number 99 on screen +--- start --- + +# foo +! on this location we declare a local variable +local i = 0 +! local variable is translated to the loop +loop while i < 10 step i += 1: + ! in the loop we call location undo + gosub 'undo' + ! and also in the loop we work with the variable + ! declared on location foo +end +*nl i & ! we'll see number 10 on screen +--- foo --- + +# undo +! to this location from the loop on location foo +! the same local variable declared on location foo is translated +i+=1 & ! increase variable value, affecting the value in foo +*p 'undo:<>, ' & ! numbers 1,3,5,7,9 with prefix undo: will appear on screen +--- undo --- +``` + +**However!** Local variable values are not translated to actions (unlike `ARGS` array values at the current location): + +```qsp +$args[0] = 'current location' +local $var = 'local variable' +*pl $args[0] +*pl $var +act "Output values": + *pl $args[0] + *pl $var +end +``` + +::: + +### Examples of local variable assignment + +```qsp title="Two locations, each with its own variable i" +# location 1 +if i = 0: i = 99 & ! variable i value is set only once +*pl "Global i = <>" +act "To location 2": goto 'location 2' +--- location 1 --- + +# location 2 +*pl "Global i = <>" +local i = 137 & ! variable i value is set only once +*pl "Local i = <>" +act "To location 1": goto 'location 1' +--- location 2 --- +``` + +```qsp title="Another example with two locations" +! this code will sequentially output numbers 12, 549 and 99, 549 +# start +x = 99 +z = 4608 +gosub 'foo' +*pl x & *pl z & ! numbers 99 and 549 will be output to screen +--- start --- + +# foo +local x & ! declare variable x local for this location +x = 12 & ! change variable x value +z = 549 +*pl x & *pl z & ! numbers 12 and 549 will be output to screen +--- foo --- +``` + +```qsp title="Example of declaring local variables in DYNEVAL code and in loop" +$chkObjWord = { + ! this is code written as text in variable $chkObjWord + ! in local variable $word we write the word + ! by which we search + local $word = $args[0] + loop local i = 1 while no i > countobj step i += 1: + ! use local variable i inside the loop + ! loop executes while counter doesn't exceed number of objects + if instr($getobj(i), $word) <> 0: + ! as soon as the considered word is found + ! in the name of the next object + result = i & ! return position + exit & ! close function + end + end +} +object_position = dyneval($chkObjWord, 'grenade') +``` + +```qsp title="Local variables can also be declared inside actions" +i=99 +act "Action with local i": + local i = 449933 + *pl i +end +act "Action with global i": + *pl i +end +``` + +## LOOP + +`LOOP` — loop statement. Necessary for organizing cyclic calculations. General syntax of single-line form: + +```qsp +LOOP {commands before loop start} WHILE [condition] STEP {commands at end of iteration}: {loop body Statements} +``` + +General syntax of multi-line form: + +```qsp +LOOP {commands before loop start} WHILE [condition] STEP {commands at end of iteration}: + {loop body Statements} +END +``` + +where: + +- `{commands before loop start}` — these are commands executed before the loop is started. These commands belong to the loop block but don't fall into iterations (passes), i.e., are executed only once. Here you can, for example, declare a loop counter. And here you can write multiple commands, listing them with the `&` (ampersand) separator. +- `[condition]` — this is an expression by whose value the condition is checked. Comparison operations and logical operations in any combinations can be used here. If the value of expression `[condition]` equals zero, the loop is interrupted. +- `{commands at end of iteration}` — these are commands executed at the end of each loop pass. Commands that don't directly relate to the loop body but nevertheless should be executed on each iteration can be placed here. Here you can, for example, change the loop counter value. And here you can actually write multiple commands, listing them with the `&` (ampersand) separator. +- `{loop body Statements}` — these are commands that need to be executed on each pass and are the main ones for the loop. I.e., we make the loop specifically for these commands. + +The loop in QSP is a separate code block, which means we can declare local variables inside this code block. This is very convenient because we can declare a local variable for the counter, and this won't affect other variables at the location: + +```qsp +i = 99 +*pl "i before loop <>" +loop local i = 0 & *p "i in loop: " while i < 6 step i += 1: + *p "<>, " +end +*nl "i after loop <>" +``` + +Loops are very convenient for iterating through arrays. For example, you can use a loop to add all numbers stored in an array: + +```qsp +summ=0 & ! here we'll write the sum of numbers +! our numbers are in array **mass** +loop local i, size = 0, arrsize('mass') while i < size step i += 1: + summ += mass[i] +end +*pl 'Sum of all elements in array mass: <>' +``` + +## MENU + +`MENU` — displays a popup menu anywhere in the game, whose items are written in the specified array. General syntax: + +```qsp +MENU [$array name] +``` + +Before using this statement, you need to fill the array based on whose contents the menu items will be formed. Menu items are tuples of three values, sequentially placed in consecutive array cells starting from zero. The contents of each tuple should be approximately like this: + +```qsp +["menu item name", "location name", "path to icon file"] +``` + +Menu item name is what we'll see on screen when the menu is displayed; location name is the name of the location whose code will be executed when clicking on the corresponding menu item; path to icon file is the path to the image file that will be displayed next to the menu item name. + +Knowing this, we can fill the array to create our menu items: + +```qsp +%stone[0] = ['Take stone', 'takestone'] +%stone[1] = ['Throw stone', 'throwstone'] +%stone[2] = ['Examine stone', 'lookstone'] +``` + +Here the array name (`%stone`) is the menu name, and the tuples are actions for which item names and handler location names for menu item selection are specified. When selecting the "Take stone" item, the location named "takestone" will be called. Similarly for other items. + +To display the menu on screen, use the `MENU` statement: + +```qsp +menu '%stone' +``` + +Example of creating a menu with icons: + +```qsp +! no icon +%usr_menu[0] = ['Take item', 'take_item'] +! icon specified by gif file +%usr_menu[1] = ['Put item', 'put_item', 'images/put_item.gif'] +! icon specified by $icon_file value +%usr_menu[2] = ['Destroy item','del_item', $icon_file] +! menu item specified by 3 variables +%usr_menu[3] = [$name, $location, $icon_file] + +menu 'usr_menu' &! will show menu of 4 items +``` + +The menu ends on an array element with an empty tuple, or with a tuple missing a value for the menu item name or item handler location. + +Examples where the last two menu items won't be created: + +```qsp +%usr_menu[0]=['Take item','take_item'] & ! we'll see this item on screen +$usr_menu[1]=['Examine item','look_item'] & ! and we'll see this item on screen +$usr_menu[2]=[] & ! empty tuple, player will consider menu ended +$usr_menu[3]=['Put item','put_item'] & ! we won't see this item +``` + +```qsp +%usr_menu[0]=['Take item','take_item'] & ! we'll see this item on screen +$usr_menu[1]=['Examine item','look_item'] & ! and we'll see this item on screen +$usr_menu[2]=['destroy item', ''] & ! no handler location specified, won't see item +$usr_menu[3]=['Put item','put_item'] & ! and we won't see this item +``` + +```qsp +%usr_menu[0]=['Take item','take_item'] & ! we'll see this item on screen +$usr_menu[1]=['Examine item','look_item'] & ! and we'll see this item on screen +$usr_menu[2]=['', 'del_item'] & ! no name specified, won't see item +$usr_menu[3]=['Put item','put_item'] & ! and we won't see this item +``` + +To insert a separator in the menu, use a tuple with "-" values. I.e., if you need to put a separator instead of the 3rd element: + +```qsp +%usr_menu[0]=['Take item','take_item'] +$usr_menu[1]=['Examine item','look_item'] +$usr_menu[2]=['-', '-'] & ! separator instead of menu item +$usr_menu[3]=['Put item','put_item'] +``` + +An argument (`args[0]`) - the position of the selected item - is passed to the menu item selection handler location. Menu item positions are numbered from 1. + +:::note[Deprecated array filling variant. Strings] + +This variant can be used both in players version 5.9.0 and in earlier versions. + +Here menu items are string values of an array with a special format: + +```qsp +"menu item name:location name:path to icon file" +``` + +- Menu item name is what we'll see on screen when the menu is displayed; +- location name is the name of the menu item handler location whose code will be executed when clicking on the corresponding menu item; +- path to icon file is the path to the image file that will be displayed next to the menu item name. If the path to icon file is not specified or the specified file is unavailable, the menu item will be displayed without an icon. + +The search for ":" symbols starts from the end of the string, meaning the menu item name can contain colons, but then there must be a colon after the location name, even if you don't use icons for menu items. + +```qsp +$stone[0]='Stone: take:takestone:' +$stone[1]='Stone: throw:throwstone:' +$stone[2]='Stone: examine:lookstone:' +``` + +If the path to icon file is not specified or the specified file is unavailable, the menu item will be displayed without an icon. + +Thus we should fill the array to create our menu items: + +```qsp +$stone[0]='Take stone:takestone' +$stone[1]='Throw stone:throwstone' +$stone[2]='Examine stone:lookstone' +``` + +Here the array name (`$stone`) is the menu name, and the text array values are actions for which names and handler location names for menu item selection are specified. When selecting "Take stone", the location named "takestone" will be processed. Similarly for other items. + +To call the menu on screen, use the `menu` statement: + +```qsp +menu '$stone' +``` + +Menus can be called anywhere in the game, for example, from hyperlinks: + +```qsp +'Stone' +``` + +Example of creating a menu with icons: + +```qsp +! no icon +$usr_menu[0] = 'Take item:take_item' +! icon specified by gif file +$usr_menu[1] = 'Put item:put_item:images/put_item.gif' +! icon specified by $icon_file value +$usr_menu[2] = 'Examine item:look_item:<<$icon_file>>' +! menu item specified by 3 variables +$usr_menu[3] = '<<$name>>:<<$location>>:<<$file>>' + +menu 'usr_menu' &! will show menu of 4 items +``` + +The menu ends on an array element with value `''` (empty string). I.e., if the menu array consists of elements 'Take', 'Examine', '', 'Throw', then the last 2 menu items won't be created: + +```qsp +$usr_menu[0] = 'Take item:take_item' & ! we'll see this item on screen +$usr_menu[1] = 'Examine item:look_item' & ! and we'll see this item on screen +$usr_menu[2] = '' & ! empty value here, player will consider menu ended +$usr_menu[3] = 'Put item:put_item' & ! we won't see this item +``` + +To insert a separator in the menu, write `"-:-"` instead of the corresponding array element. I.e., if you need to put a separator instead of the 3rd element: + +```qsp +$usr_menu[0] = 'Take item:take_item' +$usr_menu[1] = 'Examine item:look_item' +$usr_menu[2] = '-:-' +$usr_menu[3] = 'Put item:put_item' +``` + +::: + +## MSG + +`MSG` — displays the specified message in a dialog box. General syntax: + +```qsp +MSG [message] +``` + +where `[message]` is any text string, number, expression of any type. Examples: + +Examples: + +```qsp +! simple message output. +msg 'Many ripe pears.' +! we get a window with message 'Many ripe pears' +``` + +```qsp +! Example of message in ACT action. +act 'Eat pears': + msg 'Mmm pears are very tasty.' +end +! We get message output when clicking on action "Eat pears" +``` + +```qsp +!Example with condition. +if breadready = 1: + msg 'Looks like the bread is ready.' +end +! We get message output when condition breadready = 1 +``` + +## NL + +`NL` — line break, then text output in the additional description window. General syntax: + +```qsp +NL [$text] +``` + +where `[$text]` is any text string, number, or expression of any type. If `[$text]` is absent, a simple line break occurs. Example: + +```qsp +p "Text without line break." +nl "Line break + text output." +p "Text without line break." +``` + +## OPENGAME + +`OPENGAME` — loading the specified game state file. General syntax: + +```qsp +OPENGAME [$path] +``` + +where `[$path]` is the path to the saved game state file. If the `[$path]` parameter is absent, the game state loading window is called. + +Example: + +```qsp +! load state from file 1.sav +opengame "1.sav" +! open state loading window +opengame +``` + +See also the game state loading event handler location ([$ongload](qsp-keyword-sys-var.md#ongload)). + +## OPENQST + +`OPENQST` — opening and running the specified game file. General syntax: + +```qsp +OPENQST [$path] +``` + +where [$path] is the path to the game file to be run. Example: + +```qsp +openqst "gamespool/cubesgame.qsp" +``` + +When using this statement, variables are not deleted, inventory objects are not removed, the additional description and input line are not cleared, and playing files are not stopped. If you need to clear the screen and all variable values, you can write such commands at the beginning of the loaded game file: + +```qsp +killall & cls & close all +``` + +## P + +`P` — text output to the additional description window without line break. Text output by any other statement immediately after p will add new text immediately after the current text. General syntax: + +```qsp +P [$text] +``` + +where `[$text]` is any text string, number, or expression of any type. `[$text]` can be an empty string `''`, but should not be absent. Example: + +```qsp +p "Text without line break." +p "Text without line break." +p "" +p "Text without line break." +``` + +## PL + +`PL` — text output to the additional description window, then line break. General syntax: + +```qsp +PL [$text] +``` + +where `[$text]` is any text string, number, or expression of any type. `[$text]` can be absent, then just a line break. Example: + +```qsp +pl "Text output, then line break." +pl & ! line break without text output +pl "Text output, then line break." +p "Text without line break." +pl "Text output, then line break." +``` + +## PLAY + +`PLAY` — playing the specified sound file with given volume. General syntax: + +```qsp +PLAY [$path to sound file],[#volume] +``` + +where `[$path to sound file]` is the path to the sound file relative to the game file, `[#volume]` is playback volume as percentage from 0 to 100. The `[#volume]` parameter can be absent, in which case volume is taken as 100%. Examples: + +```qsp +!Volume 100% +play 'sound/music.mp3' +!Volume 50% +play 'sound/music.mp3', 50 +!Volume 0% (no sound) +play 'sound/music.mp3', 0 +``` + +```qsp +!Playing file by address from variable $file +! with extension 'mid' +! and volume volume +$file = "melody" +play '<<$file>>.mid', volume +! similarly: +$file = "melody.mid" +play $file, volume +``` + +If the file is already playing, the volume changes without "restarting" it. Multiple audio formats are supported and simultaneous playback of up to 32 compositions. + +## REFINT + +`REFINT` — forced interface update (including color and font changes assigned using system variables). + +By default, interface update occurs 2 times per second (every 500 ms). See also the [`settimer`](#settimer) statement. + +## SAVEGAME + +`SAVEGAME` — saving game state to the specified file. General syntax: + +```qsp +SAVEGAME [$path] +``` + +where `[$path]` is the path to the created game state save file. If the `[$path]` parameter is absent, the game state save window is called. + +Example: + +```qsp +! save state to file 1.sav +savegame "1.sav" +! open state save window +savegame +``` + +See also [game state save event handler location ($ongsave)](qsp-keyword-sys-var.md#ongsave). + +## SCANSTR + +`SCANSTR` — searching for non-overlapping occurrences in a string that match a pattern, and placing these occurrences in an array. General syntax: + +```qsp +SCANSTR [$array_name], [$text_to_parse], [$regexp], [#group_number] +``` + +where `[$array_name]` is the array where strings matching the regular expression `[$regexp]` are placed. The search is performed on string `[$text_to_parse]`. If parameter `[#group_number]` is specified, not the entire string matching the regular expression will be placed in the array, but only the part corresponding to the specified group in this regular expression. + +Examples: + +```qsp +! extract all words from string: +$text = 'Sasha walked down the highway, and Greka across the river.' +scanstr '$words', $text, '\b\w+\b' +!The $words array will contain values: 'Sasha', 'walked', 'down', 'highway', 'and', 'Greka', 'across', 'river' + +! split string by delimiter: +$text = 'morning|day|evening|night' +scanstr '$words', $text, '[^|]+' +!The $words array will contain values: 'morning', 'day', 'evening', 'night' + +! extract all words placed in square brackets from string, but without square brackets: +$text = '[first] ignoredtext [second][third] also ignored' +scanstr '$words', $text, '\[(.*?)\]', 1 +!The $words array will contain values: 'first', 'second', 'third' +``` + +## SET + +`SET` — statement for setting variables values. General syntax: + +```qsp +SET [variable name] = [expression] +SET [variable 1], [variable 2], ... = [value 1], [value 2], ... +``` + +where `[variable name]` is a valid variable name, `[expression]` is a valid value for this variable. + +Numeric variable names are written without the `$` symbol at the beginning. Text variable names are written with the `$` symbol at the beginning. Examples: + +```qsp +! set text variable +set $text = "text string" +! set numeric variable +set abs = 123 +! set tuple +set %tuple = [27, 184, 'steel'] +! multiple assignment +set unit_power, $unit_name = 1300, 'DiggerBull' +! unpack the tuple +set $name, age, height = %npc_fields +``` + +:::note[Recommendation:] +Since assignment can be done without the `set` statement, we recommend using this statement only for cases when it improves code readability. For example, with multiple assignment: + +```qsp +set apples_in_pocket, apples_in_basket, apples_at_Lyosha = 58, 11, 19 +set $string_1, $string_2 = 'Greka Rode Across River', 'Greka Sees Crab In River' +``` + +::: + +## SETTIMER + +`SETTIMER` — sets the interval for accessing the counter location. General syntax: + +```qsp +SETTIMER [#expression] +``` + +where `[#expression]` is the period of accessing the counter location in milliseconds. By default, the player accesses the counter location every 500 ms, i.e., 2 times per second. + +Setting the counter location access period also affects the frequency of automatic interface settings update. + +Examples: + +```qsp +! counter location will be launched every 2 seconds: +settimer 2000 +``` + +```qsp +! counter location will be launched 4 times per second: +settimer 250 +``` + +```qsp +! if we set frequency of access (times per second) +frequency=10 & ! ten times per second +settimer 1000/frequency +``` + +```qsp +! if we set access period (after how many seconds) +period=2 & ! every two seconds +settimer 1000*period +``` + +The minimum period value can thus be 1 millisecond: + +```qsp +settimer 1 +``` + +However, in practice, the minimum value is limited by your computer's power, and it's usually higher than 1 millisecond. + +## SETVAR + +`SETVAR` — assigns a value to a variable or array cell. + +This function allows avoiding the use of `dynamic` in cases where you need to assign a value to a variable whose name is not known in advance. + +General syntax: + +```qsp +SETVAR [$array_name], [value], [index] +``` + +where `[$array_name]` is the name of the array or variable to which the value should be assigned; `[value]` is a value of any type: string, number, tuple — however, the type of value that will be placed in the variable is determined by the type prefix before the variable name; `[index]` is if the value is assigned to an array cell, you need to specify the cell index with this parameter (can be of any type). + +Examples: + +```qsp +SETVAR 'A', 65 +SETVAR '$X', 'name', 4 +SETVAR '$X', 'name', 'string index' +SETVAR '%Q', ['example', 'tuple'], 3 +SETVAR '%Q', ['example', 'tuple'], [x, y] + +$arr_pref = '%' +$arr_name = 'tuple' +SETVAR $arr_pref+$arr_name, ['tuple', 1], 3 +``` + +## SHOWACTS + +`SHOWACTS` — controls the display of the actions window on screen. General syntax: + +```qsp +SHOWACTS [#expression] +``` + +where `[#expression]` is a number. Usually values `0` and `1` are used. If the value of expression `[#expression]` is not zero, the actions window is displayed. If the value of expression `[#expression]` equals zero, the actions window is hidden. Examples: + +```qsp +showacts 1 & ! shows actions list +showacts 0 & ! hides actions list +``` + +For code readability, you can pre-define `on` and `off` variables and use them: + +```qsp +on = 1 +off = 0 +showacts on & ! shows actions list +showacts off & ! hides actions list +``` + +## SHOWINPUT + +`SHOWINPUT` — controls the display of the input line on screen. General syntax: + +```qsp +SHOWINPUT [#expression] +``` + +where `[#expression]` is a number. Usually values `0` and `1` are used. If the value of expression `[#expression]` is not zero, the input line is displayed. If the value of expression `[#expression]` equals zero, the input line is hidden. Examples: + +```qsp +showinput on & ! shows input line +showinput off & ! hides input line +``` + +## SHOWOBJS + +`SHOWOBJS` — controls the display of inventory on screen. General syntax: + +```qsp +SHOWOBJS [#expression] +``` + +where `[#expression]` is a number. Usually values 0 and 1 are used. If the value of expression `[#expression]` is not zero, inventory is displayed. If the value of expression `[#expression]` equals zero, inventory is hidden. Examples: + +```qsp +showobjs 1 & ! shows inventory +showobjs 0 & ! hides inventory +``` + +For code readability, you can pre-define `on` and `off` variables and use them: + +```qsp +on = 1 +off = 0 +showobjs on & ! shows inventory +showobjs off & ! hides inventory +``` + +## SHOWSTAT + +`SHOWSTAT` — controls the display of the additional description window on screen. General syntax: + +```qsp +SHOWSTAT [#expression] +``` + +where `[#expression]` is a number. Usually values `0` and `1` are used. If the value of expression `[#expression]` is not zero, the additional description window is displayed. If the value of expression `[#expression]` equals zero, the additional description window is hidden. Examples: + +```qsp +showstat 1 & ! shows additional description window +showstat 0 & ! hides additional description window +``` + +For code readability, you can pre-define `on` and `off` variables and use them: + +```qsp +on = 1 +off = 0 +showstat on & ! shows additional description window +showstat off & ! hides additional description window +``` + +## SORTARR + +`SORTARR` — sorting the specified array. General syntax: + +```qsp +SORTARR [$array_name], [#order] +``` + +Here `[$array_name]` is the name of the array to be sorted. The `[#order]` parameter can be omitted. If not specified or equals `0`, sorts the array in ascending order (from smaller to larger). If equals `1`, sorts the array in descending order (from larger to smaller). + +Can sort arrays of any types (numbers, strings, tuples), but mixing values of different types in one array is not allowed. + +To specify the type of sorted values, you need to specify the type prefix as part of the array name (`$`, `%`). + +Example of sorting a text array: + +```qsp +$a[] = 'nn' +$a[] = 'zz' +$a[] = 'aa' +sortarr '$a' + +!check sorting result: +loop local i=0 while i Date: Sat, 16 Aug 2025 21:30:18 +0500 Subject: [PATCH 12/12] docs(lang/kwrds): rename 'qsp-keyword' to 'qsp-keywords' -files. --- ...08-15-docs-add-chapters-of-keywords-etc.md | 4 +- docs/language/qsp-keywords/index.md | 344 +++++++++--------- ...functions.md => qsp-keywords-functions.md} | 10 +- ...operators.md => qsp-keywords-operators.md} | 6 +- ...atements.md => qsp-keywords-statements.md} | 12 +- ...syntaxems.md => qsp-keywords-syntaxems.md} | 6 +- ...ord-sys-var.md => qsp-keywords-sys-var.md} | 0 .../current/language/qsp-keywords/index.md | 344 +++++++++--------- ...functions.md => qsp-keywords-functions.md} | 8 +- ...operators.md => qsp-keywords-operators.md} | 0 ...atements.md => qsp-keywords-statements.md} | 8 +- ...syntaxems.md => qsp-keywords-syntaxems.md} | 0 ...ord-sys-var.md => qsp-keywords-sys-var.md} | 0 13 files changed, 371 insertions(+), 371 deletions(-) rename docs/language/qsp-keywords/{qsp-keyword-functions.md => qsp-keywords-functions.md} (99%) rename docs/language/qsp-keywords/{qsp-keyword-operators.md => qsp-keywords-operators.md} (99%) rename docs/language/qsp-keywords/{qsp-keyword-statements.md => qsp-keywords-statements.md} (99%) rename docs/language/qsp-keywords/{qsp-keyword-syntaxems.md => qsp-keywords-syntaxems.md} (98%) rename docs/language/qsp-keywords/{qsp-keyword-sys-var.md => qsp-keywords-sys-var.md} (100%) rename i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/{qsp-keyword-functions.md => qsp-keywords-functions.md} (99%) rename i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/{qsp-keyword-operators.md => qsp-keywords-operators.md} (100%) rename i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/{qsp-keyword-statements.md => qsp-keywords-statements.md} (99%) rename i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/{qsp-keyword-syntaxems.md => qsp-keywords-syntaxems.md} (100%) rename i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/{qsp-keyword-sys-var.md => qsp-keywords-sys-var.md} (100%) diff --git a/blog/2024-08-15-docs-add-chapters-of-keywords-etc.md b/blog/2024-08-15-docs-add-chapters-of-keywords-etc.md index 2864496..567c14d 100644 --- a/blog/2024-08-15-docs-add-chapters-of-keywords-etc.md +++ b/blog/2024-08-15-docs-add-chapters-of-keywords-etc.md @@ -27,9 +27,9 @@ tags: ::: - Необходимо смириться с тем, что ссылки на `index.md` раздела не будут работать в докузаурусе, либо, если их "обрезать" для докузауруса, не будут работать в обсидиане. Лучше избегать создания разделов `index.md` для комфортной работы и там и там. - Ссылки на файлы статей должны быть относительными (чтобы работать и там и там), и включать так же расширение файлов (`.md`). - `../language/qsp-keywords/qsp-keyword-functions.md` + `../language/qsp-keywords/qsp-keywords-functions.md` :::note[Потому что:] Докузаурус опускает расширение `.md` в ссылках и таким образом в процессе работы ссылки поддерживаются и в обсидиане и в докузаурусе. После сборки ссылки во всех статьях приобретают вид валидный для докузауруса, но невалидный для Обсидиана. - `https://dev.qsp.org/docs/language/qsp-keywords/qsp-keyword-statements` + `https://dev.qsp.org/docs/language/qsp-keywords/qsp-keywords-statements` ::: - Необходимо смириться с тем, что обсидиан не поддерживает те же якоря заголовков, что и докузаурус, из-за чего сослаться на заголовок в обсидиане так же как в докузаурусе невозможно. Это не мешает обсидиану поддерживать такие ссылки при изменении местоположения статей и разделов. diff --git a/docs/language/qsp-keywords/index.md b/docs/language/qsp-keywords/index.md index 3974649..d69a572 100644 --- a/docs/language/qsp-keywords/index.md +++ b/docs/language/qsp-keywords/index.md @@ -9,175 +9,175 @@ sidebar_position: 6 Вычеркнутые команды не работают в плеерах версии 5.8.0 и выше. ::: -- [Неявный оператор](qsp-keyword-statements#неявный-оператор) -- [`!` (комментарий)](qsp-keyword-statements.md#-комментарий) -- [`!` (не равно)](qsp-keyword-operators.md#-не-равно-1) -- [`&` (конкатенация)](qsp-keyword-operators.md#-конкатенация) -- [`&` (перечисление команд)](qsp-keyword-syntaxems.md#амперсанд-) -- [`:` (метки)](qsp-keyword-syntaxems.md#метки-) -- [`,` (разделитель аргументов)](qsp-keyword-syntaxems.md#запятая-) -- [`""` (кавычки)](qsp-keyword-syntaxems.md#кавычка-) -- [`''` (апострофы)](qsp-keyword-syntaxems.md#апостроф-) -- [`{}` (Фигурные скобки)](qsp-keyword-syntaxems.md#фигурные-скобки-) -- [`()` (круглые скобки)](qsp-keyword-syntaxems.md#круглые-скобки-) -- [`[]` (квадратные скобки)](qsp-keyword-syntaxems.md#квадратные-скобки-) -- [`@` (коммерческое "эт")](qsp-keyword-syntaxems#%D1%81%D0%B8%D0%BC%D0%B2%D0%BE%D0%BB-%D0%BA%D0%BE%D0%BC%D0%BC%D0%B5%D1%80%D1%87%D0%B5%D1%81%D0%BA%D0%BE%D0%B5-%D1%8D%D1%82-) - 5.8.0 -- [`$` (знак доллара)](qsp-keyword-syntaxems#%D1%81%D0%B8%D0%BC%D0%B2%D0%BE%D0%BB-%D0%B7%D0%BD%D0%B0%D0%BA-%D0%B4%D0%BE%D0%BB%D0%BB%D0%B0%D1%80%D0%B0-) -- [`%` (знак процента)](qsp-keyword-syntaxems#%D1%81%D0%B8%D0%BC%D0%B2%D0%BE%D0%BB-%D0%B7%D0%BD%D0%B0%D0%BA-%D0%BF%D1%80%D0%BE%D1%86%D0%B5%D0%BD%D1%82%D0%B0-) - 5.9.0 -- [`*`](qsp-keyword-operators.md#-умножение) -- [`*=`](qsp-keyword-operators.md#-умножение-присвоение) -- [`+`](qsp-keyword-operators.md#-сложение) -- [`+=`](qsp-keyword-operators.md#-сложение-присвоение) -- ~~[`+` (унарный)](qsp-keyword-operators.md#--унарный-минус)~~ -- [`-`](qsp-keyword-operators.md#--вычитание) -- [`-=`](qsp-keyword-operators.md#--вычитание-присвоение) -- [`-` (унарный)](qsp-keyword-operators.md#--унарный-минус) -- [`/`](qsp-keyword-operators.md#-деление) -- [`/=`](qsp-keyword-operators.md#-деление-присвоение) -- [`<`](qsp-keyword-operators.md#-меньше) -- [`<=`](qsp-keyword-operators.md#-меньше-либо-равно) -- [`<>`](qsp-keyword-operators.md#-не-равно) -- [`=` (равно)](qsp-keyword-operators.md#-равно) -- [`=` (присвоение)](qsp-keyword-operators.md#-присвоение) -- [`=<`](qsp-keyword-operators.md#-равно-либо-меньше) -- [`=>`](qsp-keyword-operators.md#-равно-или-больше) -- [`>`](qsp-keyword-operators.md#-больше) -- [`>=`](qsp-keyword-operators.md#-больше-либо-равно) -- [`ACT`](qsp-keyword-statements.md#act) -- ~~[`ADDLIB`](qsp-keyword-statements.md#inclib)~~ -- [`ADDOBJ`](qsp-keyword-statements.md#addobj) -- ~~[`ADDQST`](qsp-keyword-statements.md#inclib)~~ -- [`AND`](qsp-keyword-operators.md#and) -- [`ARGS`](qsp-keyword-sys-var.md#args) -- [`ARRCOMP`](qsp-keyword-functions.md#arrcomp) -- [`ARRITEM`](qsp-keyword-functions.md#arritem) - 5.8.0 -- [`ARRPACK`](qsp-keyword-functions.md#arrpack) - 5.9.1 -- [`ARRPOS`](qsp-keyword-functions.md#arrpos) -- [`ARRTYPE`](qsp-keyword-functions.md#arrtype) - 5.9.1 -- [`ARRSIZE`](qsp-keyword-functions.md#arrsize) -- [`$BACKIMAGE`](qsp-keyword-sys-var.md#backimage) -- [`BCOLOR`](qsp-keyword-sys-var.md#bcolor) -- [`CLA`](qsp-keyword-statements.md#cla) -- [`CLEAR`](qsp-keyword-statements.md#clear-1) -- [`*CLEAR`](qsp-keyword-statements.md#clear) -- [`CLOSE`](qsp-keyword-statements.md#close) -- [`CLOSE ALL`](qsp-keyword-statements.md#close-all) -- [`CLR`](qsp-keyword-statements.md#clear-1) -- [`*CLR`](qsp-keyword-statements.md#clear) -- [`CLS`](qsp-keyword-statements.md#cls) -- [`CMDCLEAR`](qsp-keyword-statements.md#cmdclear) -- [`CMDCLR`](qsp-keyword-statements.md#cmdclear) -- [`COPYARR`](qsp-keyword-statements.md#copyarr) -- [`$COUNTER`](qsp-keyword-sys-var.md#counter) -- [`COUNTOBJ`](qsp-keyword-functions.md#countobj) -- [`$CURACTS`](qsp-keyword-functions.md#curacts) -- [`$CURLOC`](qsp-keyword-functions.md#curloc) -- [`$CUROBJS`](qsp-keyword-functions.md#curobjs) - 5.9.0 -- [`DEBUG`](qsp-keyword-sys-var.md#debug) -- [`DELACT`](qsp-keyword-statements.md#delact) -- ~~[`DELLIB`](qsp-keyword-statements.md#freelib)~~ -- [`DELOBJ`](qsp-keyword-statements.md#delobj) -- [`$DESC`](qsp-keyword-functions.md#desc) -- [`DISABLESCROLL`](qsp-keyword-sys-var.md#disablescroll) -- ~~[`DISABLESUBEX`](qsp-keyword-sys-var.md#disablesubex)~~ -- [`DYNAMIC`](qsp-keyword-statements.md#dynamic) -- [`DYNEVAL`](qsp-keyword-functions.md#dyneval) -- [`ELSE`](qsp-keyword-statements.md#else) -- [`ELSEIF`](qsp-keyword-statements.md#elseif) -- [`END`](qsp-keyword-syntaxems.md#end) -- [`EXIT`](qsp-keyword-statements.md#exit) -- [`FCOLOR`](qsp-keyword-sys-var.md#fcolor) -- [`$FNAME`](qsp-keyword-sys-var.md#fname) -- [`FREELIB`](qsp-keyword-statements.md#freelib) - 5.8.0 -- [`FSIZE`](qsp-keyword-sys-var.md#fsize) -- [`FUNC`](qsp-keyword-functions.md#func) -- [`$GETOBJ`](qsp-keyword-functions.md#getobj) -- [`GOSUB`](qsp-keyword-statements.md#gosub) -- [`GOTO`](qsp-keyword-statements.md#goto) -- [`GS`](qsp-keyword-statements.md#gosub) -- [`GT`](qsp-keyword-statements.md#goto) -- [`IF`](qsp-keyword-statements.md#if) -- [`IIF`](qsp-keyword-functions.md#iif) -- [`INCLIB`](qsp-keyword-statements.md#inclib) - 5.8.0 -- [`$INPUT`](qsp-keyword-functions.md#input) -- [`INSTR`](qsp-keyword-functions.md#instr) -- [`ISNUM`](qsp-keyword-functions.md#isnum) -- [`ISPLAY`](qsp-keyword-functions.md#isplay) -- [`JUMP`](qsp-keyword-statements.md#jump) -- [`KILLALL`](qsp-keyword-statements.md#killall) -- [`KILLOBJ`](qsp-keyword-statements.md#killobj) -- ~~[`KILLQST`](qsp-keyword-statements.md#freelib)~~ -- [`KILLVAR`](qsp-keyword-statements.md#killvar) -- [`$LCASE`](qsp-keyword-functions.md#lcase) -- [`LCOLOR`](qsp-keyword-sys-var.md#lcolor) -- [`LEN`](qsp-keyword-functions.md#len) -- [`LET`](qsp-keyword-statements.md#let) -- [`LOC`](qsp-keyword-operators.md#loc) -- [`LOCAL`](qsp-keyword-statements.md#local) - 5.8.0 -- [`LOOP`](qsp-keyword-statements.md#loop) - 5.8.0 -- [`$MAINTXT`](qsp-keyword-functions.md#maintxt) -- [`MAX`](qsp-keyword-functions.md#max) -- [`MENU`](qsp-keyword-statements.md#menu) -- [`$MID`](qsp-keyword-functions.md#mid) -- [`MIN`](qsp-keyword-functions.md#min) -- [`MOD`](qsp-keyword-operators.md#mod) -- [`MSECSCOUNT`](qsp-keyword-functions.md#msecscount) -- [`MSG`](qsp-keyword-statements.md#msg) -- [`NL`](qsp-keyword-statements.md#nl-1) -- [`*NL`](qsp-keyword-statements.md#nl) -- [`NO`](qsp-keyword-operators.md#no) -- [`NOSAVE`](qsp-keyword-sys-var.md#nosave) -- [`OBJ`](qsp-keyword-operators.md#obj) -- [`$ONACTSEL`](qsp-keyword-sys-var.md#onactsel) -- [`$ONGLOAD`](qsp-keyword-sys-var.md#ongload) -- [`$ONGSAVE`](qsp-keyword-sys-var.md#ongsave) -- [`$ONNEWLOC`](qsp-keyword-sys-var.md#onnewloc) -- [`$ONOBJADD`](qsp-keyword-sys-var.md#onobjadd) -- [`$ONOBJDEL`](qsp-keyword-sys-var.md#onobjdel) -- [`$ONOBJSEL`](qsp-keyword-sys-var.md#onobjsel) -- [`OPENGAME`](qsp-keyword-statements.md#opengame) -- [`OPENQST`](qsp-keyword-statements.md#openqst) -- [`OR`](qsp-keyword-operators.md#or) -- [`P`](qsp-keyword-statements.md#p-1) -- [`*P`](qsp-keyword-statements.md#p) -- [`PL`](qsp-keyword-statements.md#pl-1) -- [`*PL`](qsp-keyword-statements.md#pl) -- [`PLAY`](qsp-keyword-statements.md#play) -- [`$QSPVER`](qsp-keyword-functions.md#qspver) -- [`RAND`](qsp-keyword-functions.md#rand) -- [`REFINT`](qsp-keyword-statements.md#refint) -- [`$REPLACE`](qsp-keyword-functions.md#replace) -- [`RESULT`](qsp-keyword-sys-var.md#result) -- [`RGB`](qsp-keyword-functions.md#rgb) -- [`RND`](qsp-keyword-functions.md#rnd) -- [`SAVEGAME`](qsp-keyword-statements.md#savegame) -- [`SCANSTR`](qsp-keyword-statements.md#scanstr) - 5.9.0 -- [`$SELACT`](qsp-keyword-functions.md#selact) -- [`$SELOBJ`](qsp-keyword-functions.md#selobj) -- [`SET`](qsp-keyword-statements.md#set) -- [`SETTIMER`](qsp-keyword-statements.md#settimer) -- [`SETVAR`](qsp-keyword-statements.md#setvar) - 5.9.1 -- [`SHOWACTS`](qsp-keyword-statements.md#showacts) -- [`SHOWINPUT`](qsp-keyword-statements.md#showinput) -- [`SHOWOBJS`](qsp-keyword-statements.md#showobjs) -- [`SHOWSTAT`](qsp-keyword-statements.md#showstat) -- [`SORTARR`](qsp-keyword-statements.md#sortarr) - 5.9.0 -- [`$STATTXT`](qsp-keyword-functions.md#stattxt) -- [`$STR`](qsp-keyword-functions.md#str) -- [`STRCOMP`](qsp-keyword-functions.md#strcomp) -- [`$STRFIND`](qsp-keyword-functions.md#strfind) -- [`STRPOS`](qsp-keyword-functions.md#strpos) -- [`$TRIM`](qsp-keyword-functions.md#trim) -- [`$UCASE`](qsp-keyword-functions.md#ucase) -- [`UNPACKARR`](qsp-keyword-statements.md#unpackarr) - 5.9.1 -- [`UNSEL`](qsp-keyword-statements.md#unselect) -- [`UNSELECT`](qsp-keyword-statements.md#unselect) -- [`USEHTML`](qsp-keyword-sys-var.md#usehtml) -- [`$USERCOM`](qsp-keyword-sys-var.md#usercom) -- [`$USER_TEXT`](qsp-keyword-functions.md#user_text) -- [`$USRTXT`](qsp-keyword-functions.md#user_text) -- [`VAL`](qsp-keyword-functions.md#val) -- [`VIEW`](qsp-keyword-statements.md#view) -- [`WAIT`](qsp-keyword-statements.md#wait) -- [`XGOTO`](qsp-keyword-statements.md#xgoto) -- [`XGT`](qsp-keyword-statements.md#xgoto) +- [Неявный оператор](qsp-keywords-statements#неявный-оператор) +- [`!` (комментарий)](qsp-keywords-statements.md#-комментарий) +- [`!` (не равно)](qsp-keywords-operators.md#-не-равно-1) +- [`&` (конкатенация)](qsp-keywords-operators.md#-конкатенация) +- [`&` (перечисление команд)](qsp-keywords-syntaxems.md#амперсанд-) +- [`:` (метки)](qsp-keywords-syntaxems.md#метки-) +- [`,` (разделитель аргументов)](qsp-keywords-syntaxems.md#запятая-) +- [`""` (кавычки)](qsp-keywords-syntaxems.md#кавычка-) +- [`''` (апострофы)](qsp-keywords-syntaxems.md#апостроф-) +- [`{}` (Фигурные скобки)](qsp-keywords-syntaxems.md#фигурные-скобки-) +- [`()` (круглые скобки)](qsp-keywords-syntaxems.md#круглые-скобки-) +- [`[]` (квадратные скобки)](qsp-keywords-syntaxems.md#квадратные-скобки-) +- [`@` (коммерческое "эт")](qsp-keywords-syntaxems#%D1%81%D0%B8%D0%BC%D0%B2%D0%BE%D0%BB-%D0%BA%D0%BE%D0%BC%D0%BC%D0%B5%D1%80%D1%87%D0%B5%D1%81%D0%BA%D0%BE%D0%B5-%D1%8D%D1%82-) - 5.8.0 +- [`$` (знак доллара)](qsp-keywords-syntaxems#%D1%81%D0%B8%D0%BC%D0%B2%D0%BE%D0%BB-%D0%B7%D0%BD%D0%B0%D0%BA-%D0%B4%D0%BE%D0%BB%D0%BB%D0%B0%D1%80%D0%B0-) +- [`%` (знак процента)](qsp-keywords-syntaxems#%D1%81%D0%B8%D0%BC%D0%B2%D0%BE%D0%BB-%D0%B7%D0%BD%D0%B0%D0%BA-%D0%BF%D1%80%D0%BE%D1%86%D0%B5%D0%BD%D1%82%D0%B0-) - 5.9.0 +- [`*`](qsp-keywords-operators.md#-умножение) +- [`*=`](qsp-keywords-operators.md#-умножение-присвоение) +- [`+`](qsp-keywords-operators.md#-сложение) +- [`+=`](qsp-keywords-operators.md#-сложение-присвоение) +- ~~[`+` (унарный)](qsp-keywords-operators.md#--унарный-минус)~~ +- [`-`](qsp-keywords-operators.md#--вычитание) +- [`-=`](qsp-keywords-operators.md#--вычитание-присвоение) +- [`-` (унарный)](qsp-keywords-operators.md#--унарный-минус) +- [`/`](qsp-keywords-operators.md#-деление) +- [`/=`](qsp-keywords-operators.md#-деление-присвоение) +- [`<`](qsp-keywords-operators.md#-меньше) +- [`<=`](qsp-keywords-operators.md#-меньше-либо-равно) +- [`<>`](qsp-keywords-operators.md#-не-равно) +- [`=` (равно)](qsp-keywords-operators.md#-равно) +- [`=` (присвоение)](qsp-keywords-operators.md#-присвоение) +- [`=<`](qsp-keywords-operators.md#-равно-либо-меньше) +- [`=>`](qsp-keywords-operators.md#-равно-или-больше) +- [`>`](qsp-keywords-operators.md#-больше) +- [`>=`](qsp-keywords-operators.md#-больше-либо-равно) +- [`ACT`](qsp-keywords-statements.md#act) +- ~~[`ADDLIB`](qsp-keywords-statements.md#inclib)~~ +- [`ADDOBJ`](qsp-keywords-statements.md#addobj) +- ~~[`ADDQST`](qsp-keywords-statements.md#inclib)~~ +- [`AND`](qsp-keywords-operators.md#and) +- [`ARGS`](qsp-keywords-sys-var.md#args) +- [`ARRCOMP`](qsp-keywords-functions.md#arrcomp) +- [`ARRITEM`](qsp-keywords-functions.md#arritem) - 5.8.0 +- [`ARRPACK`](qsp-keywords-functions.md#arrpack) - 5.9.1 +- [`ARRPOS`](qsp-keywords-functions.md#arrpos) +- [`ARRTYPE`](qsp-keywords-functions.md#arrtype) - 5.9.1 +- [`ARRSIZE`](qsp-keywords-functions.md#arrsize) +- [`$BACKIMAGE`](qsp-keywords-sys-var.md#backimage) +- [`BCOLOR`](qsp-keywords-sys-var.md#bcolor) +- [`CLA`](qsp-keywords-statements.md#cla) +- [`CLEAR`](qsp-keywords-statements.md#clear-1) +- [`*CLEAR`](qsp-keywords-statements.md#clear) +- [`CLOSE`](qsp-keywords-statements.md#close) +- [`CLOSE ALL`](qsp-keywords-statements.md#close-all) +- [`CLR`](qsp-keywords-statements.md#clear-1) +- [`*CLR`](qsp-keywords-statements.md#clear) +- [`CLS`](qsp-keywords-statements.md#cls) +- [`CMDCLEAR`](qsp-keywords-statements.md#cmdclear) +- [`CMDCLR`](qsp-keywords-statements.md#cmdclear) +- [`COPYARR`](qsp-keywords-statements.md#copyarr) +- [`$COUNTER`](qsp-keywords-sys-var.md#counter) +- [`COUNTOBJ`](qsp-keywords-functions.md#countobj) +- [`$CURACTS`](qsp-keywords-functions.md#curacts) +- [`$CURLOC`](qsp-keywords-functions.md#curloc) +- [`$CUROBJS`](qsp-keywords-functions.md#curobjs) - 5.9.0 +- [`DEBUG`](qsp-keywords-sys-var.md#debug) +- [`DELACT`](qsp-keywords-statements.md#delact) +- ~~[`DELLIB`](qsp-keywords-statements.md#freelib)~~ +- [`DELOBJ`](qsp-keywords-statements.md#delobj) +- [`$DESC`](qsp-keywords-functions.md#desc) +- [`DISABLESCROLL`](qsp-keywords-sys-var.md#disablescroll) +- ~~[`DISABLESUBEX`](qsp-keywords-sys-var.md#disablesubex)~~ +- [`DYNAMIC`](qsp-keywords-statements.md#dynamic) +- [`DYNEVAL`](qsp-keywords-functions.md#dyneval) +- [`ELSE`](qsp-keywords-statements.md#else) +- [`ELSEIF`](qsp-keywords-statements.md#elseif) +- [`END`](qsp-keywords-syntaxems.md#end) +- [`EXIT`](qsp-keywords-statements.md#exit) +- [`FCOLOR`](qsp-keywords-sys-var.md#fcolor) +- [`$FNAME`](qsp-keywords-sys-var.md#fname) +- [`FREELIB`](qsp-keywords-statements.md#freelib) - 5.8.0 +- [`FSIZE`](qsp-keywords-sys-var.md#fsize) +- [`FUNC`](qsp-keywords-functions.md#func) +- [`$GETOBJ`](qsp-keywords-functions.md#getobj) +- [`GOSUB`](qsp-keywords-statements.md#gosub) +- [`GOTO`](qsp-keywords-statements.md#goto) +- [`GS`](qsp-keywords-statements.md#gosub) +- [`GT`](qsp-keywords-statements.md#goto) +- [`IF`](qsp-keywords-statements.md#if) +- [`IIF`](qsp-keywords-functions.md#iif) +- [`INCLIB`](qsp-keywords-statements.md#inclib) - 5.8.0 +- [`$INPUT`](qsp-keywords-functions.md#input) +- [`INSTR`](qsp-keywords-functions.md#instr) +- [`ISNUM`](qsp-keywords-functions.md#isnum) +- [`ISPLAY`](qsp-keywords-functions.md#isplay) +- [`JUMP`](qsp-keywords-statements.md#jump) +- [`KILLALL`](qsp-keywords-statements.md#killall) +- [`KILLOBJ`](qsp-keywords-statements.md#killobj) +- ~~[`KILLQST`](qsp-keywords-statements.md#freelib)~~ +- [`KILLVAR`](qsp-keywords-statements.md#killvar) +- [`$LCASE`](qsp-keywords-functions.md#lcase) +- [`LCOLOR`](qsp-keywords-sys-var.md#lcolor) +- [`LEN`](qsp-keywords-functions.md#len) +- [`LET`](qsp-keywords-statements.md#let) +- [`LOC`](qsp-keywords-operators.md#loc) +- [`LOCAL`](qsp-keywords-statements.md#local) - 5.8.0 +- [`LOOP`](qsp-keywords-statements.md#loop) - 5.8.0 +- [`$MAINTXT`](qsp-keywords-functions.md#maintxt) +- [`MAX`](qsp-keywords-functions.md#max) +- [`MENU`](qsp-keywords-statements.md#menu) +- [`$MID`](qsp-keywords-functions.md#mid) +- [`MIN`](qsp-keywords-functions.md#min) +- [`MOD`](qsp-keywords-operators.md#mod) +- [`MSECSCOUNT`](qsp-keywords-functions.md#msecscount) +- [`MSG`](qsp-keywords-statements.md#msg) +- [`NL`](qsp-keywords-statements.md#nl-1) +- [`*NL`](qsp-keywords-statements.md#nl) +- [`NO`](qsp-keywords-operators.md#no) +- [`NOSAVE`](qsp-keywords-sys-var.md#nosave) +- [`OBJ`](qsp-keywords-operators.md#obj) +- [`$ONACTSEL`](qsp-keywords-sys-var.md#onactsel) +- [`$ONGLOAD`](qsp-keywords-sys-var.md#ongload) +- [`$ONGSAVE`](qsp-keywords-sys-var.md#ongsave) +- [`$ONNEWLOC`](qsp-keywords-sys-var.md#onnewloc) +- [`$ONOBJADD`](qsp-keywords-sys-var.md#onobjadd) +- [`$ONOBJDEL`](qsp-keywords-sys-var.md#onobjdel) +- [`$ONOBJSEL`](qsp-keywords-sys-var.md#onobjsel) +- [`OPENGAME`](qsp-keywords-statements.md#opengame) +- [`OPENQST`](qsp-keywords-statements.md#openqst) +- [`OR`](qsp-keywords-operators.md#or) +- [`P`](qsp-keywords-statements.md#p-1) +- [`*P`](qsp-keywords-statements.md#p) +- [`PL`](qsp-keywords-statements.md#pl-1) +- [`*PL`](qsp-keywords-statements.md#pl) +- [`PLAY`](qsp-keywords-statements.md#play) +- [`$QSPVER`](qsp-keywords-functions.md#qspver) +- [`RAND`](qsp-keywords-functions.md#rand) +- [`REFINT`](qsp-keywords-statements.md#refint) +- [`$REPLACE`](qsp-keywords-functions.md#replace) +- [`RESULT`](qsp-keywords-sys-var.md#result) +- [`RGB`](qsp-keywords-functions.md#rgb) +- [`RND`](qsp-keywords-functions.md#rnd) +- [`SAVEGAME`](qsp-keywords-statements.md#savegame) +- [`SCANSTR`](qsp-keywords-statements.md#scanstr) - 5.9.0 +- [`$SELACT`](qsp-keywords-functions.md#selact) +- [`$SELOBJ`](qsp-keywords-functions.md#selobj) +- [`SET`](qsp-keywords-statements.md#set) +- [`SETTIMER`](qsp-keywords-statements.md#settimer) +- [`SETVAR`](qsp-keywords-statements.md#setvar) - 5.9.1 +- [`SHOWACTS`](qsp-keywords-statements.md#showacts) +- [`SHOWINPUT`](qsp-keywords-statements.md#showinput) +- [`SHOWOBJS`](qsp-keywords-statements.md#showobjs) +- [`SHOWSTAT`](qsp-keywords-statements.md#showstat) +- [`SORTARR`](qsp-keywords-statements.md#sortarr) - 5.9.0 +- [`$STATTXT`](qsp-keywords-functions.md#stattxt) +- [`$STR`](qsp-keywords-functions.md#str) +- [`STRCOMP`](qsp-keywords-functions.md#strcomp) +- [`$STRFIND`](qsp-keywords-functions.md#strfind) +- [`STRPOS`](qsp-keywords-functions.md#strpos) +- [`$TRIM`](qsp-keywords-functions.md#trim) +- [`$UCASE`](qsp-keywords-functions.md#ucase) +- [`UNPACKARR`](qsp-keywords-statements.md#unpackarr) - 5.9.1 +- [`UNSEL`](qsp-keywords-statements.md#unselect) +- [`UNSELECT`](qsp-keywords-statements.md#unselect) +- [`USEHTML`](qsp-keywords-sys-var.md#usehtml) +- [`$USERCOM`](qsp-keywords-sys-var.md#usercom) +- [`$USER_TEXT`](qsp-keywords-functions.md#user_text) +- [`$USRTXT`](qsp-keywords-functions.md#user_text) +- [`VAL`](qsp-keywords-functions.md#val) +- [`VIEW`](qsp-keywords-statements.md#view) +- [`WAIT`](qsp-keywords-statements.md#wait) +- [`XGOTO`](qsp-keywords-statements.md#xgoto) +- [`XGT`](qsp-keywords-statements.md#xgoto) diff --git a/docs/language/qsp-keywords/qsp-keyword-functions.md b/docs/language/qsp-keywords/qsp-keywords-functions.md similarity index 99% rename from docs/language/qsp-keywords/qsp-keyword-functions.md rename to docs/language/qsp-keywords/qsp-keywords-functions.md index 2024deb..ee32c63 100644 --- a/docs/language/qsp-keywords/qsp-keyword-functions.md +++ b/docs/language/qsp-keywords/qsp-keywords-functions.md @@ -119,7 +119,7 @@ dyneval("code = 123 + 890") code ``` -См. также [оператор `DYNAMIC`](qsp-keyword-statements.md#dynamic). +См. также [оператор `DYNAMIC`](qsp-keywords-statements.md#dynamic). ## `$FUNC` @@ -211,7 +211,7 @@ $name_loc = "summ" *pl func($name_loc, 23) & ! выведет на экран 276 ``` -Также см. ["Неявный вызов функции `FUNC`"](qsp-keyword-syntaxems.md#%D1%81%D0%B8%D0%BC%D0%B2%D0%BE%D0%BB-%D0%BA%D0%BE%D0%BC%D0%BC%D0%B5%D1%80%D1%87%D0%B5%D1%81%D0%BA%D0%BE%D0%B5-%D1%8D%D1%82-). +Также см. ["Неявный вызов функции `FUNC`"](qsp-keywords-syntaxems.md#%D1%81%D0%B8%D0%BC%D0%B2%D0%BE%D0%BB-%D0%BA%D0%BE%D0%BC%D0%BC%D0%B5%D1%80%D1%87%D0%B5%D1%81%D0%BA%D0%BE%D0%B5-%D1%8D%D1%82-). ## `$GETOBJ` @@ -563,13 +563,13 @@ act "Съесть яблоко": end ``` -Так же смотрите примеры использования в разделе [`$onactsel`](qsp-keyword-sys-var.md#onactsel) +Так же смотрите примеры использования в разделе [`$onactsel`](qsp-keywords-sys-var.md#onactsel) ## `$SELOBJ` `$SELOBJ` — возвращает название выделенного предмета в любом месте игры. Выделение предмета происходит в момент нажатия (щелчка мышью по предмету) и не снимается до применения команды `unselect`. -Пример использования можно посмотреть в разделе [`$onobjsel`](qsp-keyword-sys-var.md#onobjsel) +Пример использования можно посмотреть в разделе [`$onobjsel`](qsp-keywords-sys-var.md#onobjsel) ## `$STATTXT` @@ -718,7 +718,7 @@ $ucase('Я хочу на вас орать.') & ! вернёт 'Я ХОЧУ НА act "Что я написал?": pl 'Я написал: "<<$user_text>>".' ``` -Более распространённый пример представлен в разделе [`$usercom`](qsp-keyword-sys-var.md#usercom). +Более распространённый пример представлен в разделе [`$usercom`](qsp-keywords-sys-var.md#usercom). ## ARRCOMP diff --git a/docs/language/qsp-keywords/qsp-keyword-operators.md b/docs/language/qsp-keywords/qsp-keywords-operators.md similarity index 99% rename from docs/language/qsp-keywords/qsp-keyword-operators.md rename to docs/language/qsp-keywords/qsp-keywords-operators.md index 8245e0e..f7549de 100644 --- a/docs/language/qsp-keywords/qsp-keyword-operators.md +++ b/docs/language/qsp-keywords/qsp-keywords-operators.md @@ -235,7 +235,7 @@ number *= [4,5] & ! ошибка о несоответствии типов да 37+100 & ! вернёт 137 ``` -При "суммировании" строковых значений производится [конкатенация](qsp-keyword-operators.md#-конкатенация), то есть "склеивание" строк: +При "суммировании" строковых значений производится [конкатенация](qsp-keywords-operators.md#-конкатенация), то есть "склеивание" строк: ```qsp ! на экран будет выведена строка "2627" @@ -283,7 +283,7 @@ warrior = warrior + 15 warrior += 15 ``` -Возможно так же проводить инкремент со строковыми значениями, работает как [конкатенация](qsp-keyword-operators.md#-конкатенация): +Возможно так же проводить инкремент со строковыми значениями, работает как [конкатенация](qsp-keywords-operators.md#-конкатенация): ```qsp $text += " (может быть тут что-то написано)" @@ -1088,7 +1088,7 @@ no [выражение_1] = [выражение_2] ::: :::tip -Не рекомендуется использовать данную операцию для объединения строк, поскольку строки можно объединять через [`+`](qsp-keyword-operators.md#-сложение): +Не рекомендуется использовать данную операцию для объединения строк, поскольку строки можно объединять через [`+`](qsp-keywords-operators.md#-сложение): ```qsp ! на экран будет выведена строка "2627" diff --git a/docs/language/qsp-keywords/qsp-keyword-statements.md b/docs/language/qsp-keywords/qsp-keywords-statements.md similarity index 99% rename from docs/language/qsp-keywords/qsp-keyword-statements.md rename to docs/language/qsp-keywords/qsp-keywords-statements.md index a4ac2f7..51f2290 100644 --- a/docs/language/qsp-keywords/qsp-keyword-statements.md +++ b/docs/language/qsp-keywords/qsp-keywords-statements.md @@ -416,7 +416,7 @@ dynamic " ", 'Текст', 'Вилка' ``` -Нижеследующая информация справедлива и для функции [`dyneval`](qsp-keyword-functions.md#dyneval). +Нижеследующая информация справедлива и для функции [`dyneval`](qsp-keywords-functions.md#dyneval). **Важно!** Если код задан с помощью апострофов (`''`) или кавычек (`""`), в тексте вычисляются подвыражения: @@ -909,7 +909,7 @@ inclib "res/intro.qsp" JUMP [$метка] ``` -, где `[$метка]` — это метка ниже или выше по коду (см. раздел ["Метки"](qsp-keyword-syntaxems.md#метки-)). +, где `[$метка]` — это метка ниже или выше по коду (см. раздел ["Метки"](qsp-keywords-syntaxems.md#метки-)). `jump` находит метку только в пределах текущего блока кода, то есть метки локальны. @@ -1125,8 +1125,8 @@ local arr - Локации сами по себе. - Код, передаваемый оператору `DYNAMIC`, или функции `DYNEVAL`, в виде текста. - Код, выполняемый при нажатии на гиперссылку. -- Код каждого отдельного Действия ([ACT](qsp-keyword-statements.md#act)). -- Код каждого отдельного Цикла ([LOOP](qsp-keyword-statements.md#loop)) +- Код каждого отдельного Действия ([ACT](qsp-keywords-statements.md#act)). +- Код каждого отдельного Цикла ([LOOP](qsp-keywords-statements.md#loop)) :::warning[**Внимание!**] У локальных переменных есть одна особенность, которую нужно очень чётко понимать. Значение объявленной в данном блоке кода локальной переменной транслируется и во все вложенные, или вызванные из данного, блоки кода. Например, если на локации объявлена локальная переменная, то её значение транслируется во все вызываемые с помощью `GOSUB` или `FUNC` локации, в блоки кода для `DYNAMIC`/`DYNEVAL`, в блоки циклов и так далее. Пример: @@ -1519,7 +1519,7 @@ opengame "1.sav" opengame ``` -См. также локацию-обработчик события загрузки состояния игры ([$ongload](qsp-keyword-sys-var.md#ongload)). +См. также локацию-обработчик события загрузки события загрузки состояния игры ([$ongload](qsp-keywords-sys-var.md#ongload)). ## OPENQST @@ -1633,7 +1633,7 @@ savegame "1.sav" savegame ``` -См. также [локацию-обработчик события сохранения состояния игры ($ongsave)](qsp-keyword-sys-var.md#ongsave). +См. также [локацию-обработчик события сохранения состояния игры ($ongsave)](qsp-keywords-sys-var.md#ongsave). ## SCANSTR diff --git a/docs/language/qsp-keywords/qsp-keyword-syntaxems.md b/docs/language/qsp-keywords/qsp-keywords-syntaxems.md similarity index 98% rename from docs/language/qsp-keywords/qsp-keyword-syntaxems.md rename to docs/language/qsp-keywords/qsp-keywords-syntaxems.md index 63c86d2..1ef6aab 100644 --- a/docs/language/qsp-keywords/qsp-keyword-syntaxems.md +++ b/docs/language/qsp-keywords/qsp-keywords-syntaxems.md @@ -91,7 +91,7 @@ end присутствие этого текста после end не одоб ## Метки `:` -Метки — это особые синтаксические конструкции (а вернее меньше, чем конструкции, — синтаксемы), которые отмечают указанную строку кода и служат для быстрого перемещения к таким строкам с помощью оператора [`JUMP`](qsp-keyword-statements.md#jump). Общая запись: +Метки — это особые синтаксические конструкции (а вернее меньше, чем конструкции, — синтаксемы), которые отмечают указанную строку кода и служат для быстрого перемещения к таким строкам с помощью оператора [`JUMP`](qsp-keywords-statements.md#jump). Общая запись: ```qsp :[название метки] @@ -164,7 +164,7 @@ jump "FoR" [команда 1] & [команда 2] & ... ``` -Данный символ не следует путать с [операцией объединения строк](qsp-keyword-operators.md#-конкатенация) (конкатенация), а использовать нужно с осторожностью. +Данный символ не следует путать с [операцией объединения строк](qsp-keywords-operators.md#-конкатенация) (конкатенация), а использовать нужно с осторожностью. Примеры: @@ -455,7 +455,7 @@ end Неявный вызов локации-функции заменяет и `gosub`, и `func`, поэтому: 1. если ваша локация-функция возвращает результат, неявный вызов такой локации будет работать точно так же, как явный вызов через `func`; -2. если же локация-функция не возвращает результат, то при использовании её с **[неявным оператором](qsp-keyword-statements.md#неявный-оператор)** она будет работать, как явный вызов через `gosub`. +2. если же локация-функция не возвращает результат, то при использовании её с **[неявным оператором](qsp-keywords-statements.md#неявный-оператор)** она будет работать, как явный вызов через `gosub`. ::: diff --git a/docs/language/qsp-keywords/qsp-keyword-sys-var.md b/docs/language/qsp-keywords/qsp-keywords-sys-var.md similarity index 100% rename from docs/language/qsp-keywords/qsp-keyword-sys-var.md rename to docs/language/qsp-keywords/qsp-keywords-sys-var.md diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/index.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/index.md index f0596b2..4524695 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/index.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/index.md @@ -9,175 +9,175 @@ sidebar_position: 6 Crossed out commands do not work in players version 5.8.0 and above. ::: -- [Implicit statement](qsp-keyword-statements#implicit-operator) -- [`!` (comment)](qsp-keyword-statements.md#-comment) -- [`!` (not equal)](qsp-keyword-operators.md#-not-equal-1) -- [`&` (concatenation)](qsp-keyword-operators.md#-concatenation) -- [`&` (command enumeration)](qsp-keyword-syntaxems.md#ampersand-) -- [`:` (labels)](qsp-keyword-syntaxems.md#labels-) -- [`,` (argument separator)](qsp-keyword-syntaxems.md#comma-) -- [`""` (quotes)](qsp-keyword-syntaxems.md#quote-) -- [`''` (apostrophes)](qsp-keyword-syntaxems.md#apostrophe-) -- [`{}` (Curly braces)](qsp-keyword-syntaxems.md#curly-braces-) -- [`()` (round brackets)](qsp-keyword-syntaxems.md#round-brackets-) -- [`[]` (square brackets)](qsp-keyword-syntaxems.md#square-brackets-) -- [`@` (commercial "at")](qsp-keyword-syntaxems#commercial-at-symbol-) - 5.8.0 -- [`$` (dollar sign)](qsp-keyword-syntaxems#dollar-sign-symbol-) -- [`%` (percent sign)](qsp-keyword-syntaxems#percent-sign-symbol-) - 5.9.0 -- [`*`](qsp-keyword-operators.md#-multiplication) -- [`*=`](qsp-keyword-operators.md#-multiplication-assignment) -- [`+`](qsp-keyword-operators.md#-addition) -- [`+=`](qsp-keyword-operators.md#-addition-assignment) -- ~~[`+` (unary)](qsp-keyword-operators.md#--unary-minus)~~ -- [`-`](qsp-keyword-operators.md#--subtraction) -- [`-=`](qsp-keyword-operators.md#--subtraction-assignment) -- [`-` (unary)](qsp-keyword-operators.md#--unary-minus) -- [`/`](qsp-keyword-operators.md#-division) -- [`/=`](qsp-keyword-operators.md#-division-assignment) -- [`<`](qsp-keyword-operators.md#-less-than) -- [`<=`](qsp-keyword-operators.md#-less-than-or-equal) -- [`<>`](qsp-keyword-operators.md#-not-equal) -- [`=` (equal)](qsp-keyword-operators.md#-equal) -- [`=` (assignment)](qsp-keyword-operators.md#-assignment) -- [`=<`](qsp-keyword-operators.md#-equal-or-less) -- [`=>`](qsp-keyword-operators.md#-equal-or-greater) -- [`>`](qsp-keyword-operators.md#-greater-than) -- [`>=`](qsp-keyword-operators.md#-greater-than-or-equal) -- [`ACT`](qsp-keyword-statements.md#act) -- ~~[`ADDLIB`](qsp-keyword-statements.md#inclib)~~ -- [`ADDOBJ`](qsp-keyword-statements.md#addobj) -- ~~[`ADDQST`](qsp-keyword-statements.md#inclib)~~ -- [`AND`](qsp-keyword-operators.md#and) -- [`ARGS`](qsp-keyword-sys-var.md#args) -- [`ARRCOMP`](qsp-keyword-functions.md#arrcomp) -- [`ARRITEM`](qsp-keyword-functions.md#arritem) - 5.8.0 -- [`ARRPACK`](qsp-keyword-functions.md#arrpack) - 5.9.1 -- [`ARRPOS`](qsp-keyword-functions.md#arrpos) -- [`ARRTYPE`](qsp-keyword-functions.md#arrtype) - 5.9.1 -- [`ARRSIZE`](qsp-keyword-functions.md#arrsize) -- [`$BACKIMAGE`](qsp-keyword-sys-var.md#backimage) -- [`BCOLOR`](qsp-keyword-sys-var.md#bcolor) -- [`CLA`](qsp-keyword-statements.md#cla) -- [`CLEAR`](qsp-keyword-statements.md#clear-1) -- [`*CLEAR`](qsp-keyword-statements.md#clear) -- [`CLOSE`](qsp-keyword-statements.md#close) -- [`CLOSE ALL`](qsp-keyword-statements.md#close-all) -- [`CLR`](qsp-keyword-statements.md#clear-1) -- [`*CLR`](qsp-keyword-statements.md#clear) -- [`CLS`](qsp-keyword-statements.md#cls) -- [`CMDCLEAR`](qsp-keyword-statements.md#cmdclear) -- [`CMDCLR`](qsp-keyword-statements.md#cmdclear) -- [`COPYARR`](qsp-keyword-statements.md#copyarr) -- [`$COUNTER`](qsp-keyword-sys-var.md#counter) -- [`COUNTOBJ`](qsp-keyword-functions.md#countobj) -- [`$CURACTS`](qsp-keyword-functions.md#curacts) -- [`$CURLOC`](qsp-keyword-functions.md#curloc) -- [`$CUROBJS`](qsp-keyword-functions.md#curobjs) - 5.9.0 -- [`DEBUG`](qsp-keyword-sys-var.md#debug) -- [`DELACT`](qsp-keyword-statements.md#delact) -- ~~[`DELLIB`](qsp-keyword-statements.md#freelib)~~ -- [`DELOBJ`](qsp-keyword-statements.md#delobj) -- [`$DESC`](qsp-keyword-functions.md#desc) -- [`DISABLESCROLL`](qsp-keyword-sys-var.md#disablescroll) -- ~~[`DISABLESUBEX`](qsp-keyword-sys-var.md#disablesubex)~~ -- [`DYNAMIC`](qsp-keyword-statements.md#dynamic) -- [`DYNEVAL`](qsp-keyword-functions.md#dyneval) -- [`ELSE`](qsp-keyword-statements.md#else) -- [`ELSEIF`](qsp-keyword-statements.md#elseif) -- [`END`](qsp-keyword-syntaxems.md#end) -- [`EXIT`](qsp-keyword-statements.md#exit) -- [`FCOLOR`](qsp-keyword-sys-var.md#fcolor) -- [`$FNAME`](qsp-keyword-sys-var.md#fname) -- [`FREELIB`](qsp-keyword-statements.md#freelib) - 5.8.0 -- [`FSIZE`](qsp-keyword-sys-var.md#fsize) -- [`FUNC`](qsp-keyword-functions.md#func) -- [`$GETOBJ`](qsp-keyword-functions.md#getobj) -- [`GOSUB`](qsp-keyword-statements.md#gosub) -- [`GOTO`](qsp-keyword-statements.md#goto) -- [`GS`](qsp-keyword-statements.md#gosub) -- [`GT`](qsp-keyword-statements.md#goto) -- [`IF`](qsp-keyword-statements.md#if) -- [`IIF`](qsp-keyword-functions.md#iif) -- [`INCLIB`](qsp-keyword-statements.md#inclib) - 5.8.0 -- [`$INPUT`](qsp-keyword-functions.md#input) -- [`INSTR`](qsp-keyword-functions.md#instr) -- [`ISNUM`](qsp-keyword-functions.md#isnum) -- [`ISPLAY`](qsp-keyword-functions.md#isplay) -- [`JUMP`](qsp-keyword-statements.md#jump) -- [`KILLALL`](qsp-keyword-statements.md#killall) -- [`KILLOBJ`](qsp-keyword-statements.md#killobj) -- ~~[`KILLQST`](qsp-keyword-statements.md#freelib)~~ -- [`KILLVAR`](qsp-keyword-statements.md#killvar) -- [`$LCASE`](qsp-keyword-functions.md#lcase) -- [`LCOLOR`](qsp-keyword-sys-var.md#lcolor) -- [`LEN`](qsp-keyword-functions.md#len) -- [`LET`](qsp-keyword-statements.md#let) -- [`LOC`](qsp-keyword-operators.md#loc) -- [`LOCAL`](qsp-keyword-statements.md#local) - 5.8.0 -- [`LOOP`](qsp-keyword-statements.md#loop) - 5.8.0 -- [`$MAINTXT`](qsp-keyword-functions.md#maintxt) -- [`MAX`](qsp-keyword-functions.md#max) -- [`MENU`](qsp-keyword-statements.md#menu) -- [`$MID`](qsp-keyword-functions.md#mid) -- [`MIN`](qsp-keyword-functions.md#min) -- [`MOD`](qsp-keyword-operators.md#mod) -- [`MSECSCOUNT`](qsp-keyword-functions.md#msecscount) -- [`MSG`](qsp-keyword-statements.md#msg) -- [`NL`](qsp-keyword-statements.md#nl-1) -- [`*NL`](qsp-keyword-statements.md#nl) -- [`NO`](qsp-keyword-operators.md#no) -- [`NOSAVE`](qsp-keyword-sys-var.md#nosave) -- [`OBJ`](qsp-keyword-operators.md#obj) -- [`$ONACTSEL`](qsp-keyword-sys-var.md#onactsel) -- [`$ONGLOAD`](qsp-keyword-sys-var.md#ongload) -- [`$ONGSAVE`](qsp-keyword-sys-var.md#ongsave) -- [`$ONNEWLOC`](qsp-keyword-sys-var.md#onnewloc) -- [`$ONOBJADD`](qsp-keyword-sys-var.md#onobjadd) -- [`$ONOBJDEL`](qsp-keyword-sys-var.md#onobjdel) -- [`$ONOBJSEL`](qsp-keyword-sys-var.md#onobjsel) -- [`OPENGAME`](qsp-keyword-statements.md#opengame) -- [`OPENQST`](qsp-keyword-statements.md#openqst) -- [`OR`](qsp-keyword-operators.md#or) -- [`P`](qsp-keyword-statements.md#p-1) -- [`*P`](qsp-keyword-statements.md#p) -- [`PL`](qsp-keyword-statements.md#pl-1) -- [`*PL`](qsp-keyword-statements.md#pl) -- [`PLAY`](qsp-keyword-statements.md#play) -- [`$QSPVER`](qsp-keyword-functions.md#qspver) -- [`RAND`](qsp-keyword-functions.md#rand) -- [`REFINT`](qsp-keyword-statements.md#refint) -- [`$REPLACE`](qsp-keyword-functions.md#replace) -- [`RESULT`](qsp-keyword-sys-var.md#result) -- [`RGB`](qsp-keyword-functions.md#rgb) -- [`RND`](qsp-keyword-functions.md#rnd) -- [`SAVEGAME`](qsp-keyword-statements.md#savegame) -- [`SCANSTR`](qsp-keyword-statements.md#scanstr) - 5.9.0 -- [`$SELACT`](qsp-keyword-functions.md#selact) -- [`$SELOBJ`](qsp-keyword-functions.md#selobj) -- [`SET`](qsp-keyword-statements.md#set) -- [`SETTIMER`](qsp-keyword-statements.md#settimer) -- [`SETVAR`](qsp-keyword-statements.md#setvar) - 5.9.1 -- [`SHOWACTS`](qsp-keyword-statements.md#showacts) -- [`SHOWINPUT`](qsp-keyword-statements.md#showinput) -- [`SHOWOBJS`](qsp-keyword-statements.md#showobjs) -- [`SHOWSTAT`](qsp-keyword-statements.md#showstat) -- [`SORTARR`](qsp-keyword-statements.md#sortarr) - 5.9.0 -- [`$STATTXT`](qsp-keyword-functions.md#stattxt) -- [`$STR`](qsp-keyword-functions.md#str) -- [`STRCOMP`](qsp-keyword-functions.md#strcomp) -- [`$STRFIND`](qsp-keyword-functions.md#strfind) -- [`STRPOS`](qsp-keyword-functions.md#strpos) -- [`$TRIM`](qsp-keyword-functions.md#trim) -- [`$UCASE`](qsp-keyword-functions.md#ucase) -- [`UNPACKARR`](qsp-keyword-statements.md#unpackarr) - 5.9.1 -- [`UNSEL`](qsp-keyword-statements.md#unselect) -- [`UNSELECT`](qsp-keyword-statements.md#unselect) -- [`USEHTML`](qsp-keyword-sys-var.md#usehtml) -- [`$USERCOM`](qsp-keyword-sys-var.md#usercom) -- [`$USER_TEXT`](qsp-keyword-functions.md#user_text) -- [`$USRTXT`](qsp-keyword-functions.md#user_text) -- [`VAL`](qsp-keyword-functions.md#val) -- [`VIEW`](qsp-keyword-statements.md#view) -- [`WAIT`](qsp-keyword-statements.md#wait) -- [`XGOTO`](qsp-keyword-statements.md#xgoto) -- [`XGT`](qsp-keyword-statements.md#xgoto) +- [Implicit statement](qsp-keywords-statements#implicit-operator) +- [`!` (comment)](qsp-keywords-statements.md#-comment) +- [`!` (not equal)](qsp-keywords-operators.md#-not-equal-1) +- [`&` (concatenation)](qsp-keywords-operators.md#-concatenation) +- [`&` (command enumeration)](qsp-keywords-syntaxems.md#ampersand-) +- [`:` (labels)](qsp-keywords-syntaxems.md#labels-) +- [`,` (argument separator)](qsp-keywords-syntaxems.md#comma-) +- [`""` (quotes)](qsp-keywords-syntaxems.md#quote-) +- [`''` (apostrophes)](qsp-keywords-syntaxems.md#apostrophe-) +- [`{}` (Curly braces)](qsp-keywords-syntaxems.md#curly-braces-) +- [`()` (round brackets)](qsp-keywords-syntaxems.md#round-brackets-) +- [`[]` (square brackets)](qsp-keywords-syntaxems.md#square-brackets-) +- [`@` (commercial "at")](qsp-keywords-syntaxems#commercial-at-symbol-) - 5.8.0 +- [`$` (dollar sign)](qsp-keywords-syntaxems#dollar-sign-symbol-) +- [`%` (percent sign)](qsp-keywords-syntaxems#percent-sign-symbol-) - 5.9.0 +- [`*`](qsp-keywords-operators.md#-multiplication) +- [`*=`](qsp-keywords-operators.md#-multiplication-assignment) +- [`+`](qsp-keywords-operators.md#-addition) +- [`+=`](qsp-keywords-operators.md#-addition-assignment) +- ~~[`+` (unary)](qsp-keywords-operators.md#--unary-minus)~~ +- [`-`](qsp-keywords-operators.md#--subtraction) +- [`-=`](qsp-keywords-operators.md#--subtraction-assignment) +- [`-` (unary)](qsp-keywords-operators.md#--unary-minus) +- [`/`](qsp-keywords-operators.md#-division) +- [`/=`](qsp-keywords-operators.md#-division-assignment) +- [`<`](qsp-keywords-operators.md#-less-than) +- [`<=`](qsp-keywords-operators.md#-less-than-or-equal) +- [`<>`](qsp-keywords-operators.md#-not-equal) +- [`=` (equal)](qsp-keywords-operators.md#-equal) +- [`=` (assignment)](qsp-keywords-operators.md#-assignment) +- [`=<`](qsp-keywords-operators.md#-equal-or-less) +- [`=>`](qsp-keywords-operators.md#-equal-or-greater) +- [`>`](qsp-keywords-operators.md#-greater-than) +- [`>=`](qsp-keywords-operators.md#-greater-than-or-equal) +- [`ACT`](qsp-keywords-statements.md#act) +- ~~[`ADDLIB`](qsp-keywords-statements.md#inclib)~~ +- [`ADDOBJ`](qsp-keywords-statements.md#addobj) +- ~~[`ADDQST`](qsp-keywords-statements.md#inclib)~~ +- [`AND`](qsp-keywords-operators.md#and) +- [`ARGS`](qsp-keywords-sys-var.md#args) +- [`ARRCOMP`](qsp-keywords-functions.md#arrcomp) +- [`ARRITEM`](qsp-keywords-functions.md#arritem) - 5.8.0 +- [`ARRPACK`](qsp-keywords-functions.md#arrpack) - 5.9.1 +- [`ARRPOS`](qsp-keywords-functions.md#arrpos) +- [`ARRTYPE`](qsp-keywords-functions.md#arrtype) - 5.9.1 +- [`ARRSIZE`](qsp-keywords-functions.md#arrsize) +- [`$BACKIMAGE`](qsp-keywords-sys-var.md#backimage) +- [`BCOLOR`](qsp-keywords-sys-var.md#bcolor) +- [`CLA`](qsp-keywords-statements.md#cla) +- [`CLEAR`](qsp-keywords-statements.md#clear-1) +- [`*CLEAR`](qsp-keywords-statements.md#clear) +- [`CLOSE`](qsp-keywords-statements.md#close) +- [`CLOSE ALL`](qsp-keywords-statements.md#close-all) +- [`CLR`](qsp-keywords-statements.md#clear-1) +- [`*CLR`](qsp-keywords-statements.md#clear) +- [`CLS`](qsp-keywords-statements.md#cls) +- [`CMDCLEAR`](qsp-keywords-statements.md#cmdclear) +- [`CMDCLR`](qsp-keywords-statements.md#cmdclear) +- [`COPYARR`](qsp-keywords-statements.md#copyarr) +- [`$COUNTER`](qsp-keywords-sys-var.md#counter) +- [`COUNTOBJ`](qsp-keywords-functions.md#countobj) +- [`$CURACTS`](qsp-keywords-functions.md#curacts) +- [`$CURLOC`](qsp-keywords-functions.md#curloc) +- [`$CUROBJS`](qsp-keywords-functions.md#curobjs) - 5.9.0 +- [`DEBUG`](qsp-keywords-sys-var.md#counter) +- [`DELACT`](qsp-keywords-statements.md#delact) +- ~~[`DELLIB`](qsp-keywords-statements.md#freelib)~~ +- [`DELOBJ`](qsp-keywords-statements.md#delobj) +- [`$DESC`](qsp-keywords-functions.md#desc) +- [`DISABLESCROLL`](qsp-keywords-sys-var.md#disablescroll) +- ~~[`DISABLESUBEX`](qsp-keywords-sys-var.md#disablesubex)~~ +- [`DYNAMIC`](qsp-keywords-statements.md#dynamic) +- [`DYNEVAL`](qsp-keywords-functions.md#dyneval) +- [`ELSE`](qsp-keywords-statements.md#else) +- [`ELSEIF`](qsp-keywords-statements.md#elseif) +- [`END`](qsp-keywords-syntaxems.md#end) +- [`EXIT`](qsp-keywords-statements.md#exit) +- [`FCOLOR`](qsp-keywords-sys-var.md#fcolor) +- [`$FNAME`](qsp-keywords-sys-var.md#fname) +- [`FREELIB`](qsp-keywords-statements.md#freelib) - 5.8.0 +- [`FSIZE`](qsp-keywords-sys-var.md#fsize) +- [`FUNC`](qsp-keywords-functions.md#func) +- [`$GETOBJ`](qsp-keywords-functions.md#getobj) +- [`GOSUB`](qsp-keywords-statements.md#gosub) +- [`GOTO`](qsp-keywords-statements.md#goto) +- [`GS`](qsp-keywords-statements.md#gosub) +- [`GT`](qsp-keywords-statements.md#goto) +- [`IF`](qsp-keywords-statements.md#if) +- [`IIF`](qsp-keywords-functions.md#iif) +- [`INCLIB`](qsp-keywords-statements.md#inclib) - 5.8.0 +- [`$INPUT`](qsp-keywords-functions.md#input) +- [`INSTR`](qsp-keywords-functions.md#instr) +- [`ISNUM`](qsp-keywords-functions.md#isnum) +- [`ISPLAY`](qsp-keywords-functions.md#isplay) +- [`JUMP`](qsp-keywords-statements.md#jump) +- [`KILLALL`](qsp-keywords-statements.md#killall) +- [`KILLOBJ`](qsp-keywords-statements.md#killobj) +- ~~[`KILLQST`](qsp-keywords-statements.md#freelib)~~ +- [`KILLVAR`](qsp-keywords-statements.md#killvar) +- [`$LCASE`](qsp-keywords-functions.md#lcase) +- [`LCOLOR`](qsp-keywords-sys-var.md#lcolor) +- [`LEN`](qsp-keywords-functions.md#len) +- [`LET`](qsp-keywords-statements.md#let) +- [`LOC`](qsp-keywords-operators.md#loc) +- [`LOCAL`](qsp-keywords-statements.md#local) - 5.8.0 +- [`LOOP`](qsp-keywords-statements.md#loop) - 5.8.0 +- [`$MAINTXT`](qsp-keywords-functions.md#maintxt) +- [`MAX`](qsp-keywords-functions.md#max) +- [`MENU`](qsp-keywords-statements.md#menu) +- [`$MID`](qsp-keywords-functions.md#mid) +- [`MIN`](qsp-keywords-functions.md#min) +- [`MOD`](qsp-keywords-operators.md#mod) +- [`MSECSCOUNT`](qsp-keywords-functions.md#msecscount) +- [`MSG`](qsp-keywords-statements.md#msg) +- [`NL`](qsp-keywords-statements.md#nl-1) +- [`*NL`](qsp-keywords-statements.md#nl) +- [`NO`](qsp-keywords-operators.md#no) +- [`NOSAVE`](qsp-keywords-sys-var.md#nosave) +- [`OBJ`](qsp-keywords-operators.md#obj) +- [`$ONACTSEL`](qsp-keywords-sys-var.md#onactsel) +- [`$ONGLOAD`](qsp-keywords-sys-var.md#ongload) +- [`$ONGSAVE`](qsp-keywords-sys-var.md#ongsave) +- [`$ONNEWLOC`](qsp-keywords-sys-var.md#onnewloc) +- [`$ONOBJADD`](qsp-keywords-sys-var.md#onobjadd) +- [`$ONOBJDEL`](qsp-keywords-sys-var.md#onobjdel) +- [`$ONOBJSEL`](qsp-keywords-sys-var.md#onobjsel) +- [`OPENGAME`](qsp-keywords-statements.md#opengame) +- [`OPENQST`](qsp-keywords-statements.md#openqst) +- [`OR`](qsp-keywords-operators.md#or) +- [`P`](qsp-keywords-statements.md#p-1) +- [`*P`](qsp-keywords-statements.md#p) +- [`PL`](qsp-keywords-statements.md#pl-1) +- [`*PL`](qsp-keywords-statements.md#pl) +- [`PLAY`](qsp-keywords-statements.md#play) +- [`$QSPVER`](qsp-keywords-functions.md#qspver) +- [`RAND`](qsp-keywords-functions.md#rand) +- [`REFINT`](qsp-keywords-statements.md#refint) +- [`$REPLACE`](qsp-keywords-functions.md#replace) +- [`RESULT`](qsp-keywords-sys-var.md#result) +- [`RGB`](qsp-keywords-functions.md#rgb) +- [`RND`](qsp-keywords-functions.md#rnd) +- [`SAVEGAME`](qsp-keywords-statements.md#savegame) +- [`SCANSTR`](qsp-keywords-statements.md#scanstr) - 5.9.0 +- [`$SELACT`](qsp-keywords-functions.md#selact) +- [`$SELOBJ`](qsp-keywords-functions.md#selobj) +- [`SET`](qsp-keywords-statements.md#set) +- [`SETTIMER`](qsp-keywords-statements.md#settimer) +- [`SETVAR`](qsp-keywords-statements.md#setvar) - 5.9.1 +- [`SHOWACTS`](qsp-keywords-statements.md#showacts) +- [`SHOWINPUT`](qsp-keywords-statements.md#showinput) +- [`SHOWOBJS`](qsp-keywords-statements.md#showobjs) +- [`SHOWSTAT`](qsp-keywords-statements.md#showstat) +- [`SORTARR`](qsp-keywords-statements.md#sortarr) - 5.9.0 +- [`$STATTXT`](qsp-keywords-functions.md#stattxt) +- [`$STR`](qsp-keywords-functions.md#str) +- [`STRCOMP`](qsp-keywords-functions.md#strcomp) +- [`$STRFIND`](qsp-keywords-functions.md#strfind) +- [`STRPOS`](qsp-keywords-functions.md#strpos) +- [`$TRIM`](qsp-keywords-functions.md#trim) +- [`$UCASE`](qsp-keywords-functions.md#ucase) +- [`UNPACKARR`](qsp-keywords-statements.md#unpackarr) - 5.9.1 +- [`UNSEL`](qsp-keywords-statements.md#unselect) +- [`UNSELECT`](qsp-keywords-statements.md#unselect) +- [`USEHTML`](qsp-keywords-sys-var.md#usehtml) +- [`$USERCOM`](qsp-keywords-sys-var.md#usercom) +- [`$USER_TEXT`](qsp-keywords-functions.md#user_text) +- [`$USRTXT`](qsp-keywords-functions.md#user_text) +- [`VAL`](qsp-keywords-functions.md#val) +- [`VIEW`](qsp-keywords-statements.md#view) +- [`WAIT`](qsp-keywords-statements.md#wait) +- [`XGOTO`](qsp-keywords-statements.md#xgoto) +- [`XGT`](qsp-keywords-statements.md#xgoto) diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keywords-functions.md similarity index 99% rename from i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md rename to i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keywords-functions.md index 0cf4d2c..2a27e9e 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-functions.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keywords-functions.md @@ -211,7 +211,7 @@ $name_loc = "summ" *pl func($name_loc, 23) & ! will output 276 to screen ``` -Also see ["Implicit `FUNC` function call"](qsp-keyword-syntaxems#commercial-at-symbol-). +Also see ["Implicit `FUNC` function call"](qsp-keywords-syntaxems#commercial-at-symbol-). ## `$GETOBJ` @@ -561,13 +561,13 @@ act "Eat apple": end ``` -Also see usage examples in the [`$onactsel`](qsp-keyword-sys-var.md#onactsel) section +Also see usage examples in the [`$onactsel`](qsp-keywords-sys-var.md#onactsel) section ## `$SELOBJ` `$SELOBJ` — returns the name of the selected object anywhere in the game. Object selection occurs when clicking (mouse click on object) and is not removed until the `unselect` command is applied. -Usage examples can be found in the [`$onobjsel`](qsp-keyword-sys-var.md#onobjsel) section +Usage examples can be found in the [`$onobjsel`](qsp-keywords-sys-var.md#onobjsel) section ## `$STATTXT` @@ -716,7 +716,7 @@ Example of an action that will output text entered in the input line to the addi act "What did I write?": pl 'I wrote: "<<$user_text>>".' ``` -A more common example is presented in the [`$usercom`](qsp-keyword-sys-var.md#usercom) section. +A more common example is presented in the [`$usercom`](qsp-keywords-sys-var.md#usercom) section. ## ARRCOMP diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keywords-operators.md similarity index 100% rename from i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-operators.md rename to i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keywords-operators.md diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-statements.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keywords-statements.md similarity index 99% rename from i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-statements.md rename to i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keywords-statements.md index 523a217..c9a3788 100644 --- a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-statements.md +++ b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keywords-statements.md @@ -416,7 +416,7 @@ dynamic " ", 'Text', 'Fork' ``` -The following information is also true for the [`dyneval`](qsp-keyword-functions.md#dyneval) function. +The following information is also true for the [`dyneval`](qsp-keywords-functions.md#dyneval) function. **Important!** If code is specified using apostrophes (`''`) or quotes (`""`), sub-expressions are evaluated in the text: @@ -909,7 +909,7 @@ In older player versions, the command was called `addqst` and `addlib`. JUMP [$label] ``` -where `[$label]` is a label below or above in the code (see section ["Labels"](qsp-keyword-syntaxems.md#labels-)). +where `[$label]` is a label below or above in the code (see section ["Labels"](qsp-keywords-syntaxems.md#labels-)). `jump` finds a label only within the current code block, i.e., labels are local. @@ -1518,7 +1518,7 @@ opengame "1.sav" opengame ``` -See also the game state loading event handler location ([$ongload](qsp-keyword-sys-var.md#ongload)). +See also the game state loading event handler location ([$ongload](qsp-keywords-sys-var.md#ongload)). ## OPENQST @@ -1632,7 +1632,7 @@ savegame "1.sav" savegame ``` -See also [game state save event handler location ($ongsave)](qsp-keyword-sys-var.md#ongsave). +See also [game state save event handler location ($ongsave)](qsp-keywords-sys-var.md#ongsave). ## SCANSTR diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-syntaxems.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keywords-syntaxems.md similarity index 100% rename from i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-syntaxems.md rename to i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keywords-syntaxems.md diff --git a/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-sys-var.md b/i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keywords-sys-var.md similarity index 100% rename from i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keyword-sys-var.md rename to i18n/en/docusaurus-plugin-content-docs/current/language/qsp-keywords/qsp-keywords-sys-var.md