if语句要注意,在Lua里面0为true,其他为假
语法为:
if("条件")
then
"操作语句"
elseif(条件)
then
"操作语句"
else
"操作语句"
end
示例:
if(0)
then
print("0为true")
else
print("0为false")
end
if( 1== 2)--注意if语句和elseif语句都要配合then,else语句不需要配合then
then
print("1 == 2为true")
elseif(1 == 3)
then
print("1 == 3为true")
else
print("1既不等于2也不等于3")
end
(1)基本语法
while(condition)
do
statements
end
(2)示例演示
i=0
while(i < 10)
do
print("i值为:",i)
i = i+1--没有++语法或者+=语法
end
(1)基本语法
①数值for循环语法
var 从 exp1 变化到 exp2,每次变化以 exp3 为步长递增 var,并执行一次 “执行体”。exp3 是可选的,如果不指定,默认为1。
for var=exp1,exp2,exp3 do
<执行体>
end
②泛型for循环
泛型 for 循环通过一个迭代器函数来遍历所有值,类似foreach 语句。
i是数组索引值,v是对应索引的数组元素值。ipairs是Lua提供的一个迭代器函数,用来迭代数组。
a = {"one", "two", "three"}
for i, v in ipairs(a) do
print(i, v)
end
(2)示例演示
--数值for循环
--没有指定步长,步长默认为1
print("第一个数值for循环:")
for i=1,10
do
print(i)
end
--数值for循环
--步长指定为2
print("第二个数值for循环:")
for i=1,10,2
do
print(i)
end
--泛型for循环
print("第一个泛型for循环:")
table1={"abc","def","ghi","jkl","mno"}
for i,v in ipairs(table1)
do
print(i,v)
end
--泛型for循环
print("第二个泛型for循环:")
for i,v in ipairs(table1)
do
print(v)
end
--[[
--不允许指定索引的开始位置
for i=2,v in ipairs(table1)
do
print(i,v)
end
--]]
(1)基本语法
repeadt类似C语言的do…while循环
语法:
repeat
statements
until( condition )
(2)示例演示
i=1
repeat
print("i值为:",i)
i = i+1
until(i > 10)
运行结果:
4.break和goto
break和goto和C语言的作用一样,break跳出最内层循环,
goto跳转到其他语句,语法为:
:: Label ::
goto Label
这里作简单演示
--break演示
i=1
while(0)--0为true,死循环
do
print("i值为:",i)
i = i+1
if(i == 5)
then
break
end
end
--goto演示
::here::
print("这是here下的第一个语句")
print("这是here下的第二个语句")
while(0)
do
print("i值为:",i)
i = i+1
if(i == 10)
then
goto here
end
if(i == 11)
then
print("又一次进入第二个while循环")
break
end
end
print("这是带goto的while外的语句")