Description of LUA basic syntax

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

Description of LUA basic syntax

This section provides a brief introduction to basic Lua syntax, adapted fromRUNOOB.COMBasic Teaching. If you have any questions, please contact

for assistance. Lua's syntax is relatively simple and easy to understand, yet powerful. Therefore, a brief summary of some Lua syntax rules is provided to help you get started quickly.

1. Comments

1.1 Single-line comments

Comments are always necessary when writing a program. In Lua, a single-line comment starts with two consecutive dashes "--" and continues until the end of the line. This is equivalent to the "//" comment in C and C++ languages, as shown below

---------- HTTP POST CHANGE PROJECT START ----------
function on_http_finish_cb(key, value)

    if key=='data' 
    then
        -- do logical operations, user code
        bell_cnt = 0
    end
end

. 1.2 Multi-line comments

The comment starts with "--[[" and continues until "--]]". This kind of comment is equivalent to "/ in C language.../" comment in C language, as shown below

---------- HTTP POST CHANGE PROJECT START ----------
function on_http_finish_cb(key, value)
    if key=='data' 
    then
    -- do logical operations, user code
        bell_cnt = 0
       --[[ for i = sc_comeState, sc_bellFinsh
        do
            set_text(i, 3, '00 : 00')
        end--]]
    end
end

. 2. Statement blocks

In C, statement blocks are enclosed in curly braces "{" and "}" while in Lua, they are enclosed in do and end. End indicates the end of the most recent code block, for example:

for i = 0, 10
do 
    print("Hello") 
end

Or use then and end to enclose

if 1 + 1 ==2
then 
    print("Hello") 
end

3. Variable Types

Lua is a dynamically typed language without type definitions (types like C, integer, unsigned, character, etc.), and only requires variable assignment. Values can be stored in variables, passed as arguments, or returned as results. There are 8 basic types in Lua: nil, boolean, number, string, userdata, function, thread, and table. The commonly used types in actual screen applications mainly include the following

TypeDescription
nilThis is the simplest, with only the value nil belonging to this category, representing an invalid value (equivalent to false in conditional expressions). In applications, avoid using the nil value and perform illegal checks
numberThe MCU of the screen is 32-bit. In actual screen applications, the assigned numerical values are equivalent to long integers or single-precision floating-point types
stringStrings are represented by a pair of double quotation marks or single quotation marks
tableIn Lua, a table (table) is actually an "associative array", where the array index can be of numeric, string, or table type. In Lua, tables are created using "construction expressions", the simplest of which is {}, used to create an empty table
functionFunctions written in C or Lua

3.1 nil (null)

The nil type represents a value without any effective value, and it only has one value -- nil. For example, printing a variable that has not been assigned a value will output a nil value:

> print(type(a))
nil
>

Boundary value judgment: In practical applications, it is best to check whether the referenced variable is null or not to prevent it from being null.

if type(a) == 'nil'
then
    –-user code
else
    -–user code
end

3.2 Number

By default, Lua only has one type of number -- double.However, the MCU of the screen is a 32-bit processor, so it only supports single precision when running on the screen.

The following are all considered as types of number:

local a = 2
local b = 2.2
local c = 0.2
local d = 0.2e-1

print(type(a))
print(type(b))
print(type(c))
print(type(d))

Running example, the execution result of the above code:

>number
>number
>number
>number
>>number
>number

3.3 String

A string is represented by a pair of double quotation marks or single quotation marks.

local string1 = "this is string1"
local string2 = 'this is string2'

3.4 Table

Equivalent to an array in C, in Lua, a table is created using a "construction expression". The simplest construction expression is {}, which is used to create an empty table. You can also add some data to the table and initialize it directly. The subscript starts from 1 by default. The output test is shown below

-- 创建一个空的 table
local tbl1 = {}
-- 直接初始表
local tbl2 = {"apple", "pear", "orange", "grape"}
print(tbl2[0])
print(tbl2[1])

Running example, the execution result of the above code:

>nil --报错
>apple

Assign a value to the subscript 0 of the table, and the output will be normal

-- 直接初始表
local tbl2 = {"apple", "pear", "orange", "grape"}
tbl2[0] = "banana"
print(tbl2[0])
print(tbl2[1])

Running instance, the execution result of the above code is:

>banana
>apple

3.5 function

In Lua, a function definition is declared as follows and must be defined above the called object

-- function_test.lua 脚本文件
function factorial1(n)
    if n == 0 
    then
        return 1
    else
        return n * factorial1(n - 1)
    end
end

print(factorial1(5))

Running instance, the execution result of the above code is:

>120

4 Variable definition

Before using a variable, it needs to be declared in the code, that is, the variable is created. The default value of a variable is always nil

Global variable: All variables in Lua are global variables, even within a block or function, unless explicitly declared as local variables using the keyword `local`

