MX2 Library Init function

Community Forums/Monkey2 Talk/MX2 Library Init function

Danilo(Posted 2016) [#1]
Looking at modules/std/std.monkey2 we see a module-private "Main()" function.

1.) Are such library initializers automatically called as soon as we #Import the lib?
2.) At what exact stage is the lib init function called? Right before executing user’s Main() function?
3.) Is there also a way for a clean-up function for libraries? For example for closing automatically still opened files at program end, etc.

Thanks in advance!


marksibly(Posted 2016) [#2]
> Looking at modules/std/std.monkey2 we see a module-private "Main()" function.

Any module with a Main() in it will have its Main() called automatically just *after* all globals/consts have been initialized but *before* app Main() executes.

Since modules can't have cyclic dependencies, they will always be called in correct order, eg: if module X imports module Y (ie: depends on), then module Y's main is guaranteed to be called *before* module X's.

Actually, there's no difference between app Main() and module Main(). Since the app depends on ALL modules, and NO modules depend on the app, app Main() just happens to be the Main called last!

There is no 'clean up' function as yet, but for most things like open files, allocated memory etc. it's just fine to let the OS do the cleanup. In fact, in the case of memory allocation it's usually WAY faster.

There's a libc function called 'atexit' that allows you to register a cleanup function for a process (not added yet) and I may add something similar for monkey code, like Global MainReturned:Void(), so you can register cleanup functions inside a modules Main(). But not sure how this will work exactly yet.


Danilo(Posted 2016) [#3]
Very nice! Thank you! :)