How to set up smartphones and PCs. Informational portal
  • home
  • Safety
  • Lua command programming language. Loops with for statement in Lua

Lua command programming language. Loops with for statement in Lua

Lua(from the Portuguese "moon") is an interpreted programming language developed by the Computer Graphics Technology Group of Pontifical Catholic University of Rio de Janeiro in Brazil. is freely distributed, open source source texts in C language. In terms of its capabilities and implementation, it is closest to JavaScript, but, from my point of view, it is more flexible and has wider capabilities. Despite the fact that Lua does not have such concepts as “class” or “object”, on its basis it is quite possible to build OOP programs based on metatables, which also allow you to implement, for example, operator overloading.

In this lesson I want to give you some of the most general information about this language, and in the following lessons I will show you in practice how you can use the Lua language to solve game programming problems.

History of Lua

As I said above, Lua was developed by one of the departments of the Catholic University of Rio de Janeiro. This happened back in 1993. But from that moment on, it was actively developing and new versions of Lua were periodically released - it became more convenient, faster, and more functional. IN this moment stable version Lua is 5.1, but an alpha version of 5.2 is already available.

Lua types

IN Lua There are eight main data types:

  • nil (undefined)
  • boolean (boolean)
  • number
  • string
  • function
  • userdata
  • thread
  • table

Lua is a language with dynamic data types. Any variable in Lua can contain values ​​of any of the above types. All values ​​in Lua can be stored in variables, used as arguments when calling functions, and returned as the result of the function execution.

Lua tables

Tables are the most important type data in Lua - tables are the basis for storing and using custom types data: structures, arrays, lists, sets, etc. are implemented in Lua precisely through tables. A table in Lua is a set of [Key, Value] pairs, where the key can be a value of any type except nil.

Lua device

Like many interpreted programming languages, the Lua implementation has a separate source-to-executable bytecode compiler and a virtual machine for executing the generated bytecode. In the case of Lua, the bytecode is not machine instructions, but commands “ virtual processor Lua" with multiple registers, which improves execution efficiency. The Lua virtual machine also uses the principle of garbage collection (similar to Java or .NET), which allows the programmer not to worry about allocating/deleting memory - this is handled by the interpreter itself.

For critical tasks, there is a Lua: compiler that allows you to get faster code.

Where is Lua used?

Lua, over the many years of its existence and development, has won the hearts of many software developers and nowadays it is used in a wide variety of areas of programming: scripting computer games(Crysis, Far Cry, Diablo 3, S.T.A.L.K.E.R.), on MMO game servers (World of Warcraft, Allods Online), in graphics packages (for example, in Adobe Photoshop Lightroom), in game engines and game designers (INSTEAD), for GUI programming of some applications (the same Photoshop Lightroom) and in many other tasks.

Lua Documentation

In general, there is a lot of documentation, as well as examples of use, on the Internet. Therefore, I will not delve too deeply into this topic. I can only say that I can advise you to read

Introduction

This guide is intended for those with limited experience with LUA. We'll cover the basics of how to format code, the building blocks for you to create more complex code, and provide some examples. The manual is written in such a way that it can be put into practice immediately. Therefore, you should open Tabletop Simulator and your LUA editor to proceed further.

This is the first tutorial in this series. The second is Learning Lua More. The third is a set useful functions called Learning Lua Functions.

Before the first key press

Firstly, I would highly recommend installing Atom if you are going to do scripts in Tabletop Simulator. It knows what functions can be used and will import/export code to/from TTS.

Then you should add to bookmarks. You will link to this site often once you start writing your scripts. Here you will find special functions in Tabletop Simulator and how they work. You will most often use the API and Object pages, by at least, in my experience.

Preparation

When you save your scripts in Tabletop, it will use your last save, and then load the scripts into it. Therefore, for any script you intend to write, you will need to do the following:

  • Prepare the table the way you want it.
  • Save the table.
  • Load the table.
For this exercise, take an empty table and create two objects (I used a square block and a rectangular block) as well as a red checker.

