Howdy, Stranger!

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

Computing string sums? Ie "40+2"

in Questions Posts: 181

Can we compute string sums like "1/2" or "40+2" etc directly without a more elaborate string interpreter function?

I tried print( tonumber("1/2 ") ) but that failed as expected...

Comments

  • Posts: 237

    @Kirl There is a function called load, which loads a function in the form of a string.
    Example:

    function setup()
        local str="40+3*4/4" --should print out 43
        local val=load("return "..str)()
        print(val)
    end
    
  • Posts: 181

    Excellent, thanks a lot cc! =)

  • edited June 2017 Posts: 160

    @CamelCoder wasn't it called loadstring?

    a = loadstring("return 63 / 2")()
    print(a)
    

    Was the name of the function changed? Or am I just wrong?

    Edit: I tried both load and loadstring. They both seem to work the same... Can someone please explain to me why. Thanks :smile:

  • dave1707dave1707 Mod
    Posts: 7,604

    Both ways work, so either one can be used in this case.

  • Posts: 237

    @Kolosso As @dave1707 said, both work. I used to use loadstring(), but then I realized that it would be simpler to use load() because it is actually in the auto-complete.

  • Posts: 160
Sign In or Register to comment.