Lua丨循环方式:while、for、repeat until

版权声明:欢迎转载,转载请注明出处 https://blog.csdn.net/weixin_38239050/article/details/82458830

Lua循环的三种方式:

1、while

2、for

3、repeat until

while

--[[

	while condition do
		statements
	end

--]]

--输出1-20之间的奇数
a=1
while a<=20 do
	if a%2==1 then
		print(a)
	end
	a=a+1  --Lua中没有自增a++
end



>lua -e "io.stdout:setvbuf 'no'" "table.lua" 
1
3
5
7
9
11
13
15
17
19
>Exit code: 0

for

--[[
for循环

1、数值for循环
这里的var会从start变化到end,每次变化step,step默认为1
for var=start,end,step do
	循环体
end
--]]
for i=1,3 do
	print(i)
end


--[[
2、泛型for循环
--]]
mytab={key1=10,key2="key2"}
for k,v in pairs(mytab) do
	print(k,v)
end



>lua -e "io.stdout:setvbuf 'no'" "table.lua" 
1
2
3
key1	10
key2	key2
>Exit code: 0

repeat until

--[[
repeat until     类似(do while),但?do while)是当...时,执行...
				repeat until是执行...,直到...时就不执行了

repeat
	循环体
until(condition)
--]]
a=1
repeat
	print(a)
	a=a+1
until(a>3)



>lua -e "io.stdout:setvbuf 'no'" "table.lua" 
1
2
3
>Exit code: 0

猜你喜欢

转载自blog.csdn.net/weixin_38239050/article/details/82458830