Jump to content

[HELP] Calcular uma expressão matemática


Recommended Posts

Posted

Olá pessoal, eu estou com uma dúvida, eu preciso criar um script no qual resolva uma expressão matemática, ex: 10+50/2*10, eu criei um que apenas realiza uma conta, ex: 10/2, e então queria saber como possa criar tal script que suporte realizar a conta com vários operadores e valores em uma string?

conta = "100/25" 
table_op = {"+","-","*","/"} 
  
function obterOperador(conta) 
    for i=1, string.len(conta) do 
        for _,v in pairs(table_op) do 
            if string.find(conta, v) then 
                op = v 
                teste_op = true 
            end 
        end 
    end 
    if (teste_op) then 
        return op 
    else 
        return false 
    end 
end 
  
function obterN1(op,conta) 
    pos = string.find(conta,op) 
    get_txt = string.sub(conta,0,(pos-1)) 
    if tonumber(get_txt) then 
        return tonumber(get_txt) 
    else 
        return false 
    end 
end 
  
function obterN2(op,conta) 
    pos = string.find(conta,op) 
    get_txt = string.sub(conta,(pos+1),string.len(conta)) 
    if tonumber(get_txt) then 
        return tonumber(get_txt) 
    else 
        return false 
    end 
end 
  
-- inicio 
op = obterOperador(conta) 
if op then 
    n1 = obterN1(op,conta) 
    n2 = obterN2(op,conta) 
    if op == "+" then 
        r = n1+n2 
    elseif op == "-" then 
        r = n1-n2 
    elseif op == "*" then 
        r = n1*n2 
    elseif op == "/" then 
        r = n1/n2 
    end 
     
    outputChatBox(r) 
end 

Obs:

¹Também é preciso que seja mantido a ordem dos operadores para realizar as contas (multiplicação/divisão antes de adição/subtração)

²Não posso utilizar eventos

Posted

Acho que não entendi a ordem do cálculo.

Seria, por exemplo:

60/2 * 10; e depois 30 * 10?

Escrevi aqui um código que calcula as expressões numa string, e passa para uma tabela chamada valuesToCalc.

E nessa tabela, os valores são armazenados em índices diferentes, que serve para cada etapa do cálculo.

A função responsável pelo cálculo é a docalcvalues - não cheguei a fazer essa parte - e ainda não testei meu código por completo.

Você pode ver como funciona o meu código e usar esse método para fazer funcionar com expressões maiores.

Aqui:

  
testcalc = "5+7/2*5" 
local oprts = {"+","-","*","/"} 
local valuesToCalc = {} 
  
local startpos = 1 
local hasOperator = true 
  
local function getStringOperatorCount() 
    local total = 0 
    for subpos=1, #testcalc do 
        for i,v in ipairs(oprts) do 
            if testcalc:sub( subpos, subpos ):find( v ) then 
                total = total + 1 
            end 
        end 
    end 
    return total 
end 
  
for _,getStringOperatorCount() do 
  for i,v in ipairs(oprts) do 
    local curstring = testcalc:sub( startpos, #testcalc ) 
    op = curstring:find( v ) 
    if op then 
     
        local firstValue = testcalc:sub( startpos, op - 1 ) 
        if not tonumber(startpos) then 
            firstValue = 0 
        end 
         
        local function g_substring() 
            for i, v in ipairs( oprts ) do 
                s = testcalc:sub( op + 1, #testcalc ) 
                if s:find( v ) then 
                    local subpos = s:find( v ) 
                    startpos = subpos 
                    return subpos - 1 
                end 
            end 
            hasOperator = false 
            startpos = #testcalc 
            return #testcalc 
        end 
        local secondValue = testcalc:sub( op + 1, g_substring() ) 
         
        valuesToCalc[ #valuesToCalc + 1 ] = { 
            values = {firstValue, secondValue}, 
            operator = testcalc:sub( op,op ) 
        } 
        if not hasOperator then docalcvalues() end; 
    end 
  end 
end 
  
function docalcvalues() 
    for i, v in ipairs(valuesToCalc) do 
        local fnumber, snumber = v.values[1], v.values[2] 
        local op = v.operator 
        -- Código... 
         
         
        outputChatBox( tostring(f)..", "..tostring(s)..", "..tostring(op) ) 
    end 
end 
  

Talvez eu veja depois essa parte de calcular os valores da tabela, às vezes o primeiro valor pode retornar 0, aí só você retornar o segundo (quando for preciso).

Please do not PM me with scripting related question nor support, use the forums instead.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...