If a global function with the same name as the module is defined, it is treated as a constructor. The constructor is called after the module has been loaded and evaluated for the first time. Because of this the constructor could (and should) be defined at the beginning of the module. Despite being located “on top” it can make use of the functions declared later in the file.
Module constructors are used mostly for initialization purposes, e.g. for setting local variables to proper values. However, the actions within a constructor can be arbitrarily complex.
![]() | Note |
---|---|
Constructors can't have any arguments. The result of calling a constructor from the outside is ignored. |
{ // This is a module called "Class" with a constructor function. // module "Class"; // A globally accessible variable. // global integer class_var = 42; // This is the constructor (same name as the module). // global define Class() ``{ class_var = 12345; } } { // The usage of the "Class"-module. // import "Class"; return Class::class_var; // will be 12345 ! }