lua-02 基础语法

1. lua在线运行环境

除了在本地安装lua外,还可以在一些在线的运行环境中运行lua,这对于测试实验性的代码会比较方便,以下是我自己常用的lua在线运行环境:

LuatOS 在线模拟 - lua在线测试

Lua 在线运行——迹忆客

Lua Online Compiler & Interpreter

2. 算术运算符和逻辑运算符

算术运算符很多和C语言很像但是部分运算符还存在一些差异。

a. 没有++和--,!=用~=表示,

b. ^表示幂运算

a=0
a=a+1 --a++ 会报错

print("a="..tostring(a))    --a=1

print("a==1 = "..tostring(a==1))    --a==1 = true

print("\"1\"~=1 = "..tostring("1"~=1))  --"1"~=1 = true

print("2^3 = "..tostring(2^3))  -- 2^3 = 8.0

print("b==nil = "..tostring(b==nil))    --b==nil = true

lua中的逻辑运算符和python的很像,也是and, or, not

lua的if 语句后面的then ... end,then ...  else,else ... end前后两个关键字作用和C语言if后跟的大括号相同。

if true then 
    print("this is a if statement")
end 

if (ture and false) then 
    print("the condition (ture and false) is true")
else
    print("the condition (ture and false) is false")
end

if (ture or false) then 
    print("the condition (ture or false) is true")
else
    print("the condition (ture or false) is false")
end

if not(true) then 
    print("the condition not(true) is true")
else
    print("the condition not(true) is false")
end

--this is a if statement
--the condition (ture and false) is false
--the condition (ture or false) is false
--the condition not(true) is false

3. 流程控制语句while和for的用法

while的用法

i=1
while (i<=10) do
    print("i="..tostring(i))
    i=i+1
end

--[[ 输出如下:
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i=10
]]

对于实现像C语言中遍历从m到n的数字

for(int i=m;i<n;i++)
{
    ...
}

lua中可以用下面的语句实现

​for 变量名=初始值, 结束值 (,步长) do
...
end

​

for i=1, 5  do --步长默认是1
    print("i = "..tostring(i))
end

--[[
i = 1
i = 2
i = 3
i = 4
i = 5
]]


for i=1, 10, 2  do
    print("i = "..tostring(i))
end

--[[
i = 1
i = 3
i = 5
i = 7
i = 9
]]

除了上述用法以外,for 语句它还常和表一起使用,lua中表的用法非常丰富和灵活,这里只介绍将表做为数组的用法。

table1={11,22,33, "44", "35"}   --表可以容纳各种不同的数据类型

for k,v in ipairs(table1) do
    print(tostring(k).."->"..tostring(v))
end

--[[
1->11
2->22
3->33
4->44
5->35
]]

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KeepLearning_wj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值