1. Use of functions
The following program demonstrates how to use functions and local variables in Lua.
Example e02.lua
-- functions function pythagorean(a, b) local c2 = a^2 + b^2 return sqrt(c2) end print(pythagorean(3,4))
Running result
5
Program description
In Lua, The Function Definition Format is:
Function Name (parameter)
...
End
Unlike Pascal, end does not need to be paired with begin. You only need to end the function.
In this example, the function is used to obtain the diagonal side of a right triangle and obtain the length of the oblique side. parameters a and B indicate the length of the right side, respectively,
The local variable is defined in the function to store the square of the oblique edge. It is the same as the C language and defined in the function.
The code will not be executed directly, and will be executed only when the main program is called.
Local indicates defining a local variable. If the local variable is not added, C2 is a global variable, and the local scope
Is between the end of the innermost layer and the matched keywords, such as if... end, while... end. Global variable
The scope is the whole program.
2. Loop statements
Example e03.lua
-- Loops for i=1,5 do print("i is now " .. i) end
Running result
I is now 1
I is now 2
I is now 3
I is now 4
I is now 5
Program description
Here we use the for statement.
For variable = parameter 1, parameter 2, parameter 3 do
Loop body
End
The variable takes parameter 3 as the step, and changes from parameter 1 to parameter 2.
For example:
For I = 1, F (x) Do print (I) End
For I = 10, 1,-1 do print (I) End
In Print ("I is now" .. I), we use..., which is used to connect two strings,
Even if I try to see what I mentioned in (1), I don't know if you have answered correctly.
Although I is an integer here, Lua will automatically convert it into a string type during processing, without worrying about it.
3. Condition branch statement
Example e04.lua
-- Loops and conditionals for i=1,5 do print(“i is now “ .. i) if i < 2 then print(“small”) elseif i < 4 then print(“medium”) else print(“big”) end end
Running result
I is now 1
Small
I is now 2
Medium
I is now 3
Medium
I is now 4
Big
I is now 5
Big
Program description
If else is easy to use, similar to the C language, but note that the entire if only needs an end,
Even if multiple elseif are used, it is also an end.
For example
if op == "+" then r = a + b elseif op == "-" then r = a - b elseif op == "*" then r = a*b elseif op == "/" then r = a/b else error("invalid operation") end
4. Try again
In addition to the for loop, Lua also supports multiple loops. Use the while... do and repeat... Until to rewrite the for program in this article.
1