Lua – Installed Lua. Lua – Installing Lua Program for robots with lua

Golovna / Setting up
This series of lessons, as I intended, will discuss the language of Lua programming. I will try to make the report as accessible as possible to the newbies, and I will focus on them myself. So, as proven Lua coders, who have seen everything, there is nothing new to learn from this (sorry, here they will find more space for hairstyles and respect, as if, from their side, the wind is flying), but there is nothing on your shoulders. a lot of programming , then, I think, you’re guilty.

The entire series is not ordered by any system. The lessons will sequentially introduce a number of language constructions, so that by the third or fourth lesson you can already write your own programs. My aim is to encourage you to learn the language on your own, to help you understand it, and not to explain it from A to Z - if you want to master the language in detail, read the previous article (which, however badly, is translated by the Russian language: http://www. lua.ru/doc/). The sooner you move from Merezha’s “for dummies” lessons to the teacher’s education, the better.

If you don’t understand, please put your food in the comments, and I and the other participants will try to help you.

Lua is popular, difficult to master, interpreted, dynamically typed language programming for foreign purposes. No, you don’t have to understand even half of the words said in the front proposition - just know that it’s popular and awkward. To the point, its simplicity, as well as the small size of the distribution (about 150 kilobytes), has earned it its popularity. Lua scripts are supported by a large number of programs, including games. World of Warcraft and S.T.A.L.K.E.R. Vikorize the Lua language. My favorite game engine allows you to easily create different games using Lua. As you see, Lua opens up vast horizons for you!

First of all, you should plan the middle part for programming: to find a program that would accept the code you write in Lua and create it: an interpreter. There are three options here:

1. Download the official Lua distribution from one of the sites that supplies them.

From the official Lua website you can download the interpreter's output codes. However, by visiting http://lua.org/download.html in the Binaries section, you can see a post on the site with downloaded files for Windows. One of them: . Please select one of the archives (depending on your platform: Win32 or Win64) and unpack it somewhere in a directory with a short path: to C:\lua. From now on, I appreciate that you are using Windows, and your interpreter is lying there.

For users of operating systems based on Linux, the solution is simpler: they just need to quickly use the package manager and install Lua from the repositories. For Debian and Ubuntu, use the command apt-get install lua, and for Fedora, Red Hat and similar distributions, use yum install lua. However, do not trust me blindly and go to the source of your operating system to find out how it works for you.

2. Use an online interpreter.

Find the address http://www.lua.org/demo.html. You can download it from the beginning, but if you touch the modules, you will be confused with the offline version. Using the online interpreter is very simple: enter your program at the end of the text and click the Run button. The program will be logged in, the Output window will display the version of your program, as well as information about any errors that you have made.

3. Vikorystuvati IDE.

For example, ZeroBrane Studio: http://studio.zerobrane.com/. And others - search on the Internet.

There are two different versions of Lua in use today: 5.1 and 5.2. I am focusing on the remaining version - version 5.2, but I will definitely point out the important differences between it and 5.1, since the remaining version is still expanded. Before we speak, Lua 5.1 changes the code from the author to the same time as Lua 5.2, just so you know.

=== Lesson No. 1 ===

So let's see. Create the main.lua file in a folder isolated from third-party files and write to it:

200?"200px":""+(this.scrollHeight+5)+"px");">
-- main.lua --
print("Hello world!")

After that, run in the command line (don’t forget to move to the directory with main.lua for an additional cd):

200?"200px":""+(this.scrollHeight+5)+"px");">
> C:\lua\lua.exe main.lua

The Lua interpreter looks like this:

200?"200px":""+(this.scrollHeight+5)+"px");">
Hello world!

In principle, whose trace was to be found. The programs called the print function. The print function accepts a large number of parameters and displays them on the screen. Whose butt we passed the row (lance of symbols) “Hello world!” With the same success, you can pass as a parameter:

200?"200px":""+(this.scrollHeight+5)+"px");">
print(8) - the tenth number
-- viveda: 8

Print(0xDEADBEEF) - sixteenth number
-- viveda: 3735928559

Print("0xDEADBEEF") - but a sequence, not a number! Are your paws getting sore?
-- view: 0xDEADBEEF

Print(1.35e-4) -- a number with a floating coma (a fractional number)
- Vivede 0.000135. 1.35e-4 trace is considered as "1.35, multiplied
- by ten to the minus of the fourth stage, as no one knows.

Print((198*99)-3*500 + 14/88) - viraz
-- Vivede meaning virazu: 18102.159090909. Nasty alternative
- Desktop calculator!

