Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Script cannot find different numbers or characters from a string?

Asked by
SuperPuiu 497 Moderation Voter
2 years ago
Edited 2 years ago

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

Log in to vote
1
Answered by 2 years ago
Edited 2 years ago

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
0
Thank you so much! SuperPuiu 497 — 2y
Ad

Answer this question