The main script
A main script is a simulation script. By default, each scene in CoppeliaSim will have one main script. It contains the basic code that allows a simulation to run. Without main script, a running simulation won't do anything.
The main script contains a collection of callbacks functions that are appropriately called by the system. Except for the initialization callback, all other callbacks are optional. The default main script is typically segmented in 4 callback functions:
Following is the typical main script, slightly simplified:
There are however many more system callback functions the main script can use to react to various events.
The main script is not supposed to be modified. The reason for this is following: one of CoppeliaSim's strength is that any model (robot, actuator, sensor, etc) can be copied into a scene and is immediately operational. When modifying the main script, you run the risk that models won't perform as expected anymore (e.g. if your main script lacks the command sim.handleChildScripts then all models copied into the scene won't operate at all). Another reason is that keeping a default main script allows old scenes to easily adjust for new functionality (e.g. if a new CoppeliaSim version introduces a neat command sim.doMagic(), then old scenes will automatically be updated to have that command also called in their main script).
If however, for a reason or another you really need to modify the main script of a scene, you can do this by double-clicking the light-red script icon next to the world icon at the top of the scene hierarchy:
[Main script icon]
Most of child script's system callback functions are called from the main script, via the sim.handleChildScripts function, which operates in a cascading fashion upon the scene hierarchy and the child scripts attached to individual scene object.
If you look at the default main script, you can notice that the actuation function allows actuating or modifying the scene content (e.g. sim.handleDynamics, etc.), while the sensing function allows sensing and probing the scene content (e.g. sim.handleProximitySensor, etc.). Following illustrates what happens in the default main script when a mobile robot equipped with a proximity sensor is simulated:
[Default actuation - sensing - display sequence]
With above's sequence in mind, child scripts will always read (with sim.readProximitySensor) the proximity sensor's state from previous sensing (which happened at the end of previous simulation pass, inside of the main script, with sim.handleProximitySensor), then react to obstacles.
If you need to explicitely handle a sensor, then make sure to always do it while in the sensing section, otherwise you might end-up with situations where the display appears wrong as illustrated in following figure:
[Sensing - actuation - display sequence]
As does the main script have an actuation-sensing sequence, so do child scripts.