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

- Calculating strings ?

Asked by 9 years ago

Is it possible to do this:

function calculate(str)
    --do stuff with "str"
    return str
end

string = "1+2/3-2^(2*2.4)"
result = calculate(string)
print(result)

Is it possible to make a function to calculate what is in the string?

2 answers

Log in to vote
1
Answered by 9 years ago

The easiest way to do it is to use the loadstring function. The thing this function does, is, it returns a function that does what you tell it, but through a string.

For example,

local func = loadstring("print'hello world'")
func()  --> hello world

Now, we can use this to calculate strings.

function calculate(str)
    local str2 = loadstring("return "..str)() -- the same as function() return [anything] end
    return str2
end

I hope it helped.

Ad
Log in to vote
0
Answered by 9 years ago

Look up string patterns and string function dump on the wiki.

or try tonumber(string)

Answer this question