当前位置:网站首页>lua--数据类型、变量、循环、函数、运算符的使用
lua--数据类型、变量、循环、函数、运算符的使用
2022-06-22 18:25:00 【aruba】
lua是一种轻量级脚本语言,由c语言编写,设计lua的初衷是为了:嵌入到应用程序中,提供灵活的扩展和定制化功能 lua官网:https://www.lua.org/ 可以从中下载安装lua
一、第一个lua程序
lua有两种编程方式:交互式和脚本式。脚本式就是编写脚本文件后执行,交互式是进入lua控制台进行编程,交互式在实际开发中并不会使用,下面都将使用脚本式进行编程
1. 创建脚本文件
lua脚本不对后缀名有要求,但一般我们都以lua为后缀,以示区分
vi hello.lua内容为:
print("hello world")2. 执行lua脚本
lua脚本的执行,使用lua命令
lua ./hello.lua 结果:
二、数据类型
在使用数据类型之前,先来了解下lua的注释
lua中单行注释使用:
-- 单行注释多行注释使用:
--[[
多行注释
]]--下面是lua数据类型的使用
1. number
number类型用来表示lua中的数字类型,包括整数和浮点数,精度为双精度
i = 1
print(i)
i = 9.99999
print(i)
print(type(i))运行结果:
2. nil
和Java中的null类似,nil表示一个无效值,也可以置空一个变量
i = 1
print(i)
i = nil
print(i)运行结果:
3. string
3.1 定义方式
字符串类型定义方式有三种:
定义方式 | 描述 |
|---|---|
单引号:'内容' | 表示单行字符串 |
双引号:"内容" | 和单引号相同 |
方括号:[[内容]] | 表示多行字符串 |
s = "abc"
print(s)
s = 'def'
print(s)
s = [[
gh,
多行内容,
123
]]
print(s)运行结果:
3.2 获取字符串长度
使用#获取字符串长度
print("-----")
s = 'abcedf'
print(#s)运行结果:
3.3 字符串使用+
lua在字符串使用+号时,优先将字符串转为数字
print("-----")
print('1' + 2)
print('1' + '2')运行结果:
3.4 字符串拼接
那么如何对字符串进行拼接呢?使用..连接字符串
print("-----")
print("1".."2".."abc")运行结果:
4. table
table既可以作为哈希表,又可以作为列表、数组。tab的表现形式更像map
定义table使用:{}
4.1 table作为数组使用
tb = {'a','b','c'}
-- 遍历输出
for k,v in pairs(tb) do
print(k..":"..v)
end运行结果:
可以看到,table如果不指定key,默认会从1开始将索引作为key
4.2 table作为map使用
tb = {k1 = '1',k2 = '2',k3 = '3'}
for k,v in pairs(tb) do
print(k..":"..v)
end运行结果:
4.3 获取table中的元素
两种方式:
获取方式 | 例子 |
|---|---|
通过table['key'],如果是数组不需要加引号 | tb["k1"] |
通过table.key,如果是数组则不支持 | tb.k1 |
测试:
tb = {k1 = '1',k2 = '2',k3 = '3'}
print(tb['k1'])
print(tb.k2)运行结果:
4.4 修改和增加table元素
使用获取table中元素的方式进行赋值就可以实现修改和增加table元素
tb = {k1 = '1',k2 = '2',k3 = '3'}
tb["k1"] = 4
tb['k4'] = 8
tb.k5 = 10
for k,v in pairs(tb) do
print(k..":"..v)
end运行结果:
4.5 删除table元素
将元素赋值为nil即可
tb.k2 = nil5. function
定义函数类型有两种方式:
- 定义函数,将函数方法名赋值给一个变量
- 匿名函数,直接将函数赋值给变量
5.1 定义函数方式
-- 定义一个函数
function sum(a,b)
return a + b
end
-- 将函数赋值给变量
f1 = sum
print(f1(1,6))运行结果:
5.2 匿名函数方式
function sumAndPrint(a,b,printFunc)
ret = a + b
-- 调用传入的函数
printFunc(ret)
return ret
end
-- 第三个参数是一个函数
sumAndPrint(10,20,
function(result)
print(result)
end
)运行结果:
三、变量
1. 作用域
lua中变量分为局部变量和全局变量,默认为全局变量,局部变量使用local关键字声明
function scope()
a = 0
local b = 1
end
scope()
print(a)
print(b)运行结果:
2. 多变量赋值
除了1:1(一个变量对应一个赋值)进行变量赋值外,lua还支持 n:n 、(m < n):n、n:(m < n) 变量赋值
方式 | 描述 |
|---|---|
n : n | 按先后顺序将值赋给变量 |
(m < n) : n | 按先后顺序将值赋给变量,多余的值丢弃 |
n : (m < n) | 按先后顺序将值赋给变量,值少的,赋值为nil |
a1,b1 = 1,2
print('a1:'..a1..',b1:'..b1)
a1,b1 = 5,3,4
print('a1:'..a1..',b1:'..b1)
a1,b1 = 9
print('a1:'..a1)
print(b1)运行结果:
四、循环
1. while
a = 0
while(a < 10) do
a = a + 1
print(a)
end运行结果:
2. for
for循环的语法稍微优点不同,第一个值表示初始值,第二个值表示条件结束的值,第三个值表示步长,步长可以省略不写,默认为1
for i = 0,10,2 do
print(i)
end运行结果:
3. repeat until
重复执行repeat后的代码,直到满足until条件
j = 0
repeat
j = j+1
print(j)
until(j > 4)运行结果:
五、条件与跳出循环
1. if
if判断来执行满足条件的某些代码
n = nil
if(n == nil) then
print('n是空')
end运行结果:
2. break
break用于强制跳出循环
k = 0
while(k < 10) do
k = k+1
if(k == 5) then
break;
end
print(k)
end运行结果:
六、函数
上面数据类型中我们了解到,函数也是可以被作为一个变量,定义函数使用function关键字,函数分为具名函数和匿名函数,具名函数可以通过函数名进行调用,匿名函数只能通过被赋值的函数型变量调用,除了上面的使用外,函数还有以下内容
1. 多值返回
lua中函数可以返回多个值
-- 将参数a,b,a+b作为返回值返回
function moreReturn(a,b)
return a,b,a+b
end
i,j,k = moreReturn(1,2)
print(i)
print(j)
print(k)运行结果:
2. 可变参数
使用...传递可变参数
-- 将所有参数相加
function sum(...)
local sum = 0
for k,v in pairs({...}) do
sum = sum + v
end
return sum
end
print(sum(1,2,3,4,5))运行结果:
2.1 含有固定参数
固定参数和可变参数都有的情况,固定参数写在前面
-- 格式化输出
function fmtPrint(fmt,...)
io.write(string.format(fmt,...))
end
fmtPrint("%d,%s,%d\n",12,'asd',66)运行结果:
2.2 select函数
lua中select函数可以对可变参数做一定的处理,如获取可变参数长度,截取可变参数
--求平均值
function avg(...)
local avg = 0
for k,v in pairs({...}) do
avg = avg + v
end
return avg / select("#",...)
--return avg / #{...}
end
print(avg(2,4,6,8))运行结果:
-- 截取可变参数
function limit(limit,...)
return select(limit,...)
end
a,b,c = limit(2,"a","b","c","d","e")
print(a)
print(b)
print(c)运行结果:
七、运算符
运算符都是比较常见的,一些我们之前就已经使用过
1. 算术运算符
符号 | 描述 |
|---|---|
+ | 加 |
- | 减 |
* | 乘 |
/ | 除 |
% | 取余 |
^ | 乘幂 |
- | 负号 |
2. 关系运算符
符号 | 描述 |
|---|---|
== | 等于 |
~= | 不等于 |
> | 大于 |
< | 小于 |
>= | 大于等于 |
<= | 小于等于 |
3. 逻辑运算符
符号 | 描述 |
|---|---|
and | 并且 |
or | 或者 |
not | 非 |
4. 其他运算符
符号 | 描述 |
|---|---|
.. | 字符串连接符 |
# | 长度计算符 |
边栏推荐
- 第一章 力扣热题100道(1-5)
- Online generation of placeholder pictures
- what? Homekit, Micah, aqara and other ecosystems can also be linked with tmall elf ecology through zhiting?
- K个一组翻转链表[链表拆解/翻转/拼装]
- 将一维数据(序列)转化为二维数据(图像)的方法汇总GAFS, MTF, Recurrence plot,STFT
- 1.3----- simple setting of 3D slicing software
- Programmer's tool encyclopedia [continuous update]
- MySQL多表操作
- Follow up course supplement of little turtle teacher "take you to learn C and take you to fly"
- Xintang nuc980 usage record: basic description of development environment preparation and compilation configuration
猜你喜欢

技术管理进阶——你了解成长的全貌吗?

Solution of off grid pin in Altium Designer
![K个一组翻转链表[链表拆解/翻转/拼装]](/img/70/fb783172fa65763f031e6bd945cbd9.png)
K个一组翻转链表[链表拆解/翻转/拼装]

Detailed explanation of shell script (x) -- how to use sed editor

Adapter mode of structural mode

实验4 NoSQL和关系数据库的操作比较

编译报错:/usr/bin/ld: /usr/local/lib/libgflags.a(gflags.cc.o): relocation R_X86_64_32S against `.rodata‘

shell脚本(五)——函数

Interface development component devaxpress asp Net core v21.2 - UI component enhancements

Damp 3D printer consumables
随机推荐
c# winform 嵌入flash
84.(cesium篇)cesium模型在地形上运动
The custom control autoscalemode causes the problem of increasing the width of font
MySQL多表操作
Array objects can be compared one by one (the original data with the same index and ID will be retained, and the data not in the original array will be added from the default list)
小波变换db4进行四层分解及其信号重构—matlab分析及C语言实现
Creator mode summary
shell脚本详解(四)——循环语句之while循环和until循环(附加例题及解析)
Thread pool: reading the source code of threadpoolexcutor
Shell编程规范与变量
0.1-----用AD画PCB的流程
Typescript (7) generic
误用append案例一则
Pat a 1093 count Pat's (25 points)
Digital business cloud: build a digital supply chain system to enable enterprises to optimize and upgrade their logistics supply chain
生产系统SQL执行计划突然变差怎么办?
Intelligent procurement system solution for processing and manufacturing industry: help enterprises realize integrated and Collaborative Procurement in the whole process
vs2008 水晶报表升级到 vs2013对应版本
Div horizontal layout
取zip包中的文件名