Lua - 如何从用户获取命令行输入?

18

在我的lua程序中,我想在执行操作之前停止并询问用户确认。我不确定如何停止并等待用户输入,应该如何实现?

6个回答

33
local answer
repeat
   io.write("continue with this operation (y/n)? ")
   io.flush()
   answer=io.read()
until answer=="y" or answer=="n"

当使用默认的stdin/out时,io.read()是否会强制执行自动的io.flush() - Egor Skriptunoff
@EgorSkriptunoff,这有可能,但我们不能确定。我认为 ANSI C 没有关于这个的说明。 - lhf

15

10

我曾经处理过类似的代码。我会以一种可行的方式打出:

io.write("continue with this operation (y/n)?")
answer=io.read()
if answer=="y" then
   --(put what you want it to do if you say y here)
elseif answer=="n" then
   --(put what you want to happen if you say n)
end

1
我使用:

     print("Continue (y/n)?")
re = io.read()
if re == "y" or "Y" then
    (Insert stuff here)
elseif re == "n" or "N" then
    print("Ok...")
end

条件语句有误,例如 re == "y" or "Y" 应该改为 re == "y" or re == "Y"。我们也可以检查 re:lower() == "y"。请注意这一点可能很重要。 - PaulR

1

尝试使用以下代码

m=io.read() if m=="yes" then (在此处插入函数) end


-1
print("Continue (y/n)?")
re = io.read()
if re == "y" or "Y" then
    (Insert stuff here)
elseif re == "n" or "N" then
    print("Ok...")
end

从我所做的一点点Lua(不多),如果你使用string.sub,同时使用大写和小写字母是多余的。
print("Continue? (y/n)")
local re = io.read()

--[[Can you get string.sub from a local var? 
If so, this works. I'm unfamiliar with io(game 
lua uses GUI elements and keypresses in place of the CLI.]]

if re.sub == "y" then
    --do stuff
if re.sub == "n" then
    --do other stuff
end

那应该可以运行。


1
re.sub will resolve to the function string.sub & always be unequal to "y" or "n". Besides, string matching is case sensitive. At best you can do re:match("[nN]") and re:match("[yY]") - Demur Rumed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接