Lua has a well-established reputation as a semi-language, a tool that can, on occasion, be built in to script an application written in a compiled language like C++. Nevertheless, Lua is a completely independent language that has its own interpreter, the ability to create modules, big number libraries, and at the same time, this PL has the minimum size among analogues. Simply put, we have everything to create the same applications as in perl, python, and in general any other common programming language.

I can offer you the following reasons for Lua:

  • - applications will be easily portable between Windows and Linux (not the fact that the code will work without changes, but porting will be painless if platform-specific libraries were not used)
  • - small overhead of created programs
  • - high speed work and download applications
  • - the ability to quickly "glue" any C-library to your application - you will not find a better "glue" for libraries
  • - nice minimalistic syntax of the language, with the ability to implement modern programming paradigms on it
  • - Lua programs are very easy to deploy
  • - low memory consumption

To demonstrate the power of Lua, I'll show you how to use Lua to create small program for building graphs by points with the ability to save the graph as an image file.

As a graphical toolkit, we will use iup - a cross-platform library, originally created with the expectation of using it from Lua.

Installing Lua SDK
As part of the idea of ​​using Lua as an independent programming language, the Lua for Windows assembly was created, which contains the libraries necessary for everyday tasks that arise when programming for the specified OS: working with the database, GUI, XML parsing, etc. Don't be embarrassed that the version of Lua is in assembly 5.1 and not 5.2 - there is not much difference between them in our case.

Download and install the build.

Brief description of the iup concept
I thought for a long time how to describe the process of creating a program without going into detail about the iup device. And I decided to briefly describe its main principles:
  • - iup.dialog is the root element of the program interface - all elements are placed in this container
  • - positioning of elements in a container is done using layouts: setting the rules for placing an element in a container. Iup itself will position and draw the element according to the rules. The main containers are frame, vertical sizer, horizontal sizer.
  • - event handlers are set as functions attached to the widget
  • - after the dialog is created, the event loop is started
If you've written for GUIs before with Tk, WxWidgets, or WinAPI, this will all sound familiar. If not, the program is covered in some detail with comments.
Program code