Local variable: The scope starts from the declaration position and ends at the end of the block where it is located

-- test.lua 文件脚本
a = 5               -- 全局变量
local b = 5         -- 局部变量

function joke()
    c = 5           -- 全局变量
    local d = 6     -- 局部变量
end
print(c,d)          --> 5 nil

do
    local a = 6     -- 局部变量
    b = 6           -- 对局部变量重新赋值
    print(a,b);     --> 6 6
end
print(a,b)          --> 5 6

5 Control statements

5.1 if (conditional statement)

The conditional expression result of a control structure can be any value. Lua considers `false` and `nil` as false, and `true` and non-`nil` as true. It is important to note that in Lua, `0` is considered `true`:

local a = 0
if a == 0
then
    print("a = 0")
elseif a > 0 
then
    print("a > 0 ")
else
    print("a < 0 ")
end

Running instance, the execution result of the above code is:

>a = 0

Switch case statement is not supported

5.2 while(loop)

When the condition is true, the program repeatedly executes certain statements. Before executing the statements, it checks whether the condition is true

local  a = 10
while(a > 0 )
do
    a = a - 1
end

5.3 for(loop)

In the Lua programming language, the syntax format for numeric for loops is:

  • Numeric for loop
  • Generic for loop
Numeric for loop

In the Lua programming language, the syntax format for numeric for loops is: var varies from exp1 to exp2, increasing by exp3 each time, and executes once"execution body". exp3 is optional; if not specified, it defaults to 1.

for var=exp1,exp2,exp3 do  
    <执行体>  
end

Instance loop outputting values 1-5:

for i=1,5 do
    print(i)
end

Running the instance, the execution result of the above code is:

>1
>2
>3
>4
>5
Generic for loop

The generic for loop iterates over all values through an iterator function, similar to the foreach statement in Java. The syntax format of the generic for loop in the Lua programming language. i is the array index value, and v is the array element value corresponding to the index. ipairs is an iterator function provided by Lua to iterate over arrays

--打印数组a的所有值  
a = {"one", "two", "three"}
for i, v in ipairs(a) do
    print(i, v)
end

Instance loop array days

days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"} 
for i,v in ipairs(days) 
do 
    print(v) 
end

The output result of the above instance is:

>Sunday
>Monday
>Tuesday
>Wednesday
>Thursday
>Friday
>Saturday

6 Operators

6.1 Arithmetic Operators

The following table lists the commonly used arithmetic operators in the Lua language, with A set to 10 and B set to 20:

OperatorDescriptionInstance
+AdditionA + B Output result 30
-SubtractionA - B Output result -10
*MultiplicationA * B Output result 200
/DivisionB / A Output result 2
%ModulusB % A Output result 0
^ExponentiationA^2 Output result 100
-Negation-A output result -10
^abnormal orA~B result 30
&And withA&B result 0
IOrAIB result 30

We can gain a more thorough understanding of the application of arithmetic operators through the following examples:

a = 21
b = 10

c = a + b
print("Line 1 - c 的值为 "..c )

c = a - b
print("Line 2 - c 的值为 "..c )

c = a * b
print("Line 3 - c 的值为 "..c )

c = a / b
print("Line 4 - c 的值为 "..c )

c = a % b
print("Line 5 - c 的值为 "..c )

c = a^2
print("Line 6 - c 的值为 "..c )

c = -a
print("Line 7 - c 的值为 "..c )

c = a~b
print("Line 8 - c 的值为 "..c )

c = a&b
print("Line 9 - c 的值为 "..c )

c = a|b
print("Line 10 - c 的值为 "..c )

The execution result of the above program is:

>Line 1 - c 的值为     31
>Line 2 - c 的值为     11
>Line 3 - c 的值为     210
>Line 4 - c 的值为     2.1
>Line 5 - c 的值为     1
>Line 6 - c 的值为     441
>Line 7 - c 的值为     -21
>Line 6 - c 的值为     31
>Line 7 - c 的值为     0
>Line 7 - c 的值为     31

6.2 Relational operators

The following table lists the commonly used relational operators in Lua language, assuming the value of A is 10 and the value of B is 20:

OperatorDescriptionExample
==means equality, which checks whether two values are equal. If they are equal, it returns true; otherwise, it returns false.(A == B) is false.
~=means inequality, which checks whether two values are equal. If they are not equal, it returns true; otherwise, it returns false.(A ~= B) is true.
>> means greater than, which returns true if the left value is greater than the right value; otherwise, it returns false.(A > B) is false.
<< means less than, which returns false if the left value is greater than the right value; otherwise, it returns true.(A < B) is true.
>=means greater than or equal to, which returns true if the left value is greater than or equal to the right value; otherwise, it returns false(A >= B) returns false.
<=Less than or equal to. If the value on the left is less than or equal to the value on the right, return true; otherwise, return false.(A <= B) returns true.

