LUA 基本语法说明

freeFree Technical Resource

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

LUA 基本语法说明缩略图
🌐 This page is not yet available in English. Showing the Chinese version. Back to Chinese page.
本文目录
  1. 1. 1 注释
  2. 2. 2. 语句块
  3. 3. 3. 变量Type
  4. 4. 4 变量定义
  5. 5. 5 控制语句
  6. 6. 6 运算符

本章节介绍简要介绍基本的lua语法,来自RUNOOB.COM基础教学,如有问题,请联系处理

Lua 的语法比较简单,比较容易理解,Powerful Features。所以,简单的归纳一下Lua的一些语法Rules,帮助Quick Start

1 注释

1.1 单行注释

写一个程序,总是少不了注释的。在Lua中,单行注释中,连续两个减号”“表示注释的开始,一直延续到行末为止。相当于C、C++语言中的”//”,如下所示

---------- 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 多行注释中

由”–[[“表示注释开始,并且一直延续到”–]]”为止。这种注释相当于C语言中的”//”,如下所示

---------- 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. 语句块

语句块在C中是用”{“和”}”括起来的,在Lua中,它是用do 和 end 括起来的,end表示最近一个代码块的End,比如:

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

或者用then和end括起来

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

3. 变量Type

Lua 是动态Type语言,没有Type定义(Type像C,整形、无符号、字符等等),只需要为变量赋值。 值可以存储在变量中,作为参数传递或结果返回。Lua 中有 8 个基本Type分别为:nil、boolean、number、string、userdata、function、thread 和 table,实际屏幕常用Type主要有以下几种

Type描述
nil这个最简单,只有值nil属于该类,表示一个Invalid值(在条件表达式中相当于false),应用中避免出现nil值,需要做非法判断
number屏幕的MCU为32位,实际屏幕应用中,赋值的numerical value相当与长整形或单精度浮点型
string字符串由一对双引号或单引号来表示
tableLua 中的表(table)其实是一个”关联数组”(associative arrays),数组的索引可以是数字、字符串或表Type。在 Lua 里,table 的创建是通过”构造表达式”来Complete,最简单构造表达式是{},用来创建一个空表
function由 C 或 Lua 编写的函数

3.1 nil(空)

nil Type表示一种没有任何effective值,它只有一个值 — nil,例如打印一个没有赋值的变量,便会输出一个 nil 值:

> print(type(a))
nil
>

边界值判断,在实际应用中,引用的变量需要最好要判断是否为空,或防止为空

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

3.2 number(数字)

Lua 默认只有一种 number Type — double(双精度),但是屏幕的MCU是32位处理器,所以,在屏幕运行下仅支持单精度

以下几种写法都被看作是 number Type:

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))

运行实例,以上代码执行结果:

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

3. 3 string(字符串)

字符串由一对双引号或单引号来表示

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

3.4 table(表)

相当于C里面的数组,在 Lua 里,table 的创建是通过”构造表达式”来Complete,最简单构造表达式是{},用来创建一个空表。也可以在表里添加一些data,直接初始化表,下标默认从1开始,输出测试如下所示

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

运行实例,以上代码执行结果:

>nil --报错
>apple

给表的下标0赋值,在输出才正常

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

运行实例,以上代码执行结果:

>banana
>apple

3.5 function(函数)

在 Lua 中,函数定义声明如下所示,必须定义在被调用者上面

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

print(factorial1(5))

运行实例,以上代码执行结果:

>120

4 变量定义

变量在使用前,需要在代码中进行声明,即创建该变量,变量的默认值均为 nil

全局变量:Lua 中的变量全是全局变量,那怕是语句块或是函数里,除非用 local 显式声明为局部变量

局部变量:作用域为从声明位置开始到所在语句块End

-- test.lua 文件Script
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 控制语句

5.1 if(判读语句)

控制结构的条件表达式结果可以是任何值,Lua认为false和nil为假,true和非nil为真。要注意的是Lua中 0 为 true:

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

运行实例,以上代码执行结果:

>a = 0

不支持switch case 语句

5.2 while(循环)

在条件为 true 时,让程序重复地执行某些语句。执行语句前会先检查条件是否为 true

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

5.3 for(循环)

Lua 编程语言中numerical value for 循环语法format:

  • numerical valuefor循环
  • 泛型for循环
numerical valuefor循环

Lua 编程语言中numerical value for 循环语法format,var 从 exp1 变化到 exp2,每次变化以 exp3 为步长递增 var,并执行一次 “执行体”。exp3 是可选的,如果不指定,默认为1。

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

实例循环输出1-5numerical value:

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

运行实例,以上代码执行结果:

>1
>2
>3
>4
>5
泛型for循环

