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

大家好,我制作了一个(非常)简单的编程语言,它有点像 Minecraft 的命令。以下是代码

function wait(cmdSleepGetNum)-- 你可以给这个函数命名
--随便什么都可以,没有关系
  local start = os.time()
  repeat until os.time() > start + cmdSleepGetNum
end

local input = io.read()

if input == "/help" then
print"你会发现它的用处的"

else if input == "/say" then
print"你想说什么?"
local cmdSay = io.read()
print(cmdSay)

else if input == "/stop" then
os.exit()

else if input == "/sleep" then
print"多久?"
local cmdSleepGetNum = io.read()
wait(cmdSleepGetNum)

else if input == "/rand" then
local randNum = math.random()
print(randNum)
end
end
end
end
end

现在我知道你在想什么 "这里的问题是什么?" 问题是我只能执行一个命令,当 Lua 解释器完成该命令后,我无法执行任何其他命令。

例如:

/rand 0.84018771715471(执行 /rand 命令并打印出一个随机数) /rand stdin:1:'/'附近有意外符号(尝试执行另一个命令时发生)

点赞
用户6632736
用户6632736

1.如果你用elseif代替else if,就不用那么多的end了,

2.如果你使用一个表格,你可以完全摆脱if

3.正如@Egor Skriptunoff所说,你需要创建一个主循环来运行许多命令,

4.我建议你给/sleep/say添加一个可选参数。

local function wait (cmdSleepGetNum) --你可以随意命名这个函数。 
  local start = os.time () 
  repeat until os.time () > start + cmdSleepGetNum 
end 

local commands = { 
    help = function () 
        print "你会发现的" 
    end, 
    say = function (arg) 
        if arg == '' then 
            print '你想说什么?' 
            arg = io.read () 
        end 
        print (arg) 
    end, 
    stop = function () 
        os.exit () 
    end, 
    sleep = function (arg) 
        if arg == '' then 
            print '多久?' 
            arg = tonumber (io.read ()) 
        end 
        wait (tonumber (arg)) 
    end, 
    rand = function () 
        local randNum = math.random () 
        print (randNum) 
    end, 
    [false] = function ()   --备用。 
        print '未知的命令' 
    end 
} 

-- 主循环: 
while true do 
    io.write '> ' 
    local key, _, arg = io.read ():match '^%s*/(%S+)(%s*(.*))$' -- 你可以在一行中输入/ sleep 1等。 
    local command = key and key ~= '' and commands [key] or commands [false] 
    command (arg) 
end
2020-11-09 03:59:05