lua 语句学习

就如同C里的if else,while,do,repeat;就看lua里怎么用:

1、首先看if else

t = {1,2,3}

local i = 1

if t[i] and t[i] % 2 == 0 then
	print("even")
else
	print("odd")
end

lua木有C里的&&,而是and来表示;if 之后跟表达式,之后要更个then 最后语句结束都要写end 表示这个chunk结束了。

2、while

while t[i] do
	print(t[i])
	i = i + 1
end

3、do end

do
	print(t[i])
	i = i + 1
end

4、repeat until

local i = 1
repeat
	print(t[i])
	i = i + 1
until t[i] == nil

5、for的用法

for i = 1, #t do
	print(t[i])
end

当然for循环里还可以直接调用lua API

for k,v in pairs(t) do
	print(k , v)
end

6、break用法

for k,v in pairs(t) do
	print(k , v)
	if k == 2 then
	break
	end
end

课后题解答:

1、lua为毛支持elseif这种写法

比如可以这么写:

for k,v in pairs(t) do
	if k == 2 then
		print('111')
	elseif k == 1 then
		print(k , v)
	end
end

这样整个if ...end是一个chunk;如果if else分开写,就得这样:

t = {1,2,3}


for k,v in pairs(t) do
	if k == 2 then
		print('111')
	else if k == 1 then
		print(k , v)
		end
	end
end

多出了一个end。

因为lua里没有switch,如果选择分支比较多写那么多end很丑陋,so就可以elseif一起用啦。

2、写无条件执行代码,如果c里我喜欢用do{}while(false);lua就可以有很多写法,来个最容易想到的:

local i = 0
repeat
	i = i + 1
	print(i)
	if i > 10 then
		break
	end
until false

3、第三个问题,我已经用第二个解答回答了,在lua里是要用到repeat until来做的。

4、修改恶心的goto语句,的确看着很不爽,改了就清爽多了:

function room1()
repeat
	local move = io.read()
	if move == "south" then
	return room3()
	elseif move == "east" then
	return room2()
	else
	print("invalid move")
	end
until false
end

function room2()
repeat
	local move = io.read()
	if move == "south" then
	return room4()
	elseif move == "west" then
	return room1()
	else
	print("invalid move")
	end
until false
end

function room3()
repeat
	local move = io.read()
	if move == "north" then
	return room1()
	elseif move == "east" then
	return room4()
	else
	print("invalid move")
	end
until false
end

function room4()
	print("Congratulations, u win!")
end

room1()

5、goto的限制

goto不能调到某个语句块内,因为内部是不能为外部所知道的;为毛不能跳出函数块,书里的解释是:

stackflow的答案是:

Your guesses are hinting at the answer. The reason is because the goto statement and its destination must reside in the same stack frame. The program context before and after the goto need to be the same otherwise the code being jumped to won't be running in its correct stack frame and its behavior will be undefined. goto in C has the same restrictions for the same reasons.

6、这道题看到goto就好凌乱,我压根就打算用goto,也驾驭不了介个,so不分析了。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值