Calculator Issues

Weird, try having the place file.
Calculator.rbxl (33.1 KB)

Module is in ReplicatedStorage and the LocalScript is in StarterPlayerScripts.

1 Like

Ok, sorry I forgot to put it into a module script. My bad!

EDIT: I deleted the last post because I solved why it didn’t work with an equal button

1 Like

Pretty fun challenge making this :slight_smile:

-- / kingerman88 

local Operations = {
    ["+"] = function(a,b) return a+b end,
    ["-"] = function(a,b) return a-b end,
    ["*"] = function(a,b) return a*b end,
    ["/"] = function(a,b) return a/b end,
    ["^"] = function(a,b) return a^b end,
    ["%"] = function(a,b) return a%b end,
}
local Order = {
    "[%^]",  -- exponent
    "[%*/%%]",  -- multiplication / division (and modulus)
    "[%+%-]" -- addition / subtraction
}

function CalculateOrderOfOperations(line:string):number
    local start, fin = line:find("%b()");
    if start then
        line = line:sub(1, start-1).. CalculateOrderOfOperations(line:sub(start+1, fin-1)) .. line:sub(fin+1);
    end
    
    for _,operator in ipairs(Order) do
        while line:match("[%d%.]+"..operator.."[%d%.]+") do
            local a,realOp,b = line:match("([%d%.]+)("..operator..")([%d%.]+)");
            a,b = tonumber(a), tonumber(b);
            local number = Operations[realOp](a,b);
            line = line:gsub("[%d%.]+"..operator.."[%d%.]+", tonumber(number), 1);
        end
    end
    return tonumber(line);
end

print(CalculateOrderOfOperations("2*2+5")) -- 9
print(CalculateOrderOfOperations("2*(1+3)+1")) -- 9
print(CalculateOrderOfOperations("3*3^(2-1)")) -- 9
print(CalculateOrderOfOperations("(1+1)*4.5")) -- 9
print(CalculateOrderOfOperations("((3+1)*.5)*4.5")) -- 9 (Complex Parentheses stuff epic)

Here’s a little bonus if you want to do calculations left to right (without order of operations)

Bonus Code
local Operations = {
    ["+"] = function(a,b) return a+b end,
    ["-"] = function(a,b) return a-b end,
    ["*"] = function(a,b) return a*b end,
    ["/"] = function(a,b) return a/b end,
    ["^"] = function(a,b) return a^b end,
    ["%"] = function(a,b) return a%b end,
}

local function CalculateLeftToRight(line:string):number
	local numbers = {};
	for w in line:gmatch("[%d%.]+") do
		print(w);
		table.insert(numbers, tonumber(w));
	end
	local total = table.remove(numbers, 1);
	for w in line:gmatch("[%+%-%*/%^%%]") do
		total = Operations[w](total, table.remove(numbers, 1));
	end
	return total;
end
1 Like