Event programming comes at its best in a parallel language like urbiScript. By nature several events can occur in parallel and trigger some code execution that could run in parallel and overlap. We call this "implicit" parallelism. Nothing special is needed in urbiScript to achieve this, as the language integrates parallelism at the core of its semantics.

In practice, the simplest way to react to an event in urbiScript is to use the at command, which looks a bit like if and takes a test and a command to execute when the test becomes true. But unlike if, the at command remains always in background to trigger again, and it will never terminate:

 

at command

 

Another tool is whenever, which will loop the execution of the command as long as the test is true. A bit like while, it remains however in background when the test is false, until it becomes true again:

 

whenever command

 

Example

Here is a small example illustrating the at command:

at (sensorFront.val < threshold && safemode)
{
  robot.stop();
  if (sensorR.val > min_dist)
    robot.turn(right)
  else
    robot.turn(left);
};

 

Emit events

It is also possible to emit events with or without parameters using the simple ! prefix to the event name, and with ? to catch it later:

myevent!;
at (myevent?) do_something;

event_with_param!(45,"hello");
at (event_with_param?(45, var x)) echo x;
...

at can then be used to catch this event, and get the parameters associated if needed. Note that you can set the value of some of the parameters, realizing a simple filter in the process.

Like many other commands in urbiScript, events can also last during a given time. The example below throws an event that lasts for 2 seconds:

myevent! ~ 2s;

 

Download Urbi