Page 1 of 1

table to math

Posted: Mon Apr 25, 2011 3:05 pm
by BarnD
Lets say if i have a table with "1, 9, +, 5, *, 1", is there some sort of way that I could get them out of the table and then do the maths "19+5*1"?

Re: table to math

Posted: Mon Apr 25, 2011 3:11 pm
by TechnoCat
Parse it into Reverse Polish Notation via Stunting-Yard algorithm
I've done it in the past with 2 stacks. One for numbers, one for operations.
Pop one from operation, two from numbers. Perform calculation, push back on stack, continue.

Re: table to math

Posted: Mon Apr 25, 2011 3:13 pm
by slime
Something like

Code: Select all

local mathstr = table.concat(mathtbl)
local sum = loadstring("return "..mathstr)()
might work.

Re: table to math

Posted: Mon Apr 25, 2011 3:14 pm
by TechnoCat
slime wrote:easy solution
http://pastie.org/1831669
are-you-wizard.png
are-you-wizard.png (77.55 KiB) Viewed 2167 times

Re: table to math

Posted: Mon Apr 25, 2011 3:30 pm
by BarnD
That way works like a charm, thanks. :D
Was busy reading "Reverse Polish notation" to notice that an easy way got posted. Thanks for such quick replies too. :)
EDIT: fail spelling is fail.. but is now fixed :/

Re: table to math

Posted: Tue Apr 26, 2011 8:04 am
by sharpobject
slime wrote:Something like

Code: Select all

local mathstr = table.concat(mathtbl)
local sum = loadstring("return "..mathstr)()
might work.
Depending on how trusted this string is, you might not want to do that. If the string came from another player over the network, the other player could send you something like {"(function() love.update = nil return 7 end)()"}. This seems to be for a calculator that builds the string locally, so it should be fine.

Re: table to math

Posted: Tue Apr 26, 2011 1:41 pm
by BarnD
sharpobject wrote:Depending on how trusted this string is, you might not want to do that. If the string came from another player over the network, the other player could send you something like {"(function() love.update = nil return 7 end)()"}. This seems to be for a calculator that builds the string locally, so it should be fine.
Yeah it was for a calculator, http://love2d.org/forums/viewtopic.php?f=5&t=2890