Connecting libraries iup require("iuplua") require("iupluacontrols") require("iuplua_pplot") -- library for working with Canvas to save the graph to a file require("cdlua") require("iupluacd") require("string ") -- global variables for widgets and program settings -- maximum number of plots plots_number = 5 -- tab widgets where data entry widgets for each plot will be placed tabs = () -- widget containers vboxes = () -- checkboxes for choose which plots to build checkboxes = () -- store widgets with text of data about points here coords = () -- label widgets for each plot legends = () -- coordinate axes designation widgets global_legend = () -- to the greatest shame , there is no standard Lua split function string:split(sep) local sep, fields = sep or ":", () local pattern = string.format("([^%s]+)", sep) self:gsub (pattern, function(c) fields[#fields+1] = c end) return fields end -- the function draws a graph on the plotter at the specified points funct ion draw_plot(pwidget, pnum, data) x = data.value:split(",") y = data.value:split(",") if checkboxes.value == "(!LANG:OFF" then return end if not (#x == #y) or #x == 0 then iup.Message("Ошибка", "Задано неверное число точек для графика " .. pnum) return end iup.PPlotBegin(pwidget, 0) iup.PPlotAdd(pwidget, 0, 0) for i = 1,#x do iup.PPlotAdd(pwidget, x[i], y[i]) end iup.PPlotEnd(pwidget) end -- виджет отвечающий за кнопку построения графика plot_btn = iup.button{ title = "Build"} -- колбэк для кнопки "построить график" function plot_btn:action() -- создать виджет графопостроителя plot = iup.pplot { expand="YES", TITLE = "simple line", MARGINBOTTOM="65", MARGINLEFT="65", AXS_XLABEL = global_legend.value, AXS_YLABEL = global_legend.value, LEGENDSHOW="YES", LEGENDPOS="TOPLEFT", size = "400x300" } -- этот блок для обхода бага - без него подпись к первому графику отображаться не будет iup.PPlotBegin(plot, 0) iup.PPlotAdd(plot,0,0) plot.DS_LEGEND = "" iup.PPlotEnd(plot) -- обходим виджеты с данными for i = 1, plots_number do -- чтобы свеженарисованный графи отобразился с правильной подписью print(legends[i].value) plot.DS_LEGEND = legends[i].value -- рисуем график draw_plot(plot, i, coords[i]) end -- кнопка сохранения графика в картинку на диске save_btn = iup.button{ title = "Save" } -- теперь создаем само окно, где будет отображаться график plot_dg = iup.dialog { iup.vbox -- это вертикальный сайзер, помести в него графопостроитель и кнопку { plot, save_btn }, } -- обработчик кнопки сохранения графика function save_btn:action() -- создаем диалог выбора имени файла ля сохранения -- в связи с ограничениями библиотеки сохранять можно только в EMF fs_dlg = iup.filedlg{DIALOGTYPE = "SAVE", FILTER = "*.emf" } iup.Popup(fs_dlg) -- если файл выбран if tonumber(fs_dlg.STATUS) >= 0 then -- дописать при необходимости !} desired extension pic = fs_dlg.value if not (string.sub(pic, string.len(pic)-3) == ".emf") then pic = pic .. ".emf" end -- create a pseudo canvas associated with file tmp_cv = cd.CreateCanvas(cd.EMF, pic .. " 400x300") -- plotting on canvas iup.PPlotPaintTo(plot, tmp_cv) -- saving data to file cd.KillCanvas(tmp_cv) end end -- display dialog plot_dg:showxy(iup.CENTER, iup.CENTER) -- run the event loop for the dialog if (iup.MainLoopLevel()==0) then iup.MainLoop() end end -- in the loop create tabs in which we will place widgets -- to collect data for i=1,plots_number do -- create text widgets where coordinates of points will be entered coords[i] = () for j = 1,2 do coords[i][j] = iup .text ( expand="HORIZONTAL", multiline = "YES", VISIBLELINES = 5 ) end -- widget for editing chart caption legends[i] = iup.text( expand = "HORIZONTAL" ) -- create tab container and fill its elements vboxes[i] = iup.vbox ( i up.hbox ( iup.label ( title = "(!LANG:Graph label:" }, legends[i] }, iup.hbox { iup.label { title="X:", }, coords[i] }, iup.hbox { iup.label { title="Y:", }, coords[i] }; expand="YES", } -- меняем заголовк вкладки vboxes[i].tabtitle = "Schedule" .. i -- создаем чекбокс, который будет указывать на то, нужно ли строить -- график по данным из указанной вкладки checkboxes[i] = iup.toggle{ title= "Schedule" .. i, value = "ON" } end -- теперь из заполненных нами контейнеров создаем вкладки tabs = iup.tabs{unpack(vboxes)} -- создаем текстовые виджеты для редактирования подписей осей global_legend = iup.text{} global_legend = iup.text{} -- создаем фрейм для !} general settings graphics frame = iup.frame ( iup.vbox ( iup.label( title="(!LANG:Use data:", expand="HORIZONTAL" }, iup.vbox { unpack(checkboxes) }, iup.label{}, -- пустую подпись можно использовать как распорку iup.label{title = "Signatures"}, iup.hbox { iup.label{ title = "X axis"}, global_legend }, iup.hbox { iup.label{ title = "Y-axis"}, global_legend }, iup.label{}, plot_btn }; expand = "VERTICAL", } -- создаем главное окно программы и наносим на него настройки и табы dg = iup.dialog { iup.hbox { frame, tabs }, title="Building a graph", size = "HALF" } -- показываем главное окно и запускаем обработку событий dg:showxy(iup.CENTER, iup.CENTER) if (iup.MainLoopLevel()==0) then iup.MainLoop() end !}

A few words about deployment
The script can be run with the command:

Luaplotter.exe

In this case, the libraries will be included from the clibs/ subdirectory, which is located in the directory where Lua for Windows was installed. To pack the script and libraries as compactly as possible for transfer to another machine, just copy the following files into one folder (indicated with relative paths from the Lua installation directory):

Lua.exe lib/lua5.1.dll clibs/cd.dll clibs/cdlua51.dll clibs/iup.dll clibs/iup_pplot.dll clibs/iupcd.dll clibs/iupcontrols.dll clibs/iupgl.dll clibs/iuplua51.dll clibs/iuplua_pplot51.dll clibs/iupluacontrols51.dll clibs/iupluacontrols51.dll clibs/freetype6.dll

Do not forget to place the script with the program in this folder. Now you can transfer this folder to another machine and run your programs with the command above. In this case, no other steps to install libraries and runtime are needed.

Unfortunately, the cd.dll, cdluad51.dll and iupcd.dll files may not work correctly in this version of Lua for Windows, so I recommend taking them from the archive using the link below.

Results
Archive with the working version, app.bat launcher added for convenience.

Screenshots:

As a result, we got, albeit a clumsy, utility that has the same functionality as if it were written in a "serious" programming language. At the same time, it is easy to deploy and with a total weight of less than 2 mb. Memory consumption - about 7 MB. The source code is editable, Lua itself is interactively understandable, which simplifies the development of such software in the field.

In my opinion, this is an excellent choice for writing educational software for schools and institutes, as well as for internal use in enterprises. Since weak machines still abound in similar places throughout the CIS, using Lua in this way makes sense, especially in light of the gradual arrival of Linux on desktops. In addition, the tendency to lose the source codes of self-written software with its terrible buggy can be equated with a national disaster.

Tags: Add tags

LUA Plugin - required for some mods that are written in script hook V for GTA 5.

Lua is a scripting programming language developed by the Tecgraf (Computer Graphics Technology Group) division of the Catholic University of Rio de Janeiro (Brazil). The language interpreter is freely distributed, open source in the C language.

In terms of features, ideology, and implementation, the language is closest to JavaScript, but Lua has more powerful and much more flexible constructs. Although Lua does not explicitly contain the concepts of class and object, object-oriented programming mechanisms, including multiple inheritance, are easily implemented using metatables, which are also responsible for operator overloading, etc. The implemented object-oriented programming model is prototypal (as is in JavaScript).

LUA Plugin for Script Hook V

The language is widely used to create a replicable software(for example, it says GUI Adobe package Lightroom). Also gained popularity as a programming language for levels and extensions in many games (including World of Warcraft) due to its ease of embedding, speed of code execution, and ease of learning.

How to install

  1. You need an installed
  2. Then just copy all files from archive (including folders) to root folder gta 5.
  3. In the future, scripts on LUA are loaded into the folder "/scripts/addins"

Lua for Windows (LfW) is an interpreted programming language developed by the Tecgraf division of the Computer Graphics Technology Group of Pontifical Catholic University of Rio de Janeiro in Brazil. The developed interpreter is freely distributed, with open source texts in the C language.

In terms of features, ideology, and implementation, the language is closest to JavaScript, but Lua has more powerful and much more flexible constructs. Although Lua does not explicitly contain the concepts of class and object, object-oriented programming mechanisms, including multiple inheritance, are easily implemented using metatables, which are also responsible for operator overloading, etc. The implemented object-oriented programming model is prototypal (as and in JavaScript).

The language is widely used to create replicated software - in particular, the graphical interface of the package is written on it. Adobe Photoshop Lightroom. It has also gained prominence as a programming language for levels and extensions in many games (such as World of Warcraft) due to its ease of embedding, speed of code execution, and ease of learning.

Lua is commonly referred to as a multi-paradigm language. It provides a small set of basic mechanisms that can be extended to solve different problems, rather than a set of complex rigid specifications that ensure programming in a single paradigm.

For example, there is no explicit support for inheritance in Lua, but it is easily implemented using metatables.

- The extension (format) is the characters at the end of the file after the last dot.
- The computer determines the file type precisely by extension.
- By Windows default does not show filename extensions.
- Some characters cannot be used in the file name and extension.
- Not all formats are related to the same program.
- Below are all the programs with which you can open the LUA file.

Many MS Windows users have long noticed that a standard notepad is a rather inconvenient program to use. This can be a replacement free editor text files, which provides syntax support for a large number of programming languages. The program contains a fairly wide range of options and is characterized by minimal consumption of processor resources. The program makes it possible to simultaneously view several documents at once and edit them without closing unnecessary windows. An option has also become available, such as editing the same document in different places which is very convenient...

Notepad2 is a simple application that allows you to type and edit text. It will help in creating HTML pages, programming in various languages ​​(CSS, Java, JavaScript, Python, SQL, Perl, PHP) as it is able to highlight the code. The program is built on the principle of a simple notepad, it is lightweight and compact. This text editor checks all brackets for pairs, supports auto indentation. Notepad2 not only supports ASCII and UTF-8 encodings, but also knows how to convert them. Allows you to roll back unwanted operations many levels back. Supports block selection of text elements and has numbered lines...

Komodo Edit is a handy code editor that supports a wide range of different programming languages. The program gives users the opportunity to work with several files at once, writing code will become more efficient using the autocomplete function, tips. The application allows you to automatically highlight variables when they are selected. Using the editor, you can view files in other programming languages. The program supports syntax coloring, indentation. Can check syntax parameters, snippets used to store source column code. It has an easy editing mode and supports drag and drop of elements...

There are a lot of programs on the Internet that allow you to edit source another program, file, etc. However, most of these programs are just text editor like a notepad. They differ from the above editor only in that they have syntax highlighting. However, in some cases, this functionality of the program is not enough. A programmer may need to quickly find different parts of a document. And now, finally, a program has appeared that allows you to solve this problem. The program is called SynWrite. Her distinguishing feature– the presence of a navigation bar with a tree that ...

Lua scripts

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

The script can be either very simple, consisting of just one command, or very complex, containing tens, hundreds or even thousands of instructions. Following instructions may be separated by a semicolon (;). However, this requirement is not mandatory, so all of the code below is correct in terms of syntax:

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 underscores that do not start with a number.

note

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

The table below lists 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

In addition, all names that begin with an underscore followed by capital letters(e.g. _VERSION) are also reserved.

What are the variables in Lua?

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

Lua Global Variables

A global variable appears the moment it is assigned its first value. Before assigning the first value, accessing a global variable yields nil.

MsgBox(tostring(g)) --> nil

MsgBox(tostring(g)) --> 1

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

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

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

g = nil - remove the global variable g

MsgBox(tostring(g)) --> nil

All global variables are fields in a regular table called the global environment. This table is available through the _G global variable. 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 may include assigning an initial value to the variable. If no value is assigned, the variable contains nil.

local a - declare local variable a

local b = 1 - declare local variable b, assign value 1 to it

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

The scope of a local variable starts after the declaration and continues until the end of the block.

Note

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

Block means:

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

function body;

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

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

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

while i<= a do - цикл от 1 до 5

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

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

MsgBox(a) -->

if i > 5 then

local a - variable a is local inside then

MsgBox(a) --> 10

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

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

MsgBox(a) --> 20

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

note

Whenever possible, it is recommended to use local variables instead of global ones. This will avoid polluting the global namespace and provide better performance (because accessing local variables in Lua is slightly faster than accessing global ones).

Lua Data Types

What data types does the Lua language support?

Lua supports the following data types:

1. Nil (nothing). Corresponds to the absence of value variable. This type is represented by a single value, nil.

2. Boolean (logical). To this type values ​​include false (false) and true (true).

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

3. Number (numeric). Used to represent numeric values.

Numeric constants can be optional fractional part and an optional decimal exponent 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). Used 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 that begin with a "\" 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 code using the escape sequence:

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:

Defining a string with double square brackets allows you to ignore all escape sequences, i.e. the string is created completely as described:

local a = [] in Lua]=]

