Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Script cannot find different numbers or characters from a string?

Hello ScriptingHelpers community!

Today I started to get better with string manipulation. What I want to do is:

The script takes a string, let's say "1 + 2" Script does the operation and prints it.

The code I tried:

local s = "1 + 2"

local Data = s:split(" ")
local Number
local Number2
local sum

for i,v in pairs(Data) do
	if string.find(v, "%d") then
		if not Number then
			Number = v
			print("First number is "..v)
		else
			print("Second number is "..v)
			Number2 = v
		end
	elseif string.find(v, "%W") then
		print("Special character is "..v)
		if v == "+" then
			sum = Number + Number2
		elseif v == "-" then
			sum = Number - Number2
		elseif v == "*" then
			sum = Number * Number2
		elseif v == "/" then
			sum = Number / Number2
		end
	end
end

print(sum)

So, what I did wrong? Edit: The script either finds both numbers or only first number and the special character

1 answer

✓ Accepted answer

The mistake you made is adding while number 2 is still nil. So just move the part that does the math to after the loop:

local s = "1 + 2"

local Data = s:split(" ")
local Number
local Number2
local sum

local operation -- new variable

for i,v in pairs(Data) do
	if string.find(v, "%d") then
		if not Number then
			Number = v
			print("First number is "..v)
		else
			print("Second number is "..v)
			Number2 = v
		end
	else
		print("Special character is "..v)
		operation = v -- set the variable to use later, after Number2 is set bc it's the last entry in the table ur looping through
	end
end

if operation == "+" then -- it's been moved to after the loop
	sum = Number + Number2
elseif operation == "-" then
	sum = Number - Number2
elseif operation == "*" then
	sum = Number * Number2
elseif operation == "/" then
	sum = Number / Number2
end

print(sum) -- works

1 comment

0

Thank you so much!

This discussion is preserved as it was. New answers, comments, and votes are closed.