Modules: Compatibility with REBOL V2
There have been questions about how to create modules that are
compatible between REBOL V2 and V3.
Generally, modules written for V2 will work in V3 (all other
compatibility issues aside, such as PORTs). That is, if in V2 you load a
file that provides a module to your program, and you call its functions,
that will work the same way in V3.
The reason that this works is because such files are "unofficial
modules" or "modules by convention". They are nothing more than
additional code sections for your script... as if they appeared directly
within your script.
REBOL V3 provides an official definition of modules. In a nutshell,
modules give you control over contexts (think of them like you do
objects). For files, the script header object determines what is
officially a module in V3.
The default format of a module is trivial. (This is also done to
provide compatibility, but also to encourage all programmers, even
beginners to strongly consider writing their own modules, when
it makes sense to do so.)
Only one extra line in the header is needed to make any script file into
a module:
module: 'mod-example
Here defining module triggers REBOL to process the file as a module,
and mod-example provides the name of the module. The name gives
you a way to identify the module later within the REBOL system. (For
example, if you want to purge the module from the system.)
Here is a valid REBOL V3 module:
REBOL [
title: "Stock Handler"
module: 'mod-stocks
]
stocks: []
buy: func [symbol price] [
repend stocks [symbol price]
]
sell: func [symbol price] [
remove-all [asymbol aprice] stocks [
symbol = asymbol
]
]
Note that by default, this module exports all of its defined values. The
buy and sell functions are exported, and so is the stocks
block. Again, this behavior was selected to make it easy for
beginners to write their own modules.
Programmers who have a little more experience may choose to make some
of the module values private and others public. Again, such requirements
can be specified in the header. Here is the revised script that only
exports the buy and sell functions:
REBOL [
title: "Stock Handler"
module: 'mod-stocks
export: [buy sell]
]
stocks: []
buy: func [symbol price] [
repend stocks [symbol price]
]
sell: func [symbol price] [
remove-all [asymbol aprice] stocks [
symbol = asymbol
]
]
The export specifies only buy and sell be exported.
The stocks word is not exported, so its value cannot be accessed
outside of the module.
2 Comments
|