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

How do I do user inputs on the same line in 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 后按回车键。我总是不得不这样写:

print
text

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

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

command = op.read()

然后分析字符串。 对于您想要做的事情,最好的方法可能是迭代字符串以寻找空格来分隔每个单词并将其保存到 table 中。然后你几乎可以随心所欲地使用它。 您还可以在迭代时即时解释命令:

Read in the first word;
if it is "print" then read in the rest of the line and print it;
if it is "foo" read in the next 3 words as aprameters and call bar();

等等

现在我将实施留给您。如果您需要帮助,请发表评论。

当不带参数调用时,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