我用Lua做了一个(非常简单的)编程语言,但我只能执行一个命令



stackoverflow的大家好,我制作了一种(非常(简单的编程语言,它看起来有点像minecraft命令。这是代码

function wait(cmdSleepGetNum)-- you can name this function
--what ever you want, it doesnt matter
local start = os.time()
repeat until os.time() > start + cmdSleepGetNum
end

local input = io.read()

if input == "/help" then
print"you'll find it out"
else if input == "/say" then
print"what do you want to say?"
local cmdSay = io.read()
print(cmdSay)
else if input == "/stop" then
os.exit()
else if input == "/sleep" then
print"how long?"
local cmdSleepGetNum = io.read()
wait(cmdSleepGetNum)
else if input == "/rand" then
local randNum = math.random()
print(randNum)
end
end
end
end
end

现在我知道你在想什么了"这里有什么问题"问题是我只能执行一个命令,而在Lua解释器完成该命令后,我就不能执行任何其他命令了。

例如:

/兰特0.84018771715471(执行/rand命令并打印出一个随机数(/兰特stdin:1:"/"附近出现意外符号(当我尝试执行另一个命令时会发生这种情况(

  1. 如果用elseif替换else if,就不需要那么多end
  2. 你可以完全去掉if的,就是用一个表
  3. 正如@Egor Skcriptunoff所说,你需要创建一个主循环来运行许多命令
  4. 我建议您在/sleep/say中添加一个可选参数
local function wait (cmdSleepGetNum) -- you can name this function
-- whatever you want, it doesn't matter.
local start = os.time ()
repeat until os.time () > start + cmdSleepGetNum
end
local commands = {
help = function ()
print "you'll find it out"
end,
say = function (arg)
if arg == '' then
print 'what do you want to say?'
arg = io.read ()
end
print (arg)
end,
stop = function ()
os.exit ()
end,
sleep = function (arg)
if arg == '' then
print 'how long?'
arg = tonumber (io.read ())
end
wait (tonumber (arg))
end,
rand = function ()      
local randNum = math.random ()
print (randNum)
end,
[false] = function ()   -- fallback.
print 'Unknown command'
end
}
-- Main loop:
while true do
io.write '> '
local key, _, arg = io.read ():match '^%s*/(%S+)(%s*(.*))$' -- you can type /sleep 1, etc. in one line.
local command = key and key ~= '' and commands [key] or commands [false]
command (arg)
end

最新更新