Jump to content

Recommended Posts

Lua scripts

A script written in Lua does not have any special function from which to start its execution. A script can be thought of simply as a set of commands (instructions) that are executed starting from the first instruction.

A script can be either very simple, consisting of just one command, or very complex, containing tens, hundreds or even thousands of instructions. Consecutive instructions can be separated by semicolons (;). However, this requirement is optional, so all of the code below is syntactically correct:

a = 1; b = 2

a = 1 b = 2

a = 1;

b = 2;

a = 1

b = 2

Working with variables in Lua

Variables are used to store values during script execution.

Variable names in Lua

Variable names (identifiers) in Lua can be any sequence of letters, numbers, and the underscore that does not start with a number.

note

Lua is case-sensitive, so abc, Abc, ABC are different names.

The table below shows words that are reserved by the Lua language and cannot be used in variable names:

and break do else elseif

end false for function if

in local nil not or

repeat return then true until

while

In addition, all names beginning with an underscore followed by capital letters (for example, _VERSION) are also reserved.

What variables are there in Lua?

Variables in Lua can be global or local. If a variable is not explicitly declared as local, it is considered global.

Lua global variables

The global variable appears when the first value is assigned to it. Before the first value is assigned, the call to the global variable yields nil.

MsgBox (tostring (g)) -> nil

g = 1

MsgBox (tostring (g)) -> 1

The global variable exists as long as the script execution environment exists and is available to any Lua code executed in this environment.

If necessary, you can explicitly delete a global variable by simply assigning a nil value to it.

g = 1 - create a global variable g with the value 1

...

g = nil - delete the global variable g

MsgBox (tostring (g)) -> nil

All global variables are fields of a regular table called the global environment. This table is accessible through the global variable _G. Since the fields of the global environment are all global variables (including _G itself), then _G._G == _G.

Lua local variables

Any local variables must be declared explicitly using the local keyword. You can declare a local variable anywhere in the script. The declaration can include assigning an initial value to the variable. If no value is assigned, the variable contains nil.

local a - declare a local variable a

local b = 1 - declare a local variable b, assign it the value 1

local c, d = 2, 3 - declare local variables c and d, assign them values 2 and 3

The scope of a local variable begins after the declaration and continues to the end of the block.

Note

The scope of a variable is a piece of program code within which you can access the value stored in a given variable.

A block is understood as:

the body of the control structure (if-then, else, for, while, repeat);

function body;

a piece of code enclosed in the keywords do ... end.

If a local variable is defined outside of any block, its scope extends to the end of the script.

a = 5 - global variable a

local i = 1 - variable i is local within the script

   while i <= a do - loop from 1 to 5

   local a = i ^ 2 - variable a is local inside the while loop

   MsgBox (a) -> 1, 4, 9, 16, 25

   i = i + 1

end

MsgBox (a) -> 5 (here reference to global a)

if i> 5 then

   local a - variable a is local inside then

   a = 10

   MsgBox (a) -> 10

else

   MsgBox (a) -> 5 (here reference to global a)

end

do

   local a = 20 - variable a is local inside the do-end

   MsgBox (a) -> 20

end

MsgBox (a) -> 5 (here reference to global a)

note

Whenever possible, it is recommended to use local variables instead of global ones. This will avoid "cluttering" the global namespace and provide better performance (since access to local variables in Lua is somewhat faster than to global ones).

Lua data types

What data types does Lua support?

Lua supports the following data types:

1. Nil (nothing). Corresponds to the fact that a variable has no value. This type is represented by a single value, nil.

2. Boolean (logical). This type includes the values false and true.

When performing logical operations, nil is considered false. All other values, including the number 0 and the empty string, are considered true.

3. Number (numeric). Serves to represent numeric values.
Numeric constants can contain an optional fractional part and an optional decimal order, specified by the characters "e" or "E". Integer numeric constants can be specified in hexadecimal using the 0x prefix.