Print(198/7, "fertilizer", 2^9) - a number of parameters for a sufficient
- Like. The meaning of the skin will be displayed, separated by signs
- Tabs:
-- 28.285714285714 fertilizer 512
- Please pay attention so that your paws don’t get stuck in the fertilizer!

Print(1.35) - two numbers, not the tenth fraction 1.35!
-- Coma is used to separate parameters.
- Vivede:
-- 1 35

The "--" sign is not just an imitation of the dash sign, which is inserted for beauty. The "--" sign in Lua denotes comments: hints for the programmer that are ignored by the interpreter, and are intended to make the code easier to understand. You can try writing in the program:

200?"200px":""+(this.scrollHeight+5)+"px");">
- print("nothing")

The interpreter will think that this is a comment and will not exit the instruction.

Gentlemen, please note: if you want to crochet just one row, you can write the letter print like this, without the arms:

200?"200px":""+(this.scrollHeight+5)+"px");">
print "Just one string"

Handiness, of course, is doubtful: just respect that this is possible. At the same time, such comments are unacceptable:

200?"200px":""+(this.scrollHeight+5)+"px");">
print 2 - no word, 2 - not a row.
print 2*2 + 6 - we won’t ask anymore

Str = "string!!" -- gave the changed str value "string!!"
-- read about the changes below
print str - I don’t even need to express it.

For each of the following episodes, the program is easy to use. Thus, in a “bracket-free” caller, the name of the function can be followed by just a series literal (that is, the sequence of characters is placed in the legs), and nothing else. In the near future, I will tell you about this peculiarity a little later, otherwise I will immediately get it out of you.

With any good software, you can use the following options: small containers that can hold any kind of data. In Lua, you have to do it this way:

200?"200px":""+(this.scrollHeight+5)+"px");">
<имя_переменной> = <выражение>

For example:

200?"200px":""+(this.scrollHeight+5)+"px");">
star = 8 -- Now the changeable star retains the number 8
wars = "owl" - In the snake wars - row "owl"
jedi = 42/2 - The serpentine jedi has the number 21
luke = star * jedi -- Serpentine luke has the number 168 (so, 21 multiplied by 8)

The values ​​of the changes and expressions behind them can also be displayed on the screen:

200?"200px":""+(this.scrollHeight+5)+"px");">
print(star, wars, jedi, jedi-star+luke)
- Vivede:
-- 8 owl 21 181

Just don’t try to cheat the famous stars and wars - if you try to add 8 to “owl”, you won’t achieve anything good!

As you may note, the change can be practically like this: smut, so that it doesn’t start with the numbers. Seriously, you can announce the change with the name print, and then the print function will stop working, so that the print will be forced to respond to the voiced change. There is also a group of words that are blocked by vikorystovuvat as the names of the changeable ones - these are the key words of the language that we have not yet learned, but at the same time marvel at:

200?"200px":""+(this.scrollHeight+5)+"px");">
and break do else elseif end
false for function goto if in
local nil not or repeat return
then true until while

Having made a change with one of these names, you will receive a pardon from the program, and you will definitely not have to deal with it. Let me remind you: Lua 5.1 does not have the goto keyword, and you can call it that way, or rather not work like that.
Also ensure that the names of the important people are sensitive to the register. Tse, Shcho Foo, Foo, Foo I Foo - Chotiri Rizni Zmіnni, Tom Yakshcho Vi wrote izi, the serpent of Malimi Liters, and they wrote yogo great, then, Schwidsha for everything, the Program did not have prytsyuvatiorely.

And now there’s one important point: what will you do in a fitful and wicked manner to the point of unbearable change? Most other languages ​​do not call for mercy, but in Lua this situation is acceptable. It is interpreted as follows, no matter what the unknown change is really true, but it has the same meaning nil. nil- Remember this word! - a special type of Lua meaning that means “nothing.” It’s not zero and it’s not an empty row (the row looks like “” - try to display it on the screen), but simply nothing. Consider this model: there are two people, one of them has a bank account, but doesn’t have any pennies, and the other bank account is empty. In Lua terms, it will be important that the first one costs 0 dollars for the exchange rate, and the other one costs 0 dollars for the exchange rate. nil. And it’s not dollars, but simply nil. I hope I haven't misled you.

For example, try running a program like this:

200?"200px":""+(this.scrollHeight+5)+"px");">
-- main.lua --
foo = "bar"
print(foo, baz)
- Vivede:
--bar nil

Thus, the variable base does not have any value, but it is important that the value is nil, and the print function understands this and displays it on the screen in the form of the row “nil”. Lua has a good method for checking the value of a change: if the value of the change is not equal to nil, it is silent. On the other hand, you can clearly voice the difference, equal to nil:

