这是我的代码:
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
后按Enter键。我总是最不得不这样写:
print
text
如果有人知道如何解决这个问题,请回答。
答案 0 :(得分:3)
当没有参数调用时,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
答案 1 :(得分:1)
嗯,那是因为io.read()实际读取整行。 你要做的就是读一行:
"dom": '<"top">t<"bottom">p<"clear">',
然后分析字符串。 对于你想要做的事情,最好的方法是迭代字符串寻找空格来分隔每个单词并将其保存到表中。然后你可以随心所欲地做任何事情。 您还可以在迭代时动态解释命令:
command = op.read()
等
现在我要把实施留给你了。如果您需要帮助,请发表评论。