Використання змінних

Далі описано основне використання змінних у LibreOffice Basic.

Угоди про назви для ідентифікаторів змінних

Назва змінної може складатися із не більше, ніж 255 символів. Першим символом назви змінної має бути одна з літер A-Z або a-z. Також у назві змінної дозволяється використовувати цифри, однак застосування знаків пунктуації та спеціальних символів не допускається, за винятком знаку підкреслення ("_"). У ідентифікаторах змінних LibreOffice Basic регістр не враховується. Назви змінних можуть містити пробіли, але в такому випадку вони обов'язково повинні бути поміщені у квадратні дужки.

Приклади ідентифікаторів змінних:


    MyNumber=5      'Correct'
    MyNumber5=15    'Correct'
    MyNumber_5=20   'Correct'
    My Number=20    'Not valid, variable with space must be enclosed in square brackets'
    [My Number]=12  'Correct'
    DéjàVu=25       'Not valid, special characters are not allowed'
    5MyNumber=12    'Not valid, variable may not begin with a number'
    Number,Mine=12  'Not valid, punctuation marks are not allowed'

Оголошення змінних

У LibreOffice Basic оголошення змінних може бути неявним. Оголосити змінну можна за допомогою інструкції Dim. Можна оголошувати декілька змінних одночасно, якщо розділити їх назви комами. Для визначення типу змінної служить або знак оголошення типу після назви, або відповідне ключове слово.

Приклади оголошення змінних:


    Dim a$               'Declares the variable "a" as a String'
    Dim a As String      'Declares the variable "a" as a String'
    Dim a$, b As Integer 'Declares one variable as a String and one as an Integer'
    Dim c As Boolean     'Declares c as a Boolean variable that can be TRUE or FALSE'
warning

Після оголошення типу змінної не можна задати змінну іншого типу з таким же ім'ям!


When you declare multiple variables in a single line of code you need to specify the type of each variable. If the type of a variable is not explicitly specified, then Basic will assume that the variable is of the Variant type.


  ' Both variables "a" and "b" are of the Integer type
  Dim a As Integer, b As Integer
  ' Variable "c" is a Variant and "d" is an Integer
  Dim c, d As Integer
  ' A variable can also be explicitly declared as a Variant
  Dim e As Variant, f As Double
note

The Variant type is a special data type that can store any kind of value. To learn more, refer to the section The Variant type below.


Примусове оголошення змінних

Для примусового оголошення змінних служить така команда:


Option Explicit

Інструкція Option Explicit повинна бути першим рядком модуля, до першої підпрограми (SUB). Зазвичай явного оголошення потребують тільки масиви. Всі інші змінні оголошуються відповідно до символу оголошення типу або, якщо він пропущений, змінній призначається стандартний тип Single (число з одинарною точністю).

Типи змінних

У LibreOffice Basic передбачена підтримка чотирьох класів змінних:

Змінні типу Integer

Змінні типу Integer можуть мати значення від -32768 до 32767. Якщо змінній типу Integer присвоюється значення з плаваючою крапкою, десяткові розряди округлюються до наступного цілого числа. Змінні типу Integer зручні для швидких обчислень у процедурах і придатні для змінних лічильника в циклах. Для змінної типу Integer потрібно всього два байти пам'яті. "%" - символ оголошення типу.


Dim Variable%
Dim Variable As Integer

Змінні типу Long Integer

Змінні типу Long Integer можуть мати значення від -2 147 483 648 до 2 147 483 647. Якщо змінній цього типу присвоюється значення з рухомою комою, десяткові розряди округлюються до наступного цілого числа. Такі змінні зручні для швидких обчислень у процедурах і придатні для змінних лічильника в циклах при використанні великих значень. Для змінної цього типу потрібно чотири байти пам'яті. "&" - символ оголошення типу.


Dim Variable&
Dim Variable As Long

Десяткові змінні

Десяткові змінні можуть приймати додатні або від'ємні значення або нуль. Точність - до 29 цифр.

Можна використовувати знаки плюс (+) або мінус (-) в якості префіксів для десяткових чисел (з пропусками або без).

Якщо десяткове число присвоєно цілій змінній, то LibreOffice Basic здійснює округлення в більшу або меншу сторону.

Змінні типу Single

Single variables can take positive or negative values ranging from 3.402823 x 10E38 to 1.401298 x 10E-45. Single variables are floating-point variables, in which the decimal precision decreases as the non-decimal part of the number increases. Single variables are suitable for mathematical calculations of average precision. Calculations require more time than for Integer variables, but are faster than calculations with Double variables. A Single variable requires 4 bytes of memory. The type-declaration character is "!".


Dim Variable!
Dim Variable As Single

Змінні типу Double

Double variables can take positive or negative values ranging from 1.79769313486232 x 10E308 to 4.94065645841247 x 10E-324. Double variables are floating-point variables, in which the decimal precision decreases as the non-decimal part of the number increases. Double variables are suitable for precise calculations. Calculations require more time than for Single variables. A Double variable requires 8 bytes of memory. The type-declaration character is "#".


