if循环
--> if
a = 50
if a < 0 then
print('a的值小于0')
else
print('a的值大于0')
end
-->判断值
a = 0
if(a > 0) then
print('a的值大于0')
elseif a < 0 then
print('a的值小于0')
elseif a == 0 then
print('a的值等于0')
else
end
--> 练习1: 比较两个数的大小
a = 10
b = 20
if(a > b) then
print('a的值大于b,最大值是',a)
elseif a < b then
print('a的值小于b,最大值是',b)
elseif a == b then
print('a的值等于b')
else
end
while循环
--> 循环 while
a = 10
while(a > 0)
do
print('死循环')
end
--> 练习2:输出十句 hello lua
a = 0
while(a < 10)
do
print('hello lua')
a = a + 1
end
--> 练习3:输出1 - 100 的和
a = 1
sum = 0
while a <= 100
do
sum = sum + a
a = a + 1
end
print(sum)
--> 练习4:输出1-100之间所有的偶数和
a = 1
sum = 0
while a <= 100
do
if a % 2 == 0 then
sum = sum + a
end
a = a + 1
end
print(sum)
--> 练习5:输出1-100之间的偶数和并且不超过1500,并求出最后的那个偶数值是多少
a,sum,index = 1,0,0
while a <= 100
do
if a % 2 == 0 then
sum = sum + a
if sum > 1500 then
index = a
break
end
end
a = a + 1
end
print('最后的那个偶数是', index - 2)
print('1-100的偶数和不超过1500的是',sum - index)
--> repeat..until(直到满足才结束) do..while
a = 10
repeat
print("hello world",a)
a = a + 1
until a > 15
--> 练习:1-100之间所有的和不超过1500
sum,number = 0,1
repeat
sum = sum + number
number = number + 1
until sum > 1500
print('最后+的那个值为:',number)
print('1-100不超过1500的和为',sum - number)
for循环
--> for循环 1.数值for循环 2. 泛型for循环
--> for循环在lua中步长默认为1,可以自定义
for i=1,10 do
print(i)
end
function f(x)
return x^2
end
for i=1,f(5) do
print(i)
end
--> 练习1:1-100所有和
sum = 0
for i=1,100 do
sum = sum +i
end
--> 练习2:输出1-100所有的奇数
for i=1,100,2 do -- 这里步长设置为2,i取值就是1 3 5..
print(i)
end