Repeatedly press it because of course you will.

EXTRA CREDIT: When you create tables, there are several ways to do it. The technique used here was to ensure visual clarity. However, creating button parameters like this takes up a lot of space if you have a lot of buttons. I prefer to design my tables in a way that saves space but doesn't go overboard. Using our example, I would create the options table like this:

button_parameters = ( click_function="buttonClicked", function_owner=nil, label="Press Me", position=(0,0.8,0), rotation=(0,0,0), width=500, height=500, font_size= 100 )

EXTRA CREDIT: This is the perfect time to start playing with different things, which you can do with objects. Go to the Object page in the Knowledge Base and try the material. Move objects, make them switch positions, change their colors, whatever you think.

EXTRA CREDIT: Additionally, each time the button is clicked, the click_function runs with two parameters. The first is a reference to an object, specifically a reference to the object to which the button is bound. The second is the color (for example, "Blue") in string format of the color of the player who pressed the button.

5) Logical statement

Comparison of Variables

Again remove all scripts inside the buttonClicked() function. We're going to create a new variable and then change it. The new variable will be of boolean type. Boolean values ​​can only be true, false. Boolean values ​​are always written in small letters. First, we'll create our variable under our Objects and Checkers GUID.

trueOrFalse = true

Then, in buttonClicked, we will set up some logic to check if trueOrFalse is true. If it is true, it will print that it is True and switch it to False. If the button is pressed again, it will print that it is False and switch the value to True.

if trueOrFalse then print("trueOrFalse was true.") --trueOrFalse was true. trueOrFalse = false else print("trueOrFalse was false.") --trueOrFalse was false. trueOrFalse = true end

We could also write it like this "if trueOrFalse == true then", but this is not necessary. Remember that the IF statement needs to be passed a Boolean value. And since trueOrFalse is already one of those, we can drop the "== true".

A loop is a section of code that can be executed multiple times. This is one of the more complex elements you will use in LUA. They often come with tables, allowing you to run code for each record in the table.

This is another type - ipairs. Pairs are needed for tables without numeric keys, and ipairs are needed for tables with sequential numeric keys (arrays). ipairs goes in order, when pairs can go in any order.

Lua is a programming language created by Roberto Ierusalimski, Valdemar Selis and Luis Henrique de Figueiredo. It’s hard to believe that such a popular language could have been created not somewhere in Silicon Valley or MIT, but in sunny Brazil. In a country that seems to be located quite far from the centers of concentration of IT. However, in one of the divisions of the Catholic University of Rio de Janeiro they were able to create such a flexible and powerful language that it is now widely used in many fields.

It all started with the development of an auxiliary language for oil company PETROBRAS. Petroleum engineers needed a graphical front end to process data to simulate certain processes. Moreover, the equipment could be very different - PC DOS, UNIX, Macintosh, so many existing languages ​​(Perl, for example) simply were not suitable, since they only worked on one of these systems. At this stage, a language called DEL (data entry language) was developed. Over time, the capabilities of this language became insufficient, so it was developed new language, called SOL (simple object language). And finally, in 1993, the developers realized that they could be combined into one full-fledged programming language, which was called Lua (in Portuguese, Sol is the sun, and Lua is the moon). By the way, in 1996, Roberto Ierusalimsky and other authors of the language decided to tell the world about their work and sent an article about Lua to the magazine “Software: Practice & Experience”. Later, Lua was published in the magazine “Dr. Dobb’s”, from which one of the main developers of adventure games at LucasArts learned about it. Deciding to use Lua instead of their own scripting language, he was amazed by its simplicity and efficiency. As a result, most of the game being developed at that time was rewritten in Lua, which contributed to its growth in popularity.

Philosophy of the Lua language

Most of all, the ideology of Lua is similar to JavaScript. For example, they both have a prototype model for implementing OOP. However, Lua is a much more flexible and powerful language. In Lua they are used virtual machine and a garbage collector, which makes it more similar to Java, but this does not prevent it from maintaining its simplicity and elegance.

