Modules
In Sidef, a module is the declaration of a new namespace:
1
module Fibonacci {
2
func nth(n) {
3
n > 1 ? nth(n-2)+nth(n-1) : n
4
}
5
}
6
7
say Fibonacci::nth(12) # prints: 144
Copied!
The default namespace name is main. Variables from other namespaces can be used inside a module by either importing them, or by specifying their full name which includes the namespace:
1
var foo = 42
2
3
module Bar {
4
var baz = 99
5
say main::foo #=> 42
6
}
7
8
say Bar::baz #=> 99
Copied!
Importing an identifier in the current namespace, can be done using the syntax import namespace::identifier_name:
1
var foo = 42
2
3
module Bar {
4
import main::foo
5
var baz = 2*foo
6
}
7
8
import Bar::baz
9
say baz #=> 84
Copied!
Modules cannot be instantiated as objects, cannot be modified, and cannot be directly referred to by their name (like ModuleName) without a member name (like ModuleName::var_name). Therefore, they are for containing related code that doesn't need to be instantiated like a class.
Last modified 1yr ago
Copy link