Calculator

This Brain4it module implements a simple calculator that can perform the four basic arithmetic operations: sum, subtract, multiply and division. It's is a good example to understand how the Brain4it dashboards work.

As shown in the image, the dashboard of this module paints a 3 line display and a numeric pad with some additional keys.

Internally, this module stores 3 variables:

  • previous_value: the previous entered number.
  • operator: the operator selected (a reference to +, -, * or /).
  • current_value: the number that is being entered.

The display widget shows the text returned by the @display exterior function, that is the result of concatenating the previous variables:

(function (context data)
  (concat
    (if (= null previous_value)
      ""
      (concat previous_value "\n")
    )
    (if (= null operator)
      ""
      (concat operator "\n")
    )
    current_value
  )
)

When a numeric button is pressed the @digit function is invoked to append the corresponding digit to the current_value variable:

(function (context digit)
  (set current_value (concat current_value digit))
  (module-notify "@display")
)

The module-notify function is called to notify the clients that the value of @display has changed.

When the user press a operator button (+, -, *, /) the @operator function is executed:

(function (context key)
  (do_operation)
  (set current_value "")
  (set operator (reference key))
  (module-notify "@display")
)

This function stores in the operator variable the selected operator and calls the do_operation function to perform the corresponding arithmetic operation:

(function ()
  (if (> (length current_value) 0)
    (do
      (set current_value (number current_value))
      (set previous_value
        (if (= null operator)
          current_value
          (if (= null previous_value)
            (eval (list operator current_value))
            (eval
              (list
                operator
                previous_value
                current_value
              )
            )
          )
        )
      )
    )
  )
)
Download module
Top