The Lua language is based on tables, implemented using associative arrays. A table here means a set of data where each of the unique keys has its own value. Using tables in Lua, you can represent almost any data - ordinary arrays, sets, symbol tables, etc. Functions can also be described in table fields. Simply put, if you want a certain character or object to appear in your favorite game, then you only need to know its name to enter a function into the table to create this object and enter the coordinates of the game world in which it should appear.

It is also worth mentioning metatables - tables that allow you to change the behavior of other tables. For example, determine whether addition of non-numeric values ​​is acceptable in some situation. Or define the launch of “garbage collection” (memory cleaning) for some event.

Where is Lua used?

Although Lua is also used in industrial applications, this language has gained the greatest popularity in game development. Since it can be difficult for developers to make changes to the game engine, and game designers constantly have to make changes to the way levels or characters work, Lua can be simply irreplaceable here. It is very easy to describe the interaction between players, program NPCs (peasants in Skyrim) or the behavior of bosses using scripts, which can then be quickly changed without affecting the engine.

The most famous game that uses Lua now, of course, is World of Warcraft. The WoW interface (menu, chat, etc.) is written on it. Lua was also used in games such as Crysis, King’s of Bounty, Warhammer, Allods online, CS, Stalker, The Witcher, Sim City, Far Cry, Civilization V, etc.

Plugins for nmap, wireshark, nginx or bots for Telegram are also often written in Lua. Wikipedia also plans to use Lua for embedding into MediaWiki (you can try it in the English version).

Lua is also used in astrophysics research observatories and major universities around the world (such as the Technical University of Berlin). Lua has also become something of a national programming language in its homeland and is used by many local companies and research centers in the most different areas activities.

Difficulty of learning Lua

Lua is quite easy to learn. There are many resources and video tutorials on it on the Internet. In addition, gamification helps a lot here. If your favorite game allows you to create mods in Lua, then try experimenting with game world in the learning process. This will make learning programming fun and effortless.

Pros/Cons of Lua

The advantages of Lua include:

  • good portability. If you need to, for example, port a program from Windows to Linux, then, with the exception of some platform-specific libraries, the code will not need to change much.
  • the ability to quickly add a C library to a Lua application
  • ease of program deployment
  • easy syntax
  • Lua programs consume little memory
  • distributed under the MIT license, so can be used for free for business projects

Of the minuses:

Lua works as well as a scripting language can. But most often it is used in conjunction with other languages, although it is quite capable of performing some tasks independently. Therefore, you will need to know at least one more, for example, C or C++. However, undoubtedly, knowledge of Lua will be a big plus for you when applying for a job as a game developer.

Related Technologies

LuaJIt- JIT compiler for Lua. Used for tasks in which execution time is critical. Works approximately six times faster than the standard interpreter.

Love2D is a popular framework designed for developing 2D games in Lua.

Corona SDK- a framework for creating applications for iOS and Android using Lua. Since 2015, a free version has appeared.

This series of lessons I have in mind will discuss the Lua programming language. I will try to make the presentation as accessible as possible for beginners, and I will focus on them. That is, experienced Lua coders most likely will not learn anything new from here (I’m sure they will only find room for quibbles and comments, which, in fact, are even welcome on their part), but if you don’t have extensive programming experience behind you , then I think you'll take something away.

