Lua中的if else和while语句有什么限制?
2015-12-12 22:55:44
收藏:0
阅读:65
评论:2
我正在尝试为游戏中基于Lua的计算机制作程序。然而,当它运行时表现很奇怪。
--Tablet
oldpullEvent = os.pullEvent
os.pullEvent = os.pullEventRaw
while true do
term.clear()
term.setTextColor( colors.white )
term.setCursorPos(1, 1)
print("Please Enter Password:")
input = read("*")
incorrect = 0
while incorrect < 3 do
if input == "qwerty" then
print("Password Correct, Unlocking")
else
if incorrect < 3 then
incorrect = incorrect + 1
print("Password incorrect")
print(3 - incorrect, " tries remaining")
else
print(3 - incorrect, "tries remaining, locking phone for 1m")
local num = 0
while num < 60 do
if num < 60 then
term.clear()
term.setTextColor( colors.red )
term.setCursorPos(1, 1)
num = num + 1
print(60 - num, "s remaining")
sleep(1)
else
incorrect = 0
end
end
end
end
end
end
os.pullEvent = oldpullEvent
当它运行时,它开始显示“Please enter password:”,输入正确密码“qwerty”后,它会无限循环地重复显示“Password Correct, Unlocking”。当我输入错误密码时,它不运行else语句中的代码,而只是返回输入密码的屏幕。没有错误代码或崩溃。是否有了解Lua的人知道我是否在while / if / elseif函数中写错了,或是否有解决方法。
谢谢!
点赞
用户4021682
当输入正确密码时,该循环没有被告知停止。在输入正确密码后,应该在print("Password Correct, Unlocking")之后添加break。
这是因为input在循环外部,更好的方法是像下面这样:
local incorrect = 0
while true do
term.clear()
term.setTextColor( colors.white )
term.setCursorPos(1, 1)
print("Please Enter Password:")
local input = read("*")
if input == "qwerty" then
print("Password Correct, Unlocking")
break
else
if incorrect < 2 then
incorrect = incorrect + 1
print("Password incorrect")
print(3 - incorrect, " tries remaining")
sleep(1) -- let them read the print.
else
print("out of attempts, locking phone for 1m")
for i = 10, 1, -1 do
term.clear()
term.setTextColor( colors.red )
term.setCursorPos(1, 1)
print(i, "s remaining")
sleep(1)
end
incorrect = 0
end
end
end
上面的代码将允许用户尝试3次密码,如果都用完了,他们将被锁定60秒并获得另外3次尝试机会。直到输入正确密码为止,这个过程会不断重复。
我已经删除了内部的while循环,因为它不是必需的。 incorrect已被设为local并移到while循环外部,因此每次用户输入密码时不会被重置。
read("*")已移动到while循环内部,以便每次提示用户输入密码,而不是询问一次然后无限循环。
该代码已经经过测试,似乎没有任何问题。
如果有任何代码不清楚的地方,请随时问我。
2016-01-10 06:44:21
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
你输入正确密码后没有将
incorrect值重置。你需要使用break来中止循环或将incorrect设置为 3 或更大的值。