Modules - cyxigo/wi GitHub Wiki
Introduction
Before we go any further, we need to finally learn one VERY important thing – modules! They are used to organize your code into multiple files and load various libraries.
You have already seen them: std::puts that we used everywhere, std is a module too!
Exporting
Module's variables have to come from... somewhere. When you write a Wi script you need to explicitly export a bunch of variables via export statement – only they will be available when importing that script as a module. Typically, exporting is done at the end of a Wi script. Let's create a script called b.wi:
%% b.wi
x := 10;
y := 20;
z := 30;
export {
x, y
};
You can export only global variables.
Only x and y will be available from outside this script, z won't since we didn't export it!
Importing
Let's create our main script, called a.wi, and import b.wi using the import statement:
%% a.wi
b := import "b";
You don't need to write .wi in import, Wi handles it automatically. Now, we can access x and y via ::!
%% a.wi
b := import "b";
std::puts(b::x);
std::puts(b::y);
However, if we try to access z:
%% a.wi
b := import "b";
std::puts(b::x);
std::puts(b::y);
std::puts(b::z);
We get an error:
10
20
runtime error: variable z was not exported from module b.wi
--> a.wi:5 in main function
So don't forget to export-what-you-need!
Paths are resolved relative to the directory of the script that contains the import (absolute paths work too), and every module is loaded only once – importing it again gives you the same module. For import "b", Wi looks for b.wi, then b/init.wi, then the same two inside the lib folder next to your Wi executable.
If no script exists, Wi tries to load a library (b.so on Linux, b.dll on Windows), first next to the importing script and then in lib. Foreign libraries are not supported on other platforms. You can clearly see this if you try to import an unexistent script:
%% a.wi
c := import "c";
Output is:
compile error: failed to import module c
no script c.wi
no script c/init.wi
no script /home/cyxigo/wi/bin/lib/c.wi
no script /home/cyxigo/wi/bin/lib/c/init.wi
failed to load library ./c.so: cannot open shared object file: No such file or directory
failed to load library /home/cyxigo/wi/bin/lib/c.so: cannot open shared object file: No such file or directory
|
2 | c := import "c";
| ^
--> a.wi:2:14
[!NOTE] Wi used to have two separate syntaxes for script and library importing, being
requireandload!
Next: Error Handling