Dim Variable#
Dim Variable As Double

Змінні типу Currency

Змінні типу Currency зберігаються у внутрішній пам'яті як 64-розрядні числа (8 байт) і відображаються як числа з фіксованим числом розрядів - 15 знаків в цілій частині і 4 знаки в десятковій. Діапазон значень включає числа від -922337203685477.5808 до +922337203685477.5807. Змінні типу Currency застосовуються в розрахунках грошових значень високої точності. Символом опису типу є "@".


Dim Variable@
Dim Variable As Currency

Literals for integers

Numbers can be encoded using octal and hexadecimal forms.


  xi = &o13 '    8 + 3
  ci = &h65 ' 6*16 + 5
  MAX_Integer =  &o77777 '  32767 = &h7FFF
  MIN_Integer = &o100000 ' -32768 = &h8000
  MAX_Long = &h7fffffff '  2147483647 = &o17777777777
  MIN_Long = &h80000000 ' -2147483648 = &o20000000000

Змінні типу String

String variables can hold character strings with up to 2,147,483,648 characters. Each character is stored as the corresponding Unicode value. String variables are suitable for word processing within programs and for temporary storage of any non-printable character up to a maximum length of 2 Gbytes. The memory required for storing string variables depends on the number of characters in the variable. The type-declaration character is "$".

tip

In BASIC String functions, the first character of the string has index 1.



Dim Variable$
Dim Variable As String

Логічні змінні

Бульові або логічні змінні містять лише одне із двох значень: TRUE - істина або FALSE - хибність. Число 0 відповідає значенню FALSE, а усі інші значення відповідають TRUE.


Dim Variable As Boolean

Змінні типу Date

Змінні типу Date можуть містити тільки значення дати і часу, збережені у внутрішньому форматі. Значення, присвоєні змінним типу Date зі значенням Dateserial, Datevalue, Timeserial, або Timevalue, автоматично перетворюються у внутрішній формат. Змінні типу Date перетворюються у звичайні числа з допомогою функцій Day, Month, Year, або Hour, Minute, Second. Внутрішній формат дозволяє порівнювати значення дати і часу шляхом розрахунку різниці двох чисел. Ці змінні можуть бути описані тільки з допомогою ключового слова Date.


Dim Variable As Date

Literals for Dates

Date literals allow to specify unambiguous date variables that are independent from the current language. Literals are enclosed between hash signs #. Possible formats are:


  start_date = #12/30/1899# ' = 1
  dob = #2010-09-28#

The Variant type

Variables declared as Variant can handle any data type. This means that the actual data type is defined during runtime as a value is assigned to the variable.

There are three main ways to create a Variant variable, as shown below:


  Dim varA            ' The type is not specified, hence the variable is a Variant
  Dim varB as Variant ' The variable is explicitly declared as a Variant
  varC = "abc"        ' Previously undeclared variables are treated as Variants

The example below uses the TypeName function to show how the type of a Variant variable changes upon assignment.


  Dim myVar As Variant
  MsgBox TypeName(myVar) ' Empty
  myVar = "Hello!"
  MsgBox TypeName(myVar) ' String
  myVar = 10
  MsgBox TypeName(myVar) ' Integer
note

A Variant variable is initialized with the Empty special data type. You can use the IsEmpty function to test if a variable is an Empty Variant.


You can also use the keyword Any to declare a variable as a Variant. However, Any is deprecated and is available for backward compatibility.

warning

Arguments with type Variant or Any passed in function calls are not checked for their types.



  Dim myVar As Any ' Variable "myVar" is a Variant

Початкові значення змінних

Після оголошення змінної їй автоматично присвоюється значення "Null". Прийнято такі домовленості:

Числовим змінним автоматично присвоюється значення "0" після їхнього оголошення.

Змінним дат присвоюється внутрішнє значення 0, еквівалентне перетворенню значення "0" з допомогою функції Day, Month, Year, або Hour, Minute, Second.

Рядковим змінним присвоюється порожній рядок ("") при оголошенні.

Масиви

LibreOffice Basic розуміє одно - і багатовимірні масиви, які визначаються за допомогою заданого типу змінної. Масиви застосовуються для зміни списків і таблиць у програмах. До окремих елементів масиву можна звертатися за допомогою числового індексу.

Масиви потрібно оголошувати за допомогою інструкції Dim. Для визначення діапазону індексів масиву використовується кілька способів:


    Dim Text$(20)       '21 elements numbered from 0 to 20'
    Dim Text$(5,4)      '30 elements (a matrix of 6 x 5 elements)'
    Dim Text$(5 To 25)  '21 elements numbered from 5 to 25'
    Dim Text$(-15 To 5) '21 elements (including 0), numbered from -15 to 5'

Діапазон індексів може включати додатні та від'ємні числа.

Сталі

Сталі мають фіксоване значення. Вони визначаються в програмі лише один раз і не можуть бути перевизначені пізніше:


Const ConstName=Expression

Будь ласка, підтримайте нас!