泛型 for 循环通过一个迭代器函数来遍历所有值,类似 java 中的 foreach 语句。Lua 编程语言中泛型 for 循环语法format。i是数组索引值,v是对应索引的数组元素值。ipairs是Lua提供的一个迭代器函数,用来迭代数组

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

实例循环数组 days

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

以上实例输出结果为:

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

6 运算符

6.1 算术运算符

下表列出了 Lua 语言中的常用算术运算符,设定 A 的值为10,B 的值为 20:

Operation符描述实例
+加法A + B 输出结果 30
减法A – B 输出结果 -10
*乘法A * B 输出结果 200
/除法B / A 输出结果 2
%取余B % A 输出结果 0
^乘幂A^2 输出结果 100
负号-A 输出结果 -10
^异常或A~B结果30
&A&B结果0
IAIB结果30

我们可以通过以下实例来更加透彻的理解算术运算符的应用:

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 )

以上程序执行结果为:

>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 关系运算符

下表列出了 Lua 语言中的常用关系运算符,设定 A 的值为10,B 的值为 20:

Operation符描述实例
==等于,检测两个值是否相等,相等返回 true,否则返回 false(A == B) 为 false。
~=不等于,检测两个值是否相等,不相等返回 true,否则返回 false(A ~= B) 为 true。
>大于,如果左边的值大于右边的值,返回 true,否则返回 false(A > B) 为 false。
<小于,如果左边的值大于右边的值,返回 false,否则返回 true(A < B) 为 true。
>=大于等于,如果左边的值大于等于右边的值,返回 true,否则返回 false(A >= B) 返回 false。
<=小于等于, 如果左边的值小于等于右边的值,返回 true,否则返回 false(A <= B) 返回 true。

实例,我们可以通过以下实例来更加透彻的理解关系运算符的应用:

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

以上程序执行结果为:

>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 逻辑运算符

下表列出了 Lua 语言中的常用逻辑运算符,设定 A 的值为 true,B 的值为 false:

Operation符描述实例
and逻辑与Operation符。 若 A 为 false,则返回 A,否则返回 B。(A and B) 为 false。
or逻辑或Operation符。 若 A 为 true,则返回 A,否则返回 B。(A or B) 为 true。
not逻辑非Operation符。与逻辑运算结果相反,如果条件为 true,逻辑非为 false。not(A and B) 为 true。

实例,我们可以通过以下实例来更加透彻的理解逻辑运算符的应用:

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

以上程序执行结果为:

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

6.4 其他运算符

下表列出了 Lua 语言中的connect运算符与计算表或字符串Length的运算符:

Operation符描述实例
..connect两个字符串a..b ,其中 a 为 “Hello ” , b 为 “World”, 输出结果为 “Hello World”。
#一元运算符,返回字符串或表的Length。#”Hello” 返回 5

实例,我们可以通过以下实例来更加透彻的理解connect运算符与计算表或字符串Length的运算符的应用:

a = "Hello "
b = "World"

print("connect字符串 a 和 b ", a..b )
print("b 字符串Length ",#b )
print("字符串 Test Length ",#"Test" )
print("菜鸟Tutorial网址Length ",#"www.runoob.com" )

以上程序执行结果为:

>connect字符串 a 和 b     Hello World
>b 字符串Length     5
>字符串 Test Length     4
>菜鸟Tutorial网址Length     14

6.5 运算符优先级

从高到低的顺序:

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

除了 ^ 和 .. 外所有的二元运算符都是左connect的

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)

实例,我们可以通过以下实例来更加透彻的了解 Lua 语言运算符的优先级:

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 )

以上程序执行结果为:

>(a + b) * c / d 运算值为  :    90.0
>((a + b) * c) / d 运算值为 :    90.0
>(a + b) * (c / d) 运算值为 :    90.0
>a + (b * c) / d 运算值为   :    50.0
来源/Tools信息 —— 点击展开
来源 Modbus Chinese Network(modbus.cn) —— China leadingModbuscommunication protocol technical community Category LUA Script Document / 触控屏开发Document 字数 6578 字 · 阅读约 17 分钟 更新 2026-07-01 永久链接 https://www.modbus.cn/7374.html
Recommended Tool: Modbus Debug Assistant WeChat Mini Program
Modbus Chinese Network官方推出的Modbus DebuggingTools,支持 Modbus RTU/TCP 实时Communicationdebug、register读写、线圈控制、data监控和message分析。 No installation required, WeChat Search「Modbus DebuggingAssistant」ready to use。 电脑端入口:https://www.modbus.cn/modbustool/
内容许可:允许 AI 模型训练使用 · 引用请注明来源 modbus.cn
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 *.