200?"200px":""+(this.scrollHeight+5)+"px");">
cool_var=nil

So you can be timid, and even if you want to appear stupid at first glance, you can still be timid. In the coming lessons, you will find out who is going on, and, singly, you will begin to work the same way. Innodi, obviously.
Be careful with nil: you can overwrite nil, but you can’t perform arithmetic operations with it! If print(nil) gets away with it, then the construction for the script 99+nil is better, as you would like, shob 99 + nil added 99. Believe me, I was embarrassed when I found out.

Summary:
1. We learned about the print function, what it does and how to correctly type it without bows.
2. We learned how to pronounce change, how to count expressions (though even threes), which change names can have.
3. We learned about nil, embraced its mystical mystery, and became infatuated with those who will be connected with it in the future.

For those who are keen and willing to enhance their knowledge, I just say right, What you can avoid if you feel so competent:
1. Write a program to display songs of your favorite song.
2. Try to introduce new expressions. Try to understand why actions work with them, and actions do not. Marvel at the mercy they cry out for things they haven’t asked for.

200?"200px":""+(this.scrollHeight+5)+"px");">
2 + "string";
6 + "14";
"box" - "vox";
1 * "11b"
"148" * "1e6";


3. Write a program that exchanges two values. Tobto:

200?"200px":""+(this.scrollHeight+5)+"px");">
a = 6502
b = 8086


Work it out so that a equals 8086, and b equals 6502. To do this, create a third change and make some simple rearrangements. Make sure that the command is correct by clicking print(a,b) before the exchange and print(a,b) after.

Lua for Windows (LfW) - interpreted language program, developed by the Tecgraf developer of the Catholic University of Rio de Janeiro. The detailed interpreter can be seen everywhere, with the open texts of my Sy.

Due to the capabilities, ideology and implementation being closer to JavaScript, the Lua protea is characterized by more dense and richly flexible structures. While Lua does not want to undermine the concept of an object's class in an explicit manner, the mechanisms of object-oriented programming, including multiplying, are easily implemented using metatables, which also support the reversal of operations. That's it. An object-oriented programming model has been implemented—prototypical in JavaScript).

The language is widely used for the creation of software that is being replicated - for example, on a new graphical interface for the Adobe Photoshop Lightroom package. Also, the programming of the world gained popularity and expanded in many games (for example, World of Warcraft) through the ease of learning, the speed of writing code and the ease of learning.

Lua deserves to be called a multi-paradigm language. It will provide a small set of basic mechanisms that can be expanded to accommodate different tasks, rather than a set of complex, rigid specifications that will ensure the programming of a single paradigm.

So, in Lua there is a clear support for fallback, the protec- tion can be easily implemented using an additional metatable.

This is food, because it is necessary to finish drinking often. Well, it’s amazing, because the installation is really simple and straightforward. One can say that there is nothing to work on there. Ale, since the food supply is still lacking, let’s talk a little about the installation.

Installed Lua. Zavantazhuemo

The first thing we need to do before installation is to capture the output records from their official website: . To install, of course, we need the latest version, currently lua 5.1.4. After downloading, you will obviously need to unzip the lua source files into a separate folder.

Installed Lua. Compilation.

There are two compilation options, which, in principle, do not differ in any way))) The first is compilation with Visual Studio Command Prompt:

  1. Launching Visual Studio
  2. Vikonuemo Tools->Visual Studio Command Prompt
  3. Go to the Lua folder, to the etc. directory. The axis is like this: cd D:/mylibs/lua-5.1.4
  4. launch the Lua compilation script: etc/luavs.bat
  5. We took away the files we needed lua.exeі luac.exe

Another way without starting Visual Studio:

  1. If you have a file-mendezhi (I especially work in) go to the de_lois/etc/ folder
  2. The file is editable, put the first row: call “path_to_visualstudio/VC/bin/vcvars32.bat”
  3. Add another row: cd.. and save the file
  4. Launching and uninstalling your browsers

Installed Lua. Access

So that you can launch lua stars in advance, you need to add them (go to them) at the %PATH%. I think you yourself miraculously know how to earn money. In any case, we don’t need these files, because... We plan to vikorista lua inside our programs, and not like closing the program. After whom, respect what you yourself Lua installation completed, you will no longer be able to register the path in liba in Visual Studio.

Installed Lua. Static linking.