Examples of valid numeric constants: 3, 3.0, 3.1415926, 314.16e-2, 0xff.

4. String (string). Serves to represent strings.

String values are specified as a sequence of characters, enclosed in single or double quotes:

a = "this is a string"

b = 'this is the second line'

Strings enclosed in double quotes can interpret C-like escape sequences (escape sequences) that start with the character "\" (backslash):

\ b (space),

\ n (line feed),

 \ r (carriage return);

\ t (horizontal tab),

 \\ (backslash);

\ '' (double quote);

\ '(single quote).

note

A character in a string can also be represented by its own code using an escape sequence:

\ ddd,

where ddd is a sequence of no more than three digits.

In addition to quotation marks, double square brackets can also be used to define a string:

local a = [[Kronos Company]]

Defining a string with double square brackets allows all escape sequences to be ignored, that is, the string is created entirely as described:

local a = [[string

string1

string2

   string3

]] - "string

       string1

       string2

          string3 "

Note

When defining a string with double square brackets, tabs and hyphens are considered.

Double brackets can be nested. In order not to confuse them, the symbol "equal" (=) is inserted between the brackets:

local a = [= [definition of string [[string]] in Lua] =]

- there will be a term: "definition of string [[string]] in Lua"

5. Function. Functions in Lua can be written to variables, passed as parameters to other functions, and returned as the result of executing functions.

6. Table (table). A table is a set of key-value pairs, which are called fields or table elements. Both the keys and the values of the fields in the table can be of any type except nil. Tables do not have a fixed size: you can add an arbitrary number of elements to them at any time.

More details - in the article "Creating tables in Lua"

7. Userdata (user data). It is a special data type. Values of this type cannot be created or modified directly in a Lua script.

Userdata is used to represent new types created in the script calling program or in libraries written in C. For example, the Lua extension libraries for "CronosPRO" use this type to represent objects such as:

data banks (class Bank);

databases (Base class);

records (class Record), etc.

8. Thread (thread). Corresponds to the flow of execution. These streams are not connected in any way with the operating system and are supported exclusively by means of Lua itself.

How to set the type of a variable in Lua?

Lua does not explicitly set the type of a variable. The type of a variable is set at the time the variable is assigned a value. Any variable can be assigned a value of any type (regardless of what type of value it previously contained).

a = 123 - variable a is of type number

a = "123" - now the variable a is of type string

a = true - now the variable a is of type boolean

a = {} - now the variable a is of type table

note

Variables of type table, function, thread and userdata do not contain the data itself, but store references to the corresponding objects. When assigning, passing to a function as an argument and returning from a function as a result, objects are not copied, only references to them are copied.

a = {} - create a table. A reference to the table is placed in the variable a

b = a - variable b refers to the same table as a

a [1] = 10 - the element of the table with index 1 is assigned the value 10

MsgBox (b [1]) -> '10'

b [1] = 20

MsgBox (a [1]) -> '20'

The rest of the data are immediate values.

a = 10

b = a

a = 20

MsgBox (a) -> '20'

MsgBox (b) -> '10'

How to get the type of a variable in Lua?

The type of the value stored in a variable can be found out using the standard function type. This function returns a string containing the name of the type ("nil", "number", "string", "boolean", "table", "function", "thread", "userdata").

t = type ("this is a string") - t is equal to "string"

t = type (123) - t equals "number"

t = type (type) - t is "function"

t = type (true) - t is "boolean"

t = type (nil) - t is "nil"

t = type (CroApp.GetBank ()) - t equals "userdata"

How to convert the type of a variable in Lua?

Lua automatically converts numbers to strings and vice versa as needed. For example, if a string value is an operand in an arithmetic operation, it is converted to a number. Likewise, a numeric value that occurs where a string is expected will be converted to a string.

a = "10" + 2 - a is equal to 12
a = "10" + 2 - a is equal to "10 + 2"

a = "-5.3e-10" * "2" - a equals -1.06e-09

