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就能够有非常多写法,来个最easy想到的:
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不分析了。