table to math
table to math
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"?
- TechnoCat
- Inner party member
- Posts: 1612
- Joined: Thu Jul 30, 2009 12:31 am
- Location: Milwaukee, WI
- Contact:
Re: table to math
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.
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.
Last edited by TechnoCat on Mon Apr 25, 2011 3:14 pm, edited 2 times in total.
- slime
- Solid Snayke
- Posts: 3170
- Joined: Mon Aug 23, 2010 6:45 am
- Location: Nova Scotia, Canada
- Contact:
Re: table to math
Something like
might work.
Code: Select all
local mathstr = table.concat(mathtbl)
local sum = loadstring("return "..mathstr)()
Last edited by slime on Mon Apr 25, 2011 3:16 pm, edited 1 time in total.
- TechnoCat
- Inner party member
- Posts: 1612
- Joined: Thu Jul 30, 2009 12:31 am
- Location: Milwaukee, WI
- Contact:
Re: table to math
http://pastie.org/1831669slime wrote:easy solution
Re: table to math
That way works like a charm, thanks.
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 :/
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 :/
- sharpobject
- Prole
- Posts: 44
- Joined: Fri Mar 18, 2011 2:32 pm
- Location: California
Re: table to math
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.slime wrote:Something likemight work.Code: Select all
local mathstr = table.concat(mathtbl) local sum = loadstring("return "..mathstr)()
Re: table to math
Yeah it was for a calculator, http://love2d.org/forums/viewtopic.php?f=5&t=2890sharpobject 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.
Who is online
Users browsing this forum: No registered users and 5 guests