a = "string" + 2 - Error! Cannot convert "string" to number

Any value can be explicitly converted to a string using the standard tostring function.

a = tostring (10) - a equals "10"

a = tostring (true) - a equals "true"

a = tostring (nil) - a equals "nil"

a = tostring ({[1] = "this is field 1"}) - a is equal to "table: 06DB1058"

From the previous example, you can see that the contents of tables are not converted by the tostring function. This transformation can be done using the render function.

a = render (10) - a equals "10"

a = render (true) - a equals "true"

a = render (nil) - a is "nil"

a = render ({[1] = "this is field 1"}) - a is equal to "{[1] =" this is field 1 "}"

You can use the standard tonumber function to explicitly convert a value to a number. If the value is a string that can be converted to a number (or is already a number), the function returns the conversion result, otherwise it returns nil.

a = tonumber ("10") - a equals "10"

a = tonumber ("10" .. ". 5") - a equals 10.5

a = tonumber (true) - a is "nil"

a = tonumber (nil) - a is "nil"

Arranging comments in Lua

A comment in Lua begins with two minus signs (-) and continues to the end of the line.

local a = 1 - single line comment

If two open square brackets ([[)] immediately follow the “-” characters, the comment is multiline and continues up to two closing square brackets (]]).

local a = 1 - [[multiline

comment ]]

Double brackets in comments can be nested. In order not to confuse them, an equal sign (=) is inserted between the brackets:

local a = [[Kronos Company]] - [= [

local a = [[Kronos Company]]

] =]

The number of "=" symbols determines the nesting:

local a = [= [definition of some string [[string]] in Lua language] =] - [== [

local a = [= [definition of some string [[string]] in Lua language] =]

] ==]

Lua Operations

The following types of operations can be used in expressions written in Lua:

1. Arithmetic operations.

Lua supports the following arithmetic operations:

+ (addition);

- (subtraction);

* (multiplication);

/ (division);

^ (exponentiation);

% (remainder of the division).

note

Arithmetic operations apply to both numbers and strings, which in this case are converted to numbers.

2. Operations of comparison.

Lua allows the following comparison operations for values:

== (equal);

~ = (not equal);

<(less);

> (more);

<= (less or equal);

> = (greater or equal).

note

Comparison operations always return the Boolean value true or false.

The rules for converting numbers to strings (and vice versa) do not work for comparisons, that is, the expression "0" == 0 results in false.

3. Logical operations.

Logical operations include:

and (logical AND).

The and operator returns its first operand if it is false or nil. Otherwise, the operation returns the second operand (and this operand can be of any type).

a = (nil and 5) - a is nil

a == (false and 5) - a equals false

a == (4 and 5) - a equals 5

or (logical OR).

The or operator returns the first operand if it is not false or nil, otherwise it returns the second operand.

a == (4 or 5) - a equals 4

a == (false or 5) - a equals 5

note

Boolean operations and and or can return values of any type.

The logical operators and and or evaluate the value of the second operand only if it needs to be returned. If not required, the second operand is not evaluated. For instance:

a == (4 or f ()) - the function f () will not be called

not (logical NOT).

The not operation always returns true or false.

4. Operation of concatenation.

To concatenate (join) strings, use the operation ... (two dots).

a = "Kronos" .. "-" .. "Inform" - the variable a will receive the value "Kronos-Inform"

note

If one or both operands are numbers, they are converted to strings.

a = 0..1 - the variable a will receive the value "01"

5. The operation of obtaining the length.

Lua defines a length operator # that can be used to get the length of a string.

a = "string"

len = #a - len is 6

len = # "another line" - len is 10

note

You can also use the # operation to find out the maximum index (or size) of an array. More details - in the article "Working with arrays in Lua".

Operation precedence in Lua

In Lua, operations are performed according to the following priority (in descending order):

1. ^

2.not # - (unary)

3. * /%

4. + -

five. ..

