如何在Lua中在同一行上进行用户输入?

这是我的代码:

while true do
    opr = io.read() txt = io.read()
    if opr == "print" then
        print(txt)
    else
        print("wat")
    end
end

我想做的是让你输入 print,然后输入任何内容,如下所示:

print text

然后它会打印出text,但是似乎我不能在同一行上做到这一点,而不必在输入 print 后按回车键。我总是不得不这样写:

print
text

如果有人知道我如何解决这个问题,请回答。

点赞
用户4984564
用户4984564

那是因为 io.read() 实际上是读取整行。 你需要做的是读取一行:

command = op.read()

然后分析字符串。 对于你想要做的事情,最好的方法可能是遍历字符串,寻找空格以将每个单词分开并将其保存到表中。然后你几乎可以随心所欲地处理它。 在迭代时你也可以解释命令:

读取第一个单词;
如果是“print”,则读取剩余的行并打印它;
如果是“foo”则读取接下来的3个单词作为参数并调用 bar();

等等。

现在我将实现留给您。如果您需要帮助,请留言。

2015-06-08 01:48:04
用户1009479
用户1009479

当没有给io.read()传参时,它会读取一整行。你可以通过模式匹配来读取该行并且获取到它的单词:

input = io.read()
opr, txt = input:match("(%S+)%s+(%S+)")

以上代码假设opr只有一个单词,而txt也只有一个单词。如果可能会有零个或多个txt,则可以尝试使用以下代码:

while true do
    local input = io.read()
    local i, j = input:find("%S+")
    local opr = input:sub(i, j)
    local others = input:sub(j + 1)
    local t = {}
    for s in others:gmatch("%S+") do
        table.insert(t, s)
    end
    if opr == "print" then
        print(table.unpack(t))
    else
        print("wat")
    end
end
2015-06-08 02:40:07