如何使我的Lua不和机器人发送一个日语短语,以及如何检查是否预期的部分是空/空白?



我目前正在制作一个自定义的Discord bot,用Lua编写,作为纯粹出于怨恨的挑战。我最近开始学习Lua,所以这对我来说是一个有趣的挑战!但是,我还是发现了一个让我很困惑的障碍。^ ^">

为了方便起见,我就把困扰我的部分…

Client:on("messageCreate", function(Message)
--Command checker
local Content = Message.content:lower()
local CommandYes = Message.content:sub(1,2) == Settings.Prefix --[m/ ; This is already defined, no problem here]
if not CommandYes then
return
end
Content = Content:sub(3) --The command part after prefix
if Content == "hello" then --m/hello iterations
if Content:sub(7,2):lower() == "jp" then
Message:reply(string.format("こんにちは, %s-様!", Message.author.mentionString)) --Somehow the expected message doesn't send, what
elseif Content:sub(7,2):lower() == "en" or Content:sub(7,2):lower() == --[[checkblankhow]] then
Message:reply(string.format("Hello my master, %s-sama!", Message.author.mentionString))
else
Message:reply(string.format("I'm sorry, I don't know that language...nBut hello my master, %s-sama!", Message.author.mentionString))
end
end
end)

在这里,我试着做一个简单的检查,看看命令是否指定了"jp"与否。我计划仅将其设置为EN、JP或不设置(如果选中的部分不是EN/JP,并且它是空白的),正如您在上面的代码中看到的那样,但是它不起作用。:")

我试着这样写代码:

...
Content = Content:sub(3) --The command part after prefix
if Content == "hello" then --m/hello iterations
Message:reply(string.format("Konnichiwa, %s-sama!", Message.author.mentionString))
if Content:sub(7,2):lower() == "jp" then
Message:reply(string.format("こんにちは, %s-様!", Message.author.mentionString))
end
end
...

但是,只有常规的m/hello命令有效,而m/hello jp命令不起作用,就像它被bot忽略了一样。如果有人能帮我,我会很感激的,所以……

提前感谢!^ ^

Content:sub(7,2)错误:string.sub需要启动&结束索引(包括两个),而不是开始索引和长度。要获得长度为2的子字符串,必须使用8作为第二个参数:Content:sub(7,8)。您可以测试基本的"命令解析"。在REPL:("m/hello jp"):sub(3):sub(7, 8)中,生成jp

请注意,手动确定索引非常容易出错,而且非常不可读。我建议使用字符串匹配通过获取字符串长度来计算索引。例如:

local command = Message.content:match"m/(.+)"
if not command then return end
if command == "hello" then ... end
local command_name, param = command:match"(.-) (.+)"
if command_name == "hello" then
if param == "en" then ...
elseif param == "jp" then ...
else ... end
end

最新更新