The entire series will not obey any system. The lessons will sequentially introduce a number of language constructs, so that by the third or fourth lesson you can already write your own programs. My goal is to push you to self-study language, help you feel it, and not explain it from A to Z - if you want to master the language completely, read reference guide(which, although poorly, is translated into Russian: http://www.lua.ru/doc/). The sooner you move from “for dummies” lessons on the Internet to studying the reference book, the better.

If something is unclear, be sure to ask a question in the comments, and I and other participants will try to help you.

Lua is a popular, easy-to-learn, embedded, interpreted, dynamically typed programming language general purpose. No, you don’t have to understand half the words said in the previous sentence - the main thing is to know that it is popular and uncomplicated. By the way, it has earned its popularity due to its simplicity, as well as the small size of the distribution (about 150 kilobytes). Lua scripts are supported big amount applications, including games. World of Warcraft and S.T.A.L.K.E.R. use the Lua language. My favorite game engine will allow you to easily create a variety of games using Lua. As you can see, Lua opens up a lot of horizons for you!

Before we begin, you should set up a programming environment: that is, find a program that will accept the Lua code you write and execute it: an interpreter. There are three options:

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

Lua can only be downloaded from the official website source codes interpreter. However, after studying http://lua.org/download.html in the Binaries section, you may find links to sites with executable files for Windows. One of them: . Download one of the archives from there (matching your platform: Win32 or Win64) and unpack it somewhere, preferably into a directory with a short path: like C:\lua. From now on I will assume that you are using Windows and your interpreter is there.

Users of operating systems on Linux based in this sense it is simpler: they just need to use a package manager and install Lua from the repositories. On Debian and Ubuntu this is done with the command apt-get install lua, and on Fedora, Red Hat and derivative distributions - yum install lua. However, do not trust me blindly and refer to your reference book. operating system to find out exactly how this is done for you.

2. Use an online interpreter.

Found at http://www.lua.org/demo.html. At first it may be enough, but later, when we touch on modules, you will be forced to use the offline version. Using the online interpreter is very simple: enter your program in the text box and click the Run button. The program will be executed, and the Output window will display the output of your program, as well as error reports, if any, you made.

3. Use an IDE.

For example ZeroBrane Studio: http://studio.zerobrane.com/. There are others - look on the Internet.

There are currently two slightly different versions of Lua in use: 5.1 and 5.2. I will focus on the most latest version- version 5.2, but I’ll definitely point out important differences between it and 5.1, since the latter is also quite common. By the way, Lua 5.1 executes code one and a half times faster than Lua 5.2, just so you know.

=== Lesson No. 1 ===

So, let's begin. Create in isolation from extraneous files folder main.lua file and write in it:

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

Then run in command line(don't forget to move to the main.lua directory using the cd command):

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

The Lua interpreter will respond with:

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

In principle, this was to be expected. In the program we called the print function. The print function accepts arbitrary number parameters and displays them sequentially on the screen. IN in this example we passed it the string (chain of characters) "Hello world!". You can just as easily pass it as a parameter:

200?"200px":""+(this.scrollHeight+5)+"px");">
print(8) -- some decimal number
-- will output: 8

Print(0xDEADBEEF) -- hexadecimal number
-- will output: 3735928559

Print("0xDEADBEEF") - but this is a string, not a number! Do you see the quotes?
-- will output: 0xDEADBEEF

Print(1.35e-4) -- floating point number ( a fractional number)
-- Will output 0.000135. 1.35e-4 should be understood as "1.35 times
- by ten to the minus fourth power,” if anyone doesn’t know.

Print((198*99)-3*500 + 14/88) -- expression
-- Prints the value of the expression: 18102.159090909. Not a bad alternative
-- desktop calculator!

Print(198/7, "fertilizer", 2^9) -- several arbitrary parameters
-- sort of. The values ​​of each of them will be displayed, separated by signs
-- tabs:
-- 28.285714285714 fertilizer 512
-- Please note that quotes around fertilizer are not displayed!

Print(1.35) -- two numbers, not the decimal fraction 1.35!
-- A comma is used to separate parameters.
-- Will output:
-- 1 35

The "--" sign is not just an imitation of the dash sign, which is inserted for beauty. The "--" sign in Lua marks comments: hints for the programmer that are ignored by the interpreter, and 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 execute the instruction.

Note to the hostess: if you want to print only one line, you can write the print call like this, without parentheses:

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

Convenience is certainly questionable: just keep in mind that this is possible. However, such calls are unacceptable:

200?"200px":""+(this.scrollHeight+5)+"px");">
print 2 will not work, 2 is not a string.
print 2*2 + 6 -- it won't work anyway