There will be a term: "string[] definition in Lua"

5. Function (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 elements of a table. Both keys and table field values ​​can be of any type except nil. Tables do not have a fixed size: at any time, you can add an arbitrary number of elements to them.

Read more 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's caller or in libraries written in C. For example, the Lua extension libraries for "CronosPRO" use this type to represent objects such as:

data banks (Bank class);

databases (class Base);

records (class Record), etc.

8. Thread (thread). Corresponds to the flow of execution. These streams are in no way associated with 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 specify 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 it previously contained).

a = 123 - variable a has type number

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

a = true - variable a is now of type boolean

a = () - now 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 = 10 - table element with index 1 is assigned the value 10

MsgBox(b) --> "10"

MsgBox(a) --> "20"

The rest of the data are immediate values.

MsgBox(a) --> "20"

MsgBox(b) --> "10"

How to get the type of a variable in Lua?

The type of a 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 is "number"

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

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

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

t = type(CroApp.GetBank()) - t is equal to "userdata"

How to convert the type of a variable in Lua?

Lua automatically converts numbers to strings, and vice versa, if necessary. For example, if a string value is an operand in an arithmetic operation, it is converted to a number. Likewise, a numeric value encountered 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 is equal to -1.06e-09

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

A value of any type can be explicitly converted to a string using the standard tostring function.

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

