Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Problems with calculating numbers received from string.

AnatolyAnatoly Mod
edited April 2018 in Questions Posts: 830

Function:

math.sum = function(variable, from, to, condition)
    local n = 0
    for i = from, to do
        print(variable, i)
        local c = condition:gsub(variable, i)
        print(c)
        n = n + tonumber(c)
    end
    return n
end

In Main:

print(math.sum("n", 1, 35, "1/n^n"))

Error:

Math:8: attempt to perform arithmetic on a nil value
stack traceback:
    Math:8: in function 'math.sum'
    Main:8: in function 'setup'

Comments

  • dave1707dave1707 Mod
    Posts: 7,649

    @TokOut Try this.

    function setup()
        print("sum = "..math.sum("n", 1, 35, "1/n^n"))
    end    
    
    math.sum = function(variable, from, to, condition)
        local n=0
        for i = from, to do
            local c = condition:gsub(variable, i)
            x="val="..c
            loadstring(x)()
            print(c.." = "..val)
            n=n+val
        end
        return n
    end
    
  • AnatolyAnatoly Mod
    Posts: 830

    Thank you very much! That helped. I mean I tried loadscreen, too, but for some reason it didn’t worked. Now I see how to use it, again.

Sign In or Register to comment.