- Lua язык программирования изучение
- Understanding validity ranges and blocks for the Lua programming tutorial
- Learning to program with the Lua control structures
- Learning more about functions with Lua
- Related articles
- DART Tutorial
- Learn how to Code
- Flutter tutorial for beginners: how to develop apps with this Google SDK
Lua язык программирования изучение
Determine the number of elements of a table / length of a string
Lua does not use any combined allocation operators like “+=” and “-=”, which can usually be found in many script languages. For incrementing and decrementing variables, the operation is written out explicitly:
price = 42.99 discount = 0.15 -- 15% discount price -= price * discount -- `-=` does not work in Lua -- Decrementation must instead be written out explicitly price = price - (price * discount)
Understanding validity ranges and blocks for the Lua programming tutorial
The concept of the validity range is important for any programming language. A variable only exists within a certain valid range. Like in JavaScript, variables in Lua are global by default. However, the continuous use of global variables is known as “anti-patterns” and should be avoided. In Lua, a solution can be found in the form of the “local” keyword. This allows you to limit the validity range of a variable to the surrounding block – comparable to the declaration via “let” in JavaScript.
-- This variable is global x = 5 -- Define a local variable local z = 10
The bodies of functions and loops open a new validity range in Lua. Moreover, Lua uses the concept of the explicit block. A block defines a new validity range for the code between the keywords “do” and “end”. This corresponds to the open/closing brackets “” in Java/C/C++. The following code example shows how blocks, validity ranges, and variables relate to each other:
-- Outer validity range do local x = 1 do -- inner validity range local y = 2 -- Generate `z` in the global validity range -- access local variable `x` from the outer validity range -- and local variable `y` from the inner validity range z = x + y -- `z` now has the value `3` end print(x) -- outputs `1` print(y) -- outputs `nil`, because `y` does not exist in the outer validity range print(z) -- outputs `3` end -- `z` is global, i.e. it exists outside the outer validity range z = z + 4 print(z) -- outputs `7`
Learning to program with the Lua control structures
Lua offers the normal control structures that can also be found in other programming languages. These include branches and loops. Here’s an example of Lua’s “if”, “then”, “else”, and “elseif” instructions:
limit = 42; number = 43; if number < limit then print("Under the limit.") elseif number == limit then print("Right on the limit…") else print("Over the limit!") end
Besides the classic “while” loop, Lua also recognizes its counterpart “repeat” “until”. This instruction can also be found in Ruby. It requires a reversal of the condition used. That means, a “while” with the condition “number=> limit”. Beware when using the “repeat” instruction! Regardless of the condition, the loop body is executed at least once. Here’s an example:
limit = 10 number = 1 while number limit
Like most imperative programming languages, Lua offers a “for” instruction in addition to the “while” loop. Two variants are used: a C-like variant with a loop variable as well as a variant with an iterator. Let’s first consider the use of the “for” instruction with the loop variable:
start = 1 end = 10 for number = start, end do print("Current number:", number) -- `1,2,3,4,5,6,7,8,9,10` end -- Explicitly set step to `2` step = 2 for number = start, end, step do print("Current number:", number) -- `1,3,5,7,9` end -- the step can also be negative step = -2 -- With a negative step, swap start and end to count in descending order for number = end, start, step do print("Current number:", number) -- `10,8,6,4,2` end
Surprisingly, the loop variable defined in the “for” loop is local, not global, without it having to be explicitly declared as local. This makes sense and, in this respect, Lua differs positively from JavaScript. There, a loop variable declared without “let” or “var” is global, which can lead to severe errors.
Now we can move on to Lua’s “for” loop with an iterator. In principle, the approach is like Python. Instead of incrementing a loop variable and using it as an index in a list, we iterate directly using the elements of the list. The “ipairs()” function is often used to generate the iterator. Here’s an example:
-- Define list of years decades = -- Access the individual years using an iterator for index, year in ipairs(decades) do print(index, year) end
Learning more about functions with Lua
As is the case in C/C++, Java and JavaScript, functions are defined with the “function” keyword. The function parameters are written in parenthesis after the function names. With Lua, however, the parenthesis can be left out for a function call with exactly one literal as a parameter. A Lua function does not necessarily have to return a value. According to the definition, a function without a value is a “procedure”:
-- Define procedure function hello(name) print("Hello", name) end -- Call function hello("good sir") -- this is also possible hello "good sir" -- the following will not work, however name = "Walter" hello name -- syntax error -- with a variable instead of a literal, the function must be called with parenthesis hello(name)
If you want to return a value from a function, the “return” keyword is used as normal. This ends execution of the function and returns the entered value. In the following code example, a number is squared:
-- Function with a single return value function square(number) -- the expression `number * number` is evaluated -- and its value returned return number * number end -- Square number print(square(9)) -- `81`
Like in Python and JavaScript, a function in Lua can accept a variable number of parameters. The parameters are stored in the special construct “(. )”. To access the parameters, it’s often useful to summarize them in a list with the expression “<. >”. Alternatively, you can use the “select<>” function to extract a parameter under the entered index. We can determine the number of parameters with the expression “#<. >”.
-- Print all parameters of a function function var_args(. ) for index, arg in ipairs() do print(index, arg) end end var_args('Peter', 42, true)
Besides the variable number of parameters, Lua also permits returning multiple values with a “return” instruction. This works similar to Python, but without the explicit “tuple” type. Like in Python, it’s normal to assign multiple variables to the return value for the function call. Here’s an example:
-- Function with multiple return values function first_and_last(list) -- return first and last element of the list individual return values are separated by a comma `,` return list[1], list[#list] end people = -- Assignment of return values to multiple variables first, last = first_and_last(people) print("The first is", first) print("The last is", last)
If one of the return values is not required, you can use the underscore (_) as a placeholder, following common convention, as shown in the following example:
function min_mean_max(. ) -- Set initial values for `min` and `max` to the first parameter local min = select(1, . ) local max = select(1, . ) -- Initially set mean value to nil local mean = 0 -- Iterate using the numbers -- We do not need the index variable -- and therefore use `_` as a placeholder for _, number in ipairs() do -- Set a new minimum if necessary if min > number then min = number end -- Set a new maximum if necessary if max < number then max = number end -- Sum the numbers to find the average mean = mean + number end -- Divide the numbers by their quantity mean = mean / #return min, mean, max end -- Here we do not need the `mean` value -- and therefore use `_` as a placeholder min, _, max = min_man_max(78, 34, 91, 7, 28) print("Minimum and maximum of the numbers are", min, max)
In Lua, functions are “first-class citizens”. In other words, they can be bound to variables and can therefore also be transferred to other functions as parameters. What’s more, a function can act as a return value of a function. Overall, Lua thus enables functional programming – shown here using the well-known “map()” function as an example:
-- `map()` function in Lua -- Accepts a function `f` and a list as parameters function map(f, list) -- Create new list for output values local _list = <> -- Iterate using the elements of the list with an index for index, value in ipairs(list) do -- Apply function `f()` to the current value of the list -- and save the return value in a new list on the same index _list[index] = f(value) end -- Return new list return _list end -- List of numbers numbers = -- Function applied to all elements of the list function square(number) return number * number end -- Generate the squares via the `map()` function squares = map(square, numbers) -- `` -- Output squared numbers for _, number in ipairs(squares) do print(number) end
Recursion is often used in functional programming. A function calls itself repeatedly with modified parameters. Here we need to exercise special caution in Lua. Functions that are accessed recursively should be declared explicitly as “local”.
function f() -- Recursive call f() -- may refer to the global variable `f` end -- instead local function f() -- Recursive call f() -- refers to the local function end -- equivalent to local f; -- Declare variable `f` explicitly as `local` f = function() -- Assignment of the function to the local variable `f` f() -- is guaranteed to refer to the local function end
Related articles
DART Tutorial
This DART tutorial will help you to get started programming with DART. If you’re familiar with other programming languages, you’ll notice that DART tries to use simple and clear syntax to overcome some of the basic weaknesses of JavaScript. Check out the examples in our DART language tutorial and try your hand at writing your own code snippets.
Learn how to Code
Welcome to the digital age: every day the average American spends hours looking at smartphone screens and PC monitors. But most still lack even a basic understanding on how the programs affecting their everyday life work. If you think you may fit into this demographic, don’t worry: thanks to online courses, videos tutorials, and supportive internet communities, it’s never been easier to learn…
Flutter tutorial for beginners: how to develop apps with this Google SDK
Over the years, Google has not only launched a number of useful services including Gmail, Google Maps, and Google Workspace, it has also published a variety of tools for developing software. One of these tools is the SDK Flutter which is particularly useful for mobile app developers. In the following Flutter tutorial, we will show you how to create a simple app using this framework.