I didn't know how to explain this one in the title. Anyway so I was messing around with return and I got an idea that involved math so I tried creating a script that printed out a sum of a math equation that the LocalPlayer says (Example: '1 + 1' -> '2') but I don't know how to make it detect the numbers of 1 to 100. Any help?
Edit: I was trying to use math.random but it doesn't seem to work because it picks 2 random numbers and not any value of 1 & 100 for what i'm trying to do.
function add(num1,num2) return num1 + num2 end n1 = math.random(1,100) n2 = math.random(1,100) game.Players.LocalPlayer.Chatted:connect(function(msg) if msg:lower() == n1..' + '..n2 then local a = add(n1,n2) print(msg.." = "..a) end end)
I made example script which would help You. Solution was using match and pattern. Thats how I would do this.
function Sum(n1, n2) return n1 + n2 end function Subtract(n1, n2) return n1 - n2 end game.Players.LocalPlayer.Chatted:connect(function(msg) -- GETTING ARGS local args = nil if string.match(msg, "%d+%s*%p%s*%d+") ~= nil then args = {string.match(msg, "(%d+)%s*(%p)%s*(%d+)")} end if args ~= nil then -- CHECKING ARGS if args[2] == "+" then print(Sum(tonumber(args[1]), tonumber(args[3]))) elseif args[2] == "-" then print(Subtract(tonumber(args[1]), tonumber(args[3]))) end end end)
You can write for example "Whats 1 + 5" or just "1 + 5" and on console you will see "6" There is subtract function too "6 - 5" - "1" NOTE: Place spaces between numbers and characters EDIT: Edited code so it will work witheout making spaces now: "5+1" = "6"
Its easy to edit, just add things in the section wheres "CHECKING ARGS" comment. Example of args ("1 + 6") args[1] represents "1" args[2] represents "+" args[3] represents "6" You can also make new functions like "/", "*"
EDIT2: Its now not as huge as it was :)
You can do what you're trying to through the use of string patterns and some useful string functions:
game.Players.LocalPlayer.Chatted:connect(function(msg) local n1, n2 = msg:match('(%d+)%s*%+%s*(%d+)'); if n1 and n2 then n1 = tonumber(n1); n2 = tonumber(n2); if n1 > 0 and n1 < 101 and n2 > 0 and n2 < 101 then print(msg.." = "..n1+n2); end; end; end)
Without understanding of what string patterns are and what they do, what's inside of the match
function can seem like another language. I urge you to check out the above wiki page on string patterns.
Hope this helped.
EDIT: Edited to account for potential whitespace.