6. <> <=> = ~ = ==

7. and

8.or

 Calling scripts from forms

Each form (including nested forms) has a separate script associated with it, which usually contains functions that handle the events of the form and its elements.

When the form is launched, its script is loaded into the global environment. When an event of a form or its element occurs, the system calls the handler function associated with this event.
It should be noted that the form script, although it does not contain a call to the module function, is in fact a module. This means that variables declared in the form script without the local keyword are not moved to the global environment and are available only within this script. If you need to make a value available to scripts of other forms, it must be explicitly defined in the global table _G:

_G.var = 123

Another form script can read this value like this:

local a = _G.var

Operator (instruction) blocks

The main Lua operators are:

assignment;

conditional operator;

operators for organizing loops.

A group of statements can be combined into a block (compound statement) using the do… end construction.

do - the beginning of the block

   <operator1> - block body

   <operator2>

   ...

   <operatorN>

end - the end of the block

The block opens a new scope in which you can define local variables.

a = 5 - global variable a

do

   local a = 20 - inside the do-end local variable a is defined

   MsgBox (a) -> 20

end

MsgBox (a) -> 5 (here the call is already to the global a)

Lua assignment operator

An assignment changes the value of a variable or table field. In its simplest form, an assignment might look like this:

a = 1 - variable a is assigned the value 1

a = b + c - variable a is assigned the sum of values of variables b and c

a = f (x) - the variable a is assigned the value returned by the function f (x)

Lua allows the so-called multiple assignment, when several variables to the left of the assignment operator receive the values of several expressions written to the right of the assignment operator:

a, b = 1.5 * c - a equals 1; b equals 5 * c

If there are more variables than values, nil is assigned to the "extra" variables.

a, b, c = 1, 2 - a is 1; b is 2; c is nil

If there are more values than variables, "extra" values are ignored.

a, b = 1, 2, 3 - a is 1; b is 2; value 3 not used

Multiple assignment can be used to exchange values between variables:

a = 10; b = 20 - a is 10, b is 20

a, b = b, a - now a is 20, b is 10

Conditional statement (if) in Lua

The if statement tests the truth of the given condition. If the condition is true, the part of the code following the then keyword (then section) is executed. Otherwise, the code following the else keyword is executed (the else section).

if a> b then

   return a - if a is greater than b, return a

else

   return b - otherwise, return b

end

The else section is optional.

if a <0 then

   a = 0 - if a is less than 0, set a to 0

end

Instead of nested if statements, you can use the elseif construct. For example, the following code:

if a == 1 then

   return "Ivan" - if a is 1

else

   if a == 2 then

     return "Peter" - if a is 2

   else

      if a == 3 then

         return "Sergey" - if a is 3

      else

         return "There is no such player" - if a is none of the above

      end

   end

end

it will be easier to understand if you replace it with the following:

if a == 1 then

   return "Ivan" - if a is 1

elseif a == 2 then

   return "Peter" - if a is 2

elseif a == 3 then

   return "Sergey" - if a is 3

else

   return "There is no such player" - if a is none of the above

end

Loop with precondition (while) in Lua

The while statement is designed to organize loops with a precondition and has the following form:

while <condition> do

   ... - the body of the cycle

end

Before each iteration of the loop, the <condition> condition is checked:

if the condition is false, the loop ends and control is transferred to the first statement following the while statement;

if the condition is true, the body of the loop is executed, after which all actions are repeated.

i = 10; t = {}

while i> 0 do - loop from 10 to 1

   t = "field" ..i

   i = i - 1

end

You can use the break statement to exit the loop before it completes.

a = {3, 5, 8, -6, 5}

i = #a

while i> 0 do - looking for a negative value in the array

   if a <0 then break end - if found, break the loop

   i = i - 1 - otherwise go to the next element

end

if i> 0 then

   MsgBox ("Index of negative value:" ..i)

else

   MsgBox ("Array does not contain negative values")

end

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.