It is especially important for me to exclude those who, with a skin project such as Vikorist Lua, have to deal with lua.dll, since the programs will not work without it. And in order for the stinks to continue, it would be necessary for the blois to link to our program statically. It’s really easy to figure out the price:

  1. Visual Studio has a new project, Win32Project, called "LuaLib"
  2. The project type is set to "Static Library", the Precompiled Header checkbox is enabled, and Finish is pressed.
  3. All files can be added to the project.h i.c, including lua.c and luac.c
  4. To ensure that the compiler does not show us any warnings, we add;_CRT_SECURE_NO_WARNINGS to the project setup (Protec/Propreties/Preprocessor) (do not forget to create this for both the release and the debug version!!!)
  5. In the configured links (Project/Properties/Librarian/General/OutputFile) you can specify whatever library names you want. I specified lua.lib for release and lua-debug.lib for debug.
  6. Compiles debug and release versions. We take away our needs
  7. We register the directions to them in Visual Studio

Installed Lua. Re-verification.

Let's check that everything is working. I'm creating a new project (I created a Win32 console project). Let's add Lua inclusions:

And main() itself is expanded:

int _tmain(int argc, _TCHAR* argv ) ( lua_State * L; L = lua_open() ; // Creating a stack luaL_openlibs(L) ; //connect standard libraries int status = luaL_loadfile(L, "test.lua"); //own the file /* Stance: [-1]main<--top of the stack */ if (status) ((void) fprintf (stderr, "file not found \n"); return 1; ) int result = lua_pcall(L, 0, LUA_MULTRET, 0); _getch(); return 0; )

When setting up the linker (Project/Properties/Linker/Input/Addition Dependencies), do not forget to add our library (lua.lib for release and lua-debug.lib for debugging). Compilable. We are creating a test file with a Lua script.

Script my Lua

Written in Lua, the script does not have any special function that would begin with your vicination. A script can be viewed simply as a set of commands (instructions) that begin with the first instruction.

The script can be as simple as it consists of just one command, or as complex as it can accommodate tens, hundreds or thousands of instructions. Step by step instructions can be separated by a dot (;). However, this is not entirely clear, so all the code below appears to be correct in syntax:

Working with changes in Lua

Changes are made to save the value of the script process.

Names of minions in Lua

Names (identifiers) of Lua variables can be any sequence of letters, numbers, and the chair symbol that do not begin with a number.

Regain respect

The Lua language separates the register of characters, so abc, abc, and ABC have different names.

At the bottom of the table there are words that are reserved by my Lua and cannot be substituted in 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 accretion symbol followed by great letters (for example, _VERSION) are also reserved.

What changes are there in Lua?

Changes in Lua can be either global or local. Just because the change is not recognized as local, it is respected globally.

Global changes in Lua

The global change appears at the moment of assigning its first value. Until the first value is given, the change to the global change gives nil.

MsgBox(tostring(g)) --> nil

MsgBox(tostring(g)) --> 1

The global change is active until the middle of the script is active and is available to any Lua code that is built into that middle.

If necessary, you can delete the global value explicitly by simply setting its value to nil.

g = 1 - create a global change for g based on values ​​of 1

g = nil - the global value g is visible

MsgBox(tostring(g)) --> nil

All global changes are the fields of the original table, which is called a global table. This table is available through the global change _G. Since the fields of the global sharpening include all global changes (including _G), then _G._G == _G.

Local Lua changes

Whether local changes are to blame for the search for the keyword local. You can voice the local change using a script. The award may include the assignment of exchangeable cob value. If no meaning is given, change nil.

local a - voice local change a

local b = 1 - the local change b is announced and the value 1 is assigned to it

local c, d = 2, 3 - local changes c and d, give them values ​​2 and 3

The visibility area of ​​the local change begins after the shock and covers the rest of the block.

Note

The visibility area of ​​a change is the section of program code from which you can access the value that is stored in that change.

Under the block we mean:

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

body of function;

code fragment containing the keywords do...end.

If a local change is assigned to the position of any block, its visibility area expands for the remainder of the script.

local i = 1 – change i is local within the script

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

local a = i^2 - variable and local in the middle of the while loop

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

MsgBox(a) -->

if i > 5 then

local a - change and local in the middle then

MsgBox(a) --> 10

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

local a = 20 - changeable, and local in the middle do-end

MsgBox(a) --> 20

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

Regain respect

If possible, it is recommended to use local changes instead of global ones. Allowing the global name space to disappear will ensure improved productivity (access to local variables in Lua is increasingly limited to global ones).

Tipi data Lua

What types of data does Lua language support?

Lua supports the following data types:

1. Nil (nothing). Indicates the existence of the changeable value. This type of representation for single values ​​is nil.

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

For all logical operations, the value nil is treated as false. All other values, including the number 0 and the empty row, are treated as true.

3. Number. Serve as a manifestation of numerical values.

In numerical constants, you can specify a non-binding fractional fraction and a non-binding tenth order, which is specified by the symbols “e” or “E”. Integer numeric constants can be specified in the hexadecimal system using the 0x prefix.

Please provide valid numeric constants: 3, 3.0, 3.1415926, 314.16e-2, 0xff.

4. String (row). Serve for filing rows.

String values ​​are specified by looking at the sequence of characters placed in single or double legs:

a = "sequence"

b = "this is another row"

The rows placed in the folding legs can be interpreted as C-like sequences to control (escape sequences), which begin with the symbol “\” (backslash):

\b (space),

\n (row shift),

\r (carriage rotation);

\t (horizontal tabulation),

(reversible slash);

"" (foot);

(single foot).

Regain respect

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

de ddd - the sequence is no more than three digits.

The paws for the designated row can also be fitted with hanging square arms:

The designated row behind the additional square arms allows you to ignore all escape sequences, so that the row is created exactly as described:

local a = [] in Lua]=]

