{}const=>[]async()letfn</>var
BasicsDevelopment

Learn Lua easily: first steps in programming with clear examples

Start programming with Lua! A simple guide with examples will help you learn the basics of the language. Let's move on to new knowledge!

К

Kodik

Author

4 min read

Lua Basics: A Simple Guide with Clear Examples

Lua is a simple and convenient programming language that is ideal for beginners. It is used to create games, applications and programming of various systems. In this article, we will analyze the basics of the Lua language with simple explanations and examples.


Why is Lua suitable for beginners?

  1. Simplicity: Lua code is easy to read and understand.

  2. Flexibility: Lua is suitable for a variety of tasks, from games to embedded systems.

  3. Lightness: Lua runs fast and takes up little memory.


Let's start learning Lua!

1. Variables and data types

Variables are "boxes" in which we can place data in order to work with them later. For example, you can store a person's name or age. Here's how it's done in Lua:

local name = "Alice"  -- Здесь мы создаем переменную 'name' и кладем туда строку "Alice"
local age = 12        -- Создаем переменную 'age' и кладем туда число 12
local isAdult = false -- Переменная 'isAdult' содержит значение false (ложь)

Now you can use these variables in the code. For example:

print("Name: " .. name)  -- Выводит: Name: Alice
print("Age: " .. age)    -- Выводит: Age: 12
print("Is adult: " .. tostring(isAdult))  -- Выводит: Is adult: false

Please note: In Lua, variables can be combined (concatenated) with text using ... For logical values (for example, true or false), you need to use tostring to convert them to text.


2. Conditional statements

Conditional operators allow the program to make decisions. For example, if the temperature is high, you can display the message "Heat".

local temperature = 15  -- Переменная хранит текущую температуру

if temperature > 20 then
    print("It's warm outside.")  -- This is done if the temperature is greater than 20
elseif temperature > 10 then
    print("It's cool, wear a jacket.")  -- Это выполняется, если температура от 10 до 20
else
    print("It's cold, wear a hat!")  -- Это выполняется, если температура 10 или меньше
end

How does this code work?

  • If the temperature is greater than 20, the program will execute the first block print("It's warm outside.").

  • If the temperature is greater than 10, but less than or equal to 20, the second block will be executed.

  • If the temperature is 10 or below, the third block will be executed.


3. Cycles

Loops allow you to repeat actions several times. For example, you can display a message five times in a row.

Example of a cycle for:

for i = 1, 5 do
    print("Message number: " .. i)
end

How does it work?

  • The for loop creates the i variable, which starts at 1 and increments by 1 until it equals 5.

  • Each time the loop is executed, a message with the current number is displayed.

Result:

Message number: 1
Message number: 2
Message number: 3
Message number: 4
Message number: 5

Example of a cycle while:

local counter = 3  -- Начинаем с 3
while counter > 0 do
    print("Remaining seconds: " .. counter)
    counter = counter - 1  -- Уменьшаем счетчик на 1 каждый раз
end

How it works while?
The loop is executed while the condition (here counter > 0) remains true.

Result:

Remaining seconds: 3
Remaining seconds: 2
Remaining seconds: 1

4. Functions

Functions are small "blocks" of code that can be used many times. This is convenient when you need to repeat the same logic.

Example of a function:

local function greet(name)
    print("Hello, " .. name .. "!")
end

greet("Alice")  -- Выведет: Hello, Alice!
greet("John")   -- Выведет: Hello, John!

How does it work?

  • We create the greet function, which takes the name parameter.

  • Inside the function, we combine the text with the name and display it.

  • The call to the greet("Alice") function passes the "Alice" string to the name parameter.


5. Tables

Tables in Lua are like boxes where you can store a lot of data. They can be lists (arrays) or dictionaries.

Array example:

local numbers = {1, 2, 3, 4, 5}

for i, value in ipairs(numbers) do
    print("Element " .. i .. ": " .. value)
end

How does it work?

  • The table numbers contains numbers from 1 to 5.

  • ipairs allows you to go through all the elements of the array.

  • i is the element number, and value is its value.

Result:

Element 1: 1
Element 2: 2
Element 3: 3
Element 4: 4
Element 5: 5

Dictionary example:

local person = {name = "Alice", age = 12}

print("Name: " .. person.name)  -- Выведет: Name: Alice
print("Age: " .. person.age)    -- Выведет: Age: 12

How does it work?

  • Table person contains keys name and age.

  • To get the value, use person.key, where key is the key name.


Conclusion

Lua is a great language to start programming. It is simple, understandable and allows you to quickly see the results. Try experimenting with the examples in this article to better understand how variables, loops, and functions work. With Lua, programming becomes fun and accessible!

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card