Example: We can gain a more thorough understanding of the application of relational operators through the following example:

a = 21
b = 10

if( a == b )
then
   print("Line 1 - a 等于 b" )
else
   print("Line 1 - a 不等于 b" )
end

if( a ~= b )
then
   print("Line 2 - a 不等于 b" )
else
   print("Line 2 - a 等于 b" )
end

if ( a < b )
then
   print("Line 3 - a 小于 b" )
else
   print("Line 3 - a 大于等于 b" )
end

if ( a > b )
then
   print("Line 4 - a 大于 b" )
else
   print("Line 5 - a 小于等于 b" )
end

-- 修改 a 和 b 的值
a = 5
b = 20
if ( a <= b )
then
   print("Line 5 - a 小于等于  b" )
end

if ( b >= a )
then
   print("Line 6 - b 大于等于 a" )
end

The execution result of the above program is:

>Line 1 - a 不等于 b
>Line 2 - a 不等于 b
>Line 3 - a 大于等于 b
>Line 4 - a 大于 b
>Line 5 - a 小于等于  b
>Line 6 - b 大于等于 a

6.3 Logical Operators

The following table lists the commonly used logical operators in the Lua language, assuming the value of A is true and the value of B is false:

OperatorDescriptionExample
andLogical AND operator. If A is false, return A; otherwise, return B.(A and B) is false.
orLogical OR operator. If A is true, return A; otherwise, return B.(A or B) is true.
notLogical NOT operator. The result is opposite to the logical operation. If the condition is true, the logical NOT is false.not(A and B) is true.

Example: We can gain a more thorough understanding of the application of logical operators through the following example:

a = true
b = true

if ( a and b )
then
   print("a and b - 条件为 true" )
end

if ( a or b )
then
   print("a or b - 条件为 true" )
end

print("---------分割线---------" )

-- 修改 a 和 b 的值
a = false
b = true

if ( a and b )
then
   print("a and b - 条件为 true" )
else
   print("a and b - 条件为 false" )
end

if ( not( a and b) )
then
   print("not( a and b) - 条件为 true" )
else
   print("not( a and b) - 条件为 false" )
end

The execution result of the above program is:

>a and b - 条件为 true
>a or b - 条件为 true
>---------分割线---------
>a and b - 条件为 false
>not( a and b) - 条件为 true

6.4 Other Operators

The following table lists the concatenation operators and operators for calculating the length of tables or strings in the Lua language:

OperatorDescriptionExample
..Concatenate two stringsa..b, where a is "Hello" and b is "World", resulting in "Hello World".
#Unary operator that returns the length of a string or table.#"Hello" returns 5

Example: We can gain a more thorough understanding of the application of concatenation operators and operators that calculate the length of tables or strings through the following example:

a = "Hello "
b = "World"

print("连接字符串 a 和 b ", a..b )
print("b 字符串长度 ",#b )
print("字符串 Test 长度 ",#"Test" )
print("菜鸟教程网址长度 ",#"www.runoob.com" )

The execution result of the above program is:

>连接字符串 a 和 b     Hello World
>b 字符串长度     5
>字符串 Test 长度     4
>菜鸟教程网址长度     14

6.5 Operator precedence

From highest to lowest order:

^
not    - (unary)
*      /       %
+      -
..
<      >      <=     >=     ~=     ==
and
or

All binary operators except^and..are left-associative.

a+i < b/2+1          <-->       (a+i) < ((b/2)+1)
5+x^2*8              <-->       5+((x^2)*8)
a < y and y <= z     <-->       (a < y) and (y <= z)
-x^2                 <-->       -(x^2)
x^y^z                <-->       x^(y^z)

Example: We can gain a more thorough understanding of the precedence of Lua language operators through the following example:

a = 20
b = 10
c = 15
d = 5

e = (a + b) * c / d;*-- ( 30 * 15 ) / 5
print("(a + b) * c / d 运算值为  :",e )

e = ((a + b) * c) / d; *-- (30 * 15 ) / 5
print("((a + b) * c) / d 运算值为 :",e )

e = (a + b) * (c / d);*-- (30) * (15/5)
print("(a + b) * (c / d) 运算值为 :",e )

e = a + (b * c) / d; *-- 20 + (150/5)
print("a + (b * c) / d 运算值为  :",e )

The execution result of the above program is:

>(a + b) * c / d 运算值为  :    90.0
>((a + b) * c) / d 运算值为 :    90.0
>(a + b) * (c / d) 运算值为 :    90.0
>a + (b * c) / d 运算值为   :    50.0
Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

Leave a Reply

Your email address will not be published. Required fields are marked *.