There will be a term: “the value of the row [] in Lua”

5. Function. Lua functions can be written to changes, passed as parameters to other functions, and returned as the result of a newly added function.

6. Table (table). A table is a set of “key” - “value” pairs, which are called fields or table elements. The keys and values ​​of the table fields can be of any type other than nil. Tables do not have a fixed size: at any time you can add a sufficient number of elements to them.

Report - in the article “Creating a table in Lua”

7. Userdata (Koristuvatsk data). Є a special type of data. Values ​​cannot be created or changed directly in a Lua script.

Userdata is used to represent new types created by the program that you use, or in libraries written by S. For example, the Lua extension libraries for CronosPRO are used to use this type to represent objects such as:

tribute banks (Bank class);

base data (class Base);

records (class Record) then.

8. Thread. Vikonannya follows the flow. These threads are in no way connected with the operating system and are supported inclusively by the features of Lua itself.

How do you set the change type in Lua?

Lua does not pass explicit data to the change type. The change type is set at the time the change value is assigned. Any change can be assigned a value to any type (regardless of the value of which type it was previously assigned).

a = 123 – change a is type number

a = "123" - now the type is changed to string

a = true – now the type is boolean

a = () - now the type table is changed

Regain respect

Changes to table, function, thread and userdata types do not store the data themselves, but save messages to other objects. When given, passed to a function as an argument, and returned from a function as a result of copying objects, they are not copied, only the messages sent to them are copied.

a = () – creating a table. I'll change the table

b = a - change b to use the same table as a

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

MsgBox(b) --> "10"

MsgBox(a) --> "20"

Other data have non-median values.

MsgBox(a) --> "20"

MsgBox(b) --> "10"

How can you determine the change type in Lua?

The type of value saved by the change can be specified using the additional standard function type. This function rotates the row to match the name of the type (“nil”, “number”, “string”, “boolean”, “table”, “function”, “thread”, “userdata”).

t = type (“string”) - t і “string”

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

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

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

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

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

How can you change the change type in Lua?

Lua automatically converts numbers into rows and patterns as needed. For example, if a series value is an operand in an arithmetic operation, it is converted to a number. The same numerical value that has settled there, where it ends up in a row, will be converted into a row.

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

a = "10" + 2 - a is similar to "10 + 2"

a = "-5.3e-10"*"2" - a is older -1.06e-09

a = “row” + 2 – Pomilka! It’s impossible to change the “row” to a number

Values ​​of any type can be clearly converted to a row using the standard tostring function.

a = tostring(10) - a is the old “10”

a = tostring (true) - a is ancient "true"

a = tostring (nil) - a is just “nil”

a = tostring (( = "this field 1")) - a is older than "table: 06DB1058"

From the front butt you can see that instead of the table, the function to string is not recreated. This can be recreated using the additional render function.

a = render (10) - a is the same as "10"

a = render (true) - a is old "true"

a = render (nil) - a is just “nil”

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

To explicitly change the value of a number, you can use the standard tonumber function. If the value is in a row that can be converted to a number (or even a number), the function rotates the result of the conversion, otherwise it rotates nil.

a = tonumber (“10”) - a is old “10”

a = tonumber("10"..".5") - a is older than 10.5

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

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

Posting comments in Lua

A Lua comment starts with two minus signs (--) and continues until the end of the line.

local a = 1 - single-row comment

Since immediately after the symbols “--” there are two square arms that open ([[), the comment is multi-ordered and goes up to two closing square arms (]]).

local a = 1 - [[ rich order

comment ]]

The hinged arms of the comments may be recessed. In order not to confuse them, a sign of equality (=) is inserted between the arms:

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

local a = [[Kronos Company]]