Str = "string!!" -- assigned the value "string!!" to the variable str
-- read about variables below
print str -- won't work either.

In each of the above cases, the program will simply refuse to work. Thus, in a "bracketless" call, the function name can only be followed by a string literal (that is, a sequence of characters enclosed in quotes), and nothing else. I'll talk about this feature in a little more detail in the future, but for now, that's enough.

In any good language In programming, it is possible to declare variables: small containers that can contain some data. In Lua this is done like this:

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

For example:

200?"200px":""+(this.scrollHeight+5)+"px");">
star = 8 -- Now the star variable stores the number 8
wars = "owl" -- In the wars variable - the string "owl"
jedi = 42/2 -- In the variable jedi - the number 21
luke = star*jedi -- In the variable luke - the number 168 (yes, 21 times 8)

The values ​​of variables and expressions with them can also be displayed:

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

Just don't try to add the variables star and wars - trying to add 8 to "owl" won't do you any good!

As you should have noticed, the name of a variable can be almost anything: the main thing is that it does not start with a number. Seriously, you can even declare a variable called print, and then the print function will stop working because the name print will refer to the newly declared variable. But there is a group of words that are prohibited from being used as variable names - these are language keywords that we have not yet become acquainted with, but which are definitely worth a look:

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

By creating a variable with one of these names, you will cause an error in the program, and it will definitely not work. Please note: in Lua 5.1 keyword there is no goto, and you can call a variable that way, but you better not do that.
Also note that variable names are case sensitive. This means that foo, fOo, fOO and FOO are four different variables, so if you wrote the name of some variable lowercase letters, and later wrote it in capitals, then most likely the program will not work correctly.

And now alone important point: what happens if you, accidentally or intentionally, refer to a non-existent variable? In most other languages ​​this will cause an error, but in Lua this situation is acceptable. It is treated as if the non-existent variable actually exists, but its value is nil. nil- remember this word! is a special value type in Lua that means "nothing". Not zero and not an empty string (a string like "" - try displaying it on the screen), but simply nothing. Compare this with this model: there are two people, one of them has a bank account but no money in it, and the other has no bank account at all. In Lua terms, it will be considered that the first one has $0 in his account, and the second one has $0 in his account. nil. And not even dollars, but simply nil. I hope I didn't confuse you.

Try, for example, running this program:

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

Thus, the variable baz, which does not exist but is thought to exist, has the value nil, and the print function understands this and prints it to the screen as the string "nil". Lua has good method checking the existence of a variable: if the value of the variable is not nil, then it is at least declared. On the other hand, you can explicitly declare a variable equal to nil:

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

This can be done, and although it seems stupid at first glance, it is sometimes done. In subsequent lessons you will learn who and why, and you will probably start doing the same. Sometimes, of course.
Be careful with nil: you can print nil, but do things with it arithmetic operations it is forbidden! That is, if you can get away with print(nil), a construct like 99+nil will throw an error, even if you wanted 99+nil to equal 99. Believe me, I was upset when I found out too.

Summary:
1. We learned about the print function, what it can do and how to call it correctly without parentheses.
2. We learned how to declare variables, how to evaluate expressions (albeit just a little), what names variables can have.
3. We learned about nil, became imbued with its mystical mystery and gained confidence that in the future we will have a lot to do with it.

For those who are inquisitive and want to strengthen their knowledge, I offer simple exercises, which you don’t have to do if you already feel competent enough:
1. Write a program that prints the chorus of your favorite song.
2. Try to derive the values ​​of the following expressions. Try to understand why some of them work and some don't. See what errors are caused by expressions that don't work.

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


3. Write a program that exchanges two variables with values. That is:

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


Make a equal to 8086 and b equal to 6502. To do this, create a third variable and make some simple rearrangements. Make sure the problem is solved correctly by calling print(a,b) before the exchange and print(a,b) after.

Best articles on the topic