Expression evaluator in just 45 lines of code...

Share your advanced PureBasic knowledge/code with the community.
User avatar
utopiomania
Addict
Addict
Posts: 1655
Joined: Tue May 10, 2005 10:00 pm
Location: Norway

Expression evaluator in just 45 lines of code...

Post by utopiomania »

MAJOR HACK WARNING! :) This is an expression evaluator that uses Javascript built in function to do the hard work.

The demo is a bit clunky due to the problems of interfacing with the webgadget in a simple way, but it works.

There are other functions that can be used this way to, amongst them a 'var.searc() / var.replace() for regular expressions
to validate input for example.

Code: Select all

;- javascript expression evaluator, 20061130, utopiomana
;
openWindow(0, 0, 0, 400, 260, "Calculator", 13238273) 
createGadgetList(windowID(0))
setGadgetFont(#PB_Default, fontID(loadFont(#PB_Any, "fixedsys", 10)))
webGadget(1, 0, 0, 0, 0, "")
textGadget(2, 10, 55, 380, 25, "Expression")
stringGadget(3, 10, 80, 380, 25, "a = 2; b = 12; Math.pow(b * 2, a * b)")
buttonGadget(4, 10, 130, 40, 25, "=")
textGadget(5, 10, 175, 380, 25, "Result")
stringGadget(6, 10, 200, 380, 25, "")

procedure.s eval(expr.s)
  s.s = "<script language = 'JavaScript'>"
  s.s + "location = eval('" + expr +"')</script>"
  procedureReturn "about:" + s
endProcedure

webObject.IWebBrowser2 = getWindowLong_(gadgetId(1), #GWL_USERDATA) 

;-program event handler
repeat 
  select waitWindowEvent() 
    case #PB_Event_Gadget
      select eventGadget()
        case 4  ;= button
          setGadgettext(1, eval(getGadgetText(3)))
      endSelect
    case #PB_Event_CloseWindow
      end
    default 
      if busy
        webObject\get_ReadyState(@ready)
        if ready 
          url.s = getGadgetText(1)
          pos = findString(url, "/script", 1)
          if pos
            setGadgetState(1, #PB_Web_Stop)
            setGadgetText(6, mid(url, pos + 8, len(url) - pos))
          endIf 
        endIf
      endIf 
      webObject\get_busy(@busy)
  endSelect
forever