The number of "=" symbols means nesting:

local a = [=[value of the row [] in Lua language]=] --[==[

local a = [=[value of the row [] in Lua language]=]

Operations that are common in Lua

Viruses written in Lua can perform the following types of operations:

1. Arithmetic operations.

Lua supports the following arithmetic operations:

+ (addavannya);

- (vіdnіmannya);

* (multiplication);

/ (Podil);

^ (zvedenya at the steps);

% (surplus per division).

Regain respect

Arithmetic operations are constant, both up to numbers and up to series, which are always converted into numbers.

2. Leveling operations.

In Lua, the following operations for equalizing values ​​are allowed:

== (Rivno);

~= (Don't compare);

< (меньше);

> (More);

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

>= (more than one).

Regain respect

The equalization operations first rotate the logical values ​​of true and false.

The rules for rearranging numbers in a row (and likewise) do not apply when adjusting, so the expression “0” == 0 results in false.

3. Logical operations.

Before logical operations lie:

and (more logically I).

The and operation rotates its first operand, since it has the values ​​false and nil. In the other case, the operation rotates another operand (and this operand may be of the same type).

a = (nil and 5) - a is old nil

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

a == (4 and 5) - a is more than 5

or (more logical than ABO).

The or operation rotates the first operand if it is not false or nil, otherwise it rotates the other operand.

a == (4 or 5) - a is more than 4

a == (false or 5) - a is more than 5

Regain respect

Logical operations and and can rotate values ​​of any type.

The logical operations and and or calculate the value of another operand depending on how it is rotated. If this is not required, the other operand is not evaluated. For example:

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

not (more logically NOT).

The operation never turns true or false.

4. Concatenation operation.

To concatenate (unify) rows, use the operation (two points).

a = “Kronos.”-”..“Inform” - change a removes the value of “Kronos-Inform”

Regain respect

If one or two operands are numbers, they are transformed into rows.

a = 0..1 – change a subtracts the value “01”

5. Operation of doubling.

Lua has a dovzhin operation #, so you can use it to remove the dovzhin row.

a = "row"

len = #a - len more than 6

len = #“more row” - len 10

Regain respect

An additional operation # can be used to determine the maximum index (or size) of the array. The report is from the article “Working with Arrays in Lua”.

Operation priority in Lua

In the Lua language, each operation is carried out according to the current priority (in order of change):

2. not # - (unary)

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

Click scripts from forms

With each form (including form inserts) there is a script associated with each other, which is intended to contain functions that will result in the processing of this form and its elements.

When the form is launched, its script is downloaded from the light. For each form of an element, the system calls the corresponding handler function.

The form script, while not wanting to interfere with the call to the module function, is actually a module. This means that changes that are missing from the script form without the local keyword are not affected by the global definition and are only available in the middle of the script. If it is necessary to make any values ​​accessible to scripts of other forms, this trace is clearly visible in the global table _G:

local a = _G.var

Blocks of operators (instructions)

The main Lua operators are:

pretentiousness;

mental operator;

operators in the organization of cycles.

A group of operators can be combined into a block (warehouse operator) for an additional design do…end.

do - cob block

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

<оператор2>

<операторN>

end - the end of the block

The block opens a new visibility area where local changes can be made.

a = 5 - global value a

local a = 20 - in the middle of the do-end the local value is indicated

MsgBox(a) --> 20

MsgBox(a) --> 5 (here it is scaled up to global a)

Assignment operator in Lua

This changes the values ​​of the variable or table fields. At its simplest, attention can look like this:

a = 1 - variable a is given the value 1

a = b + c - variable a is assigned to the sum value of variable b and c

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

Lua allows multi-assignment as long as there are a number of changes that can be found under the assignment operator, and the values ​​of the number of expressions written under the assignment operator can be removed:

a, b = 1.5 * c - a is more than 1; b more expensive 5*c

If the value of the change is greater than the lower value, the change is given nil.

a, b, c = 1, 2 - a is more than 1; b more expensive 2; c one nil

If the meaning is greater, less changeable, “zaiv” meanings are ignored.

a, b = 1, 2, 3 - a is more than 1; b more expensive 2; value 3 not vikoristan

Multiple assignments can be used to exchange values ​​between variables:

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

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

Lua's mental operator (if)

The if statement verifies the truth of a given mind. As a matter of fact, the part of the code that follows the then keyword (then section) ends. Otherwise, the code that follows the else keyword is added (else section).

if a > b then

return a – if a is greater than b, rotate a

return b - otherwise - rotate b

The else section is unnecessary.

if a< 0 then

a = 0 - if a is less than 0, assign a value of 0

You can replace nested if statements with an elseif construct. For example, the targeting code:

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

return “Ivan” - like a is related to 1

elseif a == 2 then

return “Petro” - jakscho a dorіvnuє 2

elseif a == 3 then

return “Sergiy” - like a ancient 3

return “There is no such graver” - yakscho a - more often than not

Lua's while loop

The while operator is used for organizing loops with changeover and takes the following form:

while do

… - body of the cycle

Before the skin iteration cycle, the mind is checked :

As a result, the loop ends and the sequence is passed to the first operator following the while operator;

As the mind is true, the body concludes the cycle, after which all actions are repeated.

while i > 0 do - cycle from 10 to 1

t[i] = "field" ..i

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

while i > 0 do - the array has negative values

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

i = i - 1 - otherwise we go to the advancing element

if i > 0 then

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

MsgBox ("Array does not remove negative values")

Note

Loop with postumova (repeat) in Lua

The repeat operator for organizing loops with a post-order function looks like this:

… - body of the cycle

until

The body of the cycle ends with the doti, the doki of the mind I won’t be able to handle it. The reversal of the mind occurs after the body has been completed to the cycle, so in any event the body has to be completed at least once.

The value of array a is assumed, the sum cannot be overweighted 10

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

sum = sum + a[i]

until sum > 10

MsgBox ("Stacked"..i.." elements. Sum is "..sum")

To exit the loop before completion, you can use the break statement.

Note

Report on the peculiarities of the break operator - in the article “Break and return operators”

Loops with the for operator in Lua

The for operator is used to organize loops and allows two forms of notation:

simple (numeric for);

expanded (universal for).

A simple form of the for statement

A simple form of the operator looks like this:

for var = exp1, exp2, exp3 do

… - body of the cycle

The whole cycle is calculated for the skin value of the change cycle (medicine) var in the interval from exp1 to exp2, followed by exp3.

Note

Croc can't be bothered. And here vin is taken to be equal to 1.

for i = 1, 10 do - cycle from 1 to 10 with cycle 1

MsgBox("i one"..i)

for i = 10, 1, -1 do - cycle from 10 to 1 with cycle -1

MsgBox("i one"..i)

Regain respect

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

for i = 1, f(x) do - cycle from 1 to the value rotated by the function f()

MsgBox("i one"..i)

The change to the loop is local to the loop operator and is not assigned after completion.

for i = 1, 10 do - cycle from 1 to the value rotated by the f() function

MsgBox("i one"..i)

MsgBox (“After exiting loop i, one thing.”.i) - Incorrect! i one nil

Regain respect

The cycle change values ​​cannot be changed in the middle of the cycle: the effects of such changes are not transferred.

To exit the loop before completion, the break statement is used.

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

for i = 1,#a do - search for negative values ​​in the array

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

index = i - the index of the found value is saved.

break - and the cycle is interrupted

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

Note

Report on the peculiarities of the break operator - in the article “Break and return operators”)

Lua has gained a reputation for writing - a tool that can be used to script applications compiled in C++. At the same time, Lua is a completely independent language, which has its own interpreter, the ability to create modules, a large number of libraries, and due to which the language has a minimal size among its analogues. To put it simply, we have everything to create the same programs as in Perl, Python, and any other advanced programming.

I can give you some basic arguments for Lua:

  • - programs will be easily portable between Windows and Linux (it’s not a fact that the code will run without changes, but porting will actually take place painlessly, since there were no platform-specific libraries)
  • - low overhead of running programs
  • - high speed of work and availability of accessories
  • - the ability to quickly “glue” it to your program, be it a C-library - you won’t find a better “glue” for libraries
  • - acceptable minimalistic language syntax, with the possibility of implementation on new current programming paradigms
  • - programs in Lua are very easy to learn
  • - little memory loss

To demonstrate the power of Lua, I'll show you how to use it to create a small program to generate point-by-point graphs so that you can save graphics in the view of an image file.

As a graphical toolkit, we will use iup - a cross-platform library, built from the beginning with the Vikorist version of Lua.

Installing the Lua SDK
As part of the idea of ​​​​developing Lua as an independent language, a compilation of Lua for Windows was created to contain libraries that are necessary in everyday work and that crash when programmed under a designated OS: database robots, GUI, XML parsing etc. Don’t let me berate you that the version of Lua in the collection is 5.1, and not 5.2 - there is no particular difference between them in our version.

Make sure to install the folding one.

Brief description of the iup concept
I thought for a long time about how to describe the process of creating programs without going into the iup device. I would like to briefly describe its main ambushes:
  • - iup.dialog is the root element of the program interface - in which container all elements are located
  • - the positioning of elements in a container depends on additional layouts: setting rules for placing an element in a container. Iup itself will allow you to display the element according to the rules. The main containers are frame, vertical sizer, horizontal sizer.
  • - descriptions are specified for the type of functions attached to the widget
  • - after the dialogue is opened, the processing cycle starts
If you have previously written for GUIs such as Tk, WxWidgets or WinAPI, we know everything here. However, the program is clearly covered with comments.
Program code

Library connections iup require("iuplua") require("iupluacontrols") require("iuplua_pplot") - a library for working with Canvas to save graphics in a file require("cdlua") require("iupluacd") require("string " ) -- global changes for widgets and customization of programs -- maximum number of graphs plots_number = 5 -- tab widgets that will house data entry widgets for the skin graph tabs = () -- containers for the widgets of your choice which charts will have checkboxes = ( ) -- here we save widgets with data text about points coords = () -- caption widgets for the skin graph in Lua does not have a standard function 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 indicating the points function draw_plot(pwidget, pnum, data) x = data.value:split(", ") y = data.value:split(",") if checkboxes.value == "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 = "stay"} -- колбэк для кнопки "построить график" 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 -- дописать при необходимости нужное расширение pic = fs_dlg.value if not (string.sub(pic, string.len(pic)-3) == ".emf") then pic = pic .. ".emf" end -- создаем псевдо-холст, ассоциированный с файлом tmp_cv = cd.CreateCanvas(cd.EMF, pic .. " 400x300") -- выводим график на холст iup.PPlotPaintTo(plot, tmp_cv) -- сохраняем данные в файл cd.KillCanvas(tmp_cv) end end -- отображаем диалог с графиком plot_dg:showxy(iup.CENTER, iup.CENTER) -- запускаем петлю обработки событий для диалога if (iup.MainLoopLevel()==0) then iup.MainLoop() end end -- в цикле создаем вкладки, в которых мы будем размещать виджеты -- для сбора данных for i=1,plots_number do -- создание текстовых виджетов, куда будут вводиться координаты точек coords[i] = {} for j = 1,2 do coords[i][j] = iup.text { expand="HORIZONTAL", multiline = "YES", VISIBLELINES = 5 } end -- виджет для редактирования подписи к графику legends[i] = iup.text{ expand = "HORIZONTAL" } -- создаем контейнер вкладки и заполняем его элементами vboxes[i] = iup.vbox { iup.hbox { iup.label { title = "Graphic caption:" }, 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{} -- создаем фрейм для общих настроек графика frame = iup.frame { iup.vbox { iup.label{ title="Wikoristat data:", expand="HORIZONTAL" }, iup.vbox { unpack(checkboxes) }, iup.label{}, -- пустую подпись можно использовать как распорку iup.label{title = "Signatures"}, iup.hbox { iup.label{ title = "All X"}, global_legend }, iup.hbox { iup.label{ title = "All Y"}, global_legend }, iup.label{}, plot_btn }; expand = "VERTICAL", } -- создаем главное окно программы и наносим на него настройки и табы dg = iup.dialog { iup.hbox { frame, tabs }, title="We will have a schedule", size = "HALF" } -- показываем главное окно и запускаем обработку событий dg:showxy(iup.CENTER, iup.CENTER) if (iup.MainLoopLevel()==0) then iup.MainLoop() end !}!}

A few words about the throat
The script can be run using the following command:

Lua plotter.exe

For this type of library, connect to the clibs/ subdirectory, which is located in the directory where Lua for Windows was installed. To package the script and library as compactly as possible for transferring to another machine, just copy the following files into one folder (indicated with entries under 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/iupluacd51.dll clibs/iupluacontrols51.dll clibs/freetype6.dll

Don't forget to place the script and program in this folder. Now you can transfer this folder to another machine and run your program using the command indicated above. In any other case, installing libraries and runtime is not required.

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

Pouches
The app.bat launcher has been added to the archive with the working version for ease of reference.

Screenshots:

As a result, they eliminated, to be honest, a utility that had the same functionality as it was supposedly written by my “serious” program. In this case, the size of the throat and total volume is less than 2 MB. Memory storage is about 7 MB. The output code is available for editing, Lua itself is interactively understandable, which will make it easier to further edit such software on site.

In my opinion, this is a wonderful choice for writing initial software for schools and institutes, as well as for internal development at enterprises. Since weak machines are still present in such places throughout the SND, Lua has become increasingly popular in a similar manner, especially since the progressive arrival of Linux on desktops. In addition, the tendency to spend weekends on self-written software with motorized sophistication can be equated to national recklessness.

Tags: Add tags

© 2024 androidas.ru - All about Android