I’m trying to make a script that makes an Npc talks with chosen answers (It’s supposed to be an AI to help lonely people feel better) it works when I set the answer. But when I say it twice it throws this error: Workspace.Dummy.Script:11: bad argument #2 (string expected, got nil) this is my script:
game.Players.PlayerAdded:Connect(function(player)
player.Chatted:Connect(function(message)
local answerTime = 0;
local answer1,answerTime2 = message:match("addAnswer%[(.-)%:.-%]()",answerTime)
answerTime = answerTime + 1
local savedAnswer1 = answer1
local otherAnswerTime = 0;
local answer2,otherAnswerTime2 = message:match("addAnswer%[.-%:(.-)%]()",otherAnswerTime)
otherAnswerTime = otherAnswerTime + 1
local savedAnswer2 = answer2
if message:find(savedAnswer1) then
game:GetService("Chat"):Chat(script.Parent.Head,savedAnswer2,Enum.ChatColor.White)
end
end)
end)
game.Players.PlayerAdded:Connect(function(player)
player.Chatted:Connect(function(message)
local answerTime = 0;
local answer1,answerTime2 = message:match(“addAnswer%(.-)%:.-%”,answerTime)
answerTime = answerTime + 1
local savedAnswer1 = answer1
local otherAnswerTime = 0;
local answer2,otherAnswerTime2 = message:match(“addAnswer%.-%:(.-)%”,otherAnswerTime)
otherAnswerTime = otherAnswerTime + 1
local savedAnswer2 = answer2
if string.find(message,6savedAnswer1) then
game:GetService(“Chat”):Chat(script.Parent.Head,savedAnswer2,Enum.ChatColor.White)
end
end)
end)
Check to make sure ur getting a returned value for the string.match functions you’re making, if it can’t find a matched pattern in the searched string it’ll return nil (which will error when you use the string.find() function on message).
Overall I’m a bit confused about what this script is actually trying to accomplish. But that seems to be the likely cause of the error you’re getting.
Idk I think using :match works better in the case you’re using. :sub doesn’t take in a string pattern, it just takes in beginning and end indexes to return a substring. :match both accounts for offset/ variable-length messages and will return nil if the expression ur looking for isn’t there.
I’m just confused about why ur using :find, savedAnswer1 is the returned value of the string capture in ur match statement. This’ll return some specific portion of the message, unless the match doesn’t fit then it returns nil. So you should just check if savedAnswer1 is nil or not.
Maybe something like this?
game.Players.PlayerAdded:Connect(function(player)
player.Chatted:Connect(function(message)
local ans1, ans2, ansTime = message:match("addAnswer%[(.-):(.-)%]()")
ansTime=ansTime+1
if ans1 then
game:GetService("Chat"):Chat(script.Parent.Head,ans2,Enum.ChatColor.White)
else
print('No answer 1')
game:GetService("Chat"):Chat(script.Parent.Head,"?",Enum.ChatColor.White)
end
end)
end)
-- Should match to messages like 'addAnswer[pizza:is best]', 'addAnswer[pancakes:bacon pancakes]'