a = tostring(true) - a is equal to "true"

a = tostring(nil) - a is equal to "nil"

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

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

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

a = render(true) - a is equal to "true"

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

a = render (( = "this is field 1")) - a is "( = "this is field 1")"

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

a = tonumber("10") - a is equal to "10"

a = tonumber("10"..5") - a is equal to 10.5

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

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

Arrangement of 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 opening square brackets ([[) immediately follow the "--" characters, the comment is a multiline comment and continues 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 "=" characters determines the nesting:

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

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

Operations used in Lua

In expressions written in Lua, the following kinds of operations can be used:

1. Arithmetic operations.

Lua supports the following arithmetic operations:

+ (addition);

- (subtraction);

* (multiplication);

/ (division);

^ (exponentiation);

% (remainder of the division).

note

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

2. Comparison operations.

The following value comparison operations are allowed in Lua:

== (equal to);

~= (not equal);

< (меньше);

> (greater);

<= (меньше или равно);

>= (greater than or equal to).

note

Comparison operations always return boolean true or false.

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

3. Logical operations.

To logical operations relate:

and (logical AND).

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

a = (nil and 5) - a is equal to nil

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

a == (4 and 5) - a is equal to 5

or (logical OR).

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

a == (4 or 5) - a is equal to 4

a == (false or 5) - a is equal to 5

note

brain teaser operations and and or can return values ​​of any type.

The logical operations 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 example:

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

not (logical NOT).

The not operator always returns true or false.

4. Operation of concatenation.

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

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

note

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

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

5. The operation of getting the length.

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

a = "string"

len = #a - len is equal to 6

len = #"one more line" - len is 10

note

You can also use the # operator to find out the maximum index (or size) of an array. For more details, see the article "Working with arrays in Lua".

Operator precedence in Lua

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

2. not # - (unary)

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

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 a form is run, 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 actually a module. This means that variables declared in the form script without the local keyword are not exposed to the global environment and are available only inside this script. If a value needs to be made available to other form scripts, it must be explicitly defined in the global _G table:

local a = _G.var

Blocks of statements (instructions)

The main Lua operators are:

assignment;

conditional operator;

operators for organizing cycles.

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

do - the beginning of the block

<оператор1>- block body

<оператор2>

<операторN>

end - the end of the block

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

a = 5 - global variable a

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

MsgBox(a) --> 20

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

Assignment operator in Lua

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 the values ​​of variables b and c

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

In Lua, the so-called multiple assignment is allowed, 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 is equal to 1; b is equal to 5*c

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

a, b, c = 1, 2 - a is equal to 1; b is 2; c equals nil

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

a, b = 1, 2, 3 - a is equal to 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

if statement checks for truth given condition. If the condition is true, the part of the code that follows is executed. keyword then (section then). Otherwise, the code following the else keyword (else section) is executed.

if a > b then

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

return b - otherwise, return b

The else section is optional.

if a< 0 then

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

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

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

return "Ivan" - if a is equal to 1

elseif a == 2 then

return "Peter" - if a is 2

elseif a == 3 then

return "Sergey" - if a is equal to 3

return "No such player" - if a is none of the listed

Loop with precondition (while) in Lua

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

while do

... - loop body

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

if the condition is false, the loop terminates 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.

while i > 0 do - loop from 10 to 1

t[i] = "field"..i

a = (3, 5, 8, -6, 5)

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

if a[i]< 0 then break end - если найдено, прерываем цикл

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

if i > 0 then

MsgBox("Negative value index: "..i)

MsgBox("The array contains no negative values")

Note

Loop with postcondition (repeat) in Lua

The repeat operator is designed to organize cycles with a postcondition and has the following form:

... - loop body

until

The body of the loop is executed until the condition won't become true. The condition is checked after the execution of the loop body, so in any case the loop body will be executed at least once.

Sum the values ​​of the array a until the sum exceeds 10

a = (3, 2, 5, 7, 9)

sum = sum + a[i]

until sum > 10

MsgBox("Added ..i.." items. Sum equals "..sum)

You can use the break statement to break out of a loop before it ends.

Note

For more information about the features of using the break statement, see the article “Break and return statements”

Loops with a for statement in Lua

The for statement is intended for organizing loops and allows two forms of writing:

simple (numeric for);

extended (universal for).

The simple form of the for statement

The simple form of the for statement is as follows:

for var = exp1, exp2, exp3 do

... - loop body

Loop body is executed for each value loop variable(counter) var in the range from exp1 to exp2, with step exp3.

Note

The step may not be specified. In this case, it is taken equal to 1.

for i = 1, 10 do - loop from 1 to 10 with step 1

MsgBox("i is equal to"..i)

for i = 10, 1, -1 do - loop from 10 to 1 with step -1

MsgBox("i is equal to"..i)

note

The expressions exp1, exp2 and exp3 are evaluated only once, before the start of the loop. So, in the example below, the function f(x) will be called to calculate the loop's upper limit only once:

for i = 1, f(x) do - loop from 1 to the value returned by f()

MsgBox("i is equal to"..i)

The loop variable is local to the loop statement and is not defined at the end of the loop.

for i = 1, 10 do - loop from 1 to the value returned by f()

MsgBox("i is equal to"..i)

MsgBox("After exiting the loop, i is "..i") - Wrong! i equals nil

note

The value of a loop variable cannot be changed inside the loop: the consequences of such a change are unpredictable.

The break statement is used to exit the loop before it is completed.

a = (3, 5, 8, -6, 5)

for i = 1,#a do - look for a negative value in the array

if a[i]< 0 then - если найдено...

index = i - save the index of the found value...

break - and break the loop

MsgBox("Negative value index: "..index)

Note

For more information about the features of using the break statement, see the article "Break and return statements")