Skip to content
s-hadinger edited this page Oct 5, 2021 · 40 revisions

7. Libraries and Modules

7.1 Basic library

There are some functions and classes that can be used directly in the standard library. They provide basic services for Berry programs, so they are also called basic libraries. The functions and classes in the basic library are visible in the global scope (belonging to the built-in scope), so they can be used anywhere. Do not define variables with the same name as the functions or classes in the base library. Doing so will make it impossible to reference the functions and classes in the base library.

7.1.1 Built-in function

print function

Example

print(...)

Description

This function prints the input parameters to the standard output device. The function can accept any type and any number of parameters. All types will print their value directly, and for an instance, this function will check whether the instance has a tostring() method, and if there is, print the return value of the instance calling the tostring() method, otherwise it will print the address of the instance.

print('Hello World!') # Hello World!
print([1, 2, '3']) # [1, 2, '3']
print(print) # <function: 0x561092293780>

input function

Example

input()
input(prompt)

Description

input The function is used to input a line of character string from the standard input device. This function can use the prompt parameter as an input prompt, and the prompt parameter must be of string type. After calling the input function, characters will be read from the keyboard buffer until a newline character is encountered.

input('please enter a string:') # please enter a string:

input The function does not return until the “Enter” key is pressed, so the program "stuck" is not an error.

type function

Example

type(value)
  • value: Input parameter (expect to get its type).

  • return value: A string describing the parameter type.

Description

This function receives a parameter of any type and returns the type of the parameter. The return value is a string describing the type of the parameter. Table below shows the return values corresponding to the main parameter types:

Parameter Type return value Parameter Type return value
Nil ’nil’ Integer ’int’
Real ’real’ Boolean ’bool’
Function ’function’ Class ’class’
String ’string’ Instance ’instance’
type(0) #'int'
type(0.5) #'real'
type('hello') #'string'
type(print) #'function'

classname function

Example

classname(object)

Description

This function returns the class name (string) of the parameter. Therefore the parameter must be a class or instance, and other types of parameters will return nil.

classname(list) #'list'
classname(list()) #'list'
classname({}) #'map'
classname(0) # nil

classof function

Example

classof(object)

Description

Returns the class of an instance object. The parameter object must be an instance. If the function is successfully called, it will return the class to which the instance belongs, otherwise it will return nil.

classof(list) # nil
classof(list()) # <class: list>
classof({}) # <class: map>
classof(0) # nil

str function

Example

str(value)

Description

This function converts the parameters into strings and returns. str Functions can accept any type of parameters and convert them. When the parameter type is an instance, it will check whether the instance has a tostring() method, if there is, the return value of the method will be used, otherwise the address of the instance will be converted into a string.

str(0) # '0'
str(nil) #'nil'
str(list) #'list'
str([0, 1, 2]) #'[0, 1, 2]'
usage
number(value)
Description

This function converts the input string or number into a numeric type and returns. If the input parameter is an integer or real number, it returns directly. If it is a character string, try to convert the character string to a numeric value in decimal format. The integer or real number will be automatically judged during the conversion. Other types return nil.

Example
number(5) # 5
number('45.6') # 45.6
number('50') # 50
number(list) # nil
usage
int(value)
Description

This function converts the input string or number into an integer and returns it. If the input parameter is an integer, return directly, if it is a real number, discard the decimal part. If it is a string, try to convert the string to an integer in decimal. Other types return nil.

Example
int(5) # 5
int(45.6) # 45
int('50') # 50
int(list) # nil
usage
real(value)
Description

This function converts the input string or number into a real number and returns. If the input parameter is a real number, it will return directly, if it is an integer, it will be converted to a real number. If it is a string, try to convert the string to a real number in decimal. Other types return nil.

Example
real(5) # 5, type(real(5)) →'real'
real(45.6) # 45.6
real('50.5') # 50.5
real(list) # nil
usage
length(value)
Description

This function returns the length of the input string. If the input parameter is not a string, 0 is returned. The length of the string is calculated in bytes.

Example
length(10) # 0
length('s') # 1
length('string') # 6
usage
super(object)
Description

This function returns the parent object of the instance. When you instantiate a derived class, it will also instantiate its base class. The super function is required to access the instance of the base class (that is, the parent object).

Example
class mylist: list end
l = mylist() # classname(l) -->'mylist'
sl = super(l) # classname(sl) -->'list'
usage
assert(expression)
assert(expression, message)
Description

This function is used to implement the assertion function. assert The function accepts a parameter. When the value of the parameter is false or nil, the function will trigger an assertion error, otherwise the function will not have any effect. It should be noted that even if the parameter is a value equivalent to false in logical operations (for example, 0), it will not trigger an assertion error. The parameter message is optional and must be a string. If this parameter is used, the text information given in message will be output when an assertion error occurs, otherwise the default “Assert Failed” message will be output.

Example
assert(false) # assert failed!
assert(nil) # assert failed!
assert() # assert failed!
assert(0) # assert failed!
assert(false,'user assert message.') # user assert message.
assert(true) # pass
usage
compile(string)
compile(string,'string')
compile(filename,'file')
Description

This function compiles the Berry source code into a function. The source code can be a string or a text file. compile The first parameter of the function is a string, and the second parameter is a string ’string’ or ’file’. When the second parameter is ’string’ or there is no second parameter, the compile function will compile the first parameter as the source code. When the second parameter is ’file’, the compile function will compile the file corresponding to the first parameter. If the compilation is successful, compile will return the compiled function, otherwise it will return nil.

Example
compile('print(\'Hello World!\')')() # Hello World!
compile('test.be','file')

list Class

list is a built-in type, which is a sequential storage container that supports subscript reading and writing. list Similar to arrays in other programming languages. Obtaining an instance of the list class can be constructed using a pair of square brackets: [] will generate an empty list instance, and [expr, expr, ...] will generate a list instance with several elements. It can also be instantiated by calling the list class: executing list() will get an empty list instance, and list(expr, expr, ...) will return an instance with several elements.

Initialize the list container. This method can accept 0 to multiple parameters. The list instance generated when multiple parameters are passed will have these parameters as elements, and the arrangement order of the elements is consistent with the arrangement order of the parameters.

Serialize the list instance to a string and return it. For example, the result of executing [1, [], 1.5].tostring() is ’[1, [], 1.5]’. If the list container refers to itself, the corresponding position will use an ellipsis instead of the specific value:

l = [1, 2]
l[0] = l
print(l) # [[...], 2]

Append an element to the end of the list container. The prototype of this method is push(value), the parameter value is the value to be appended, and the appended value is stored at the end of the list container. The append operation increases the number of elements in the list container by 1. You can append any type of value to the list instance.

Insert an element at the specified position of the list container. The prototype of this method is insert(index, value), the parameter index is the position to be inserted, and value is the value to be inserted. After inserting an element at the position index, all the elements that originally started from this position will move backward by one element. The insert operation increases the number of elements in the list container by 1. You can insert any type of value into the list container.

Suppose that the value of a list instance l is [0, 1, 2], and we insert a string ’string’ at position 1, and we need to call l.insert(1, ’string’). Finally, the new list value is [0, ’string’, 1, 2].

If the number of elements in a list container is S, the value range of the insertion position is {i ∈ ℤ :  − S ≤ i < S}. When the insertion position is positive, index backward from the head of the list container, otherwise index forward from the end of the list container.

Remove an element from the container. The prototype of this method is remove(index), and the parameter index is the position of the element to be removed. After the element is removed, the element behind the removed element will move forward by one element, and the number of elements in the container will be reduced by 1. Like the insert method, the remove method can also use positive or negative indexes.

Get an element in the list container. The prototype of this method is item(index), the parameter index is the index of the element to be obtained, and the return value of the method is the element at the index position. list The container supports multiple indexing methods:

  • Integer index: The index value can be a positive integer or a negative integer (the same as the index method in insert). At this time, the return value of item is the element at the index position. If the index position exceeds the number of elements in the container or is before the 0th element, the item method will return nil.

  • list Index: Using a list of integers as an index, item returns a list, and each element in the return value list is an element corresponding to each integer index in the parameter list. The value of the expression [3, 2, 1].item([0, 2]) is [3, 1]. If an element type in the parameter list is not an integer, then the value at that position in the return value list is nil.

  • range Index: Using an integer range as an index, item returns a list. The returned value stores the indexed elements from list from the lower limit to the upper limit of the parameter range. If the index exceeds the index range of the indexed list, the return value list will use nil to fill the position beyond the index.

Set the value of the specified position in the container. The prototype of this method is setitem(index, value), index is the position of the element to be written, and value is the value to be written. index is the integer index value of the writing position. Index positions outside the index range of the container will cause setitem to fail to execute.

Returns list the number of elements in the container, which is the length of the container. The prototype of this method is size().

Reset list the length of the container. The prototype of this method is resize(count), and the parameter count is the new length of the container. When using resize to increase the length of the container, the new element will be initialized to nil. Using reszie to reduce the length of the container will discard some elements at the end of the container. E.g:

l = [1, 2, 3]
l.resize(5) # Expansion, l == [1, 2, 3, nil, nil]
l.resize(2) # Reduce, l == [1, 2]

Returns an iterator for traversing the current list container.

TODO add find() method from #83

map Class

map Class is a built-in class type used to provide an unordered container of key-value pairs. Inside the Berry interpreter, map uses the Hash table to implement. You can use curly brace pairs to construct a map container. Using an empty curly brace pair {} will generate an empty map instance. If you need to construct a non-empty map instance, use a colon to separate the key and value, and use a semicolon to separate multiple key-value pairs. For example, {0: 1, 2: 3} has two key-value pairs (0,1) and (2,3). You can also get an empty map instance by calling the map class.

Initialize the map container, this method does not accept parameters. Executing map() will get an empty map instance.

Serialize map as a string and return. The serialized string is similar to literal writing. For example, the result of executing ’str’: 1, 0: 2 is "’str’: 1, 0: 2". If the map container refers to itself, the corresponding position will use an ellipsis instead of the specific value:

m = {'map': nil,'text':'hello'}
m['map'] = m
print(m) # {'text':'hello','map': {...}}

Insert a key-value pair in the map container. The prototype of this method is insert(key, value), the parameter key is the key to be inserted, and value is the value to be inserted. If the key map to be inserted exists in the container, the original key-value pair will be updated.

Remove a key-value pair from the map container. The prototype of this method is remove(key), and the parameter key is the key of the key-value pair to be deleted.

Get a value in the map container. The prototype of this method is item(key), the parameter key is the key of the value to be obtained, and the return value of the method is the value corresponding to the key.

Set the value corresponding to the specified key in the container. The prototype of this method is setitem(key, value), key is the key of the key-value pair to be written, and value is the value to be written. If there is no key-value pair with the key key in the container, the setitem method will fail.

Return map The number of key-value pairs of the container, which is the length of the container. The prototype of this method is size().

range Class

range The class is used to represent an integer closed interval. Use the binary operator .. to construct an instance of range. The left and right operands of the operator are required to be integers. For example, 0..10 means the integer interval [0,10] ∩ ℤ.

Expansion Module

JSON Module

JSON is a lightweight data exchange format. It is a subset of JavaScript. It uses a text format that is completely independent of the programming language to represent data. Berry provides a JSON module to provide support for JSON data. The JSON module only contains two functions load and dump, which are used to parse JSON strings and multiply Berry objects and serialize a Berry object into JSON text.

usage
load(text)
Description

This function is used to convert the input JSON text into a Berry object and return it. The conversion rules are shown in Table 1.1. If there is a syntax error in the JSON text, the function will return nil.

JSON type Berry type
null nil
number integer or real
string string
array list
object map

JSON type to Berry type conversion rules

Example
import json
json.load('0') # 0
json.load('[{"name": "liu", "age": 13}, 10.0]') # [{'name':'liu','age': 13}, 10]
usage
dump(object, ['format'])
Description

This function is used to serialize the Berry object into JSON text. The conversion rules for serialization are shown in Table 1.2.

Berry type JSON type
nil null
integer number
real number
list array
map object
mapKey of string
other string

Berry type to JSON type conversion rules

Example
import json
json.dump('string') #'"string"'
json.dump('string') #'"string"'
json.dump({0:'item 0','list': [0, 1, 2]}) #'{"0":"item 0","list":[0,1,2]}'
json.dump({0:'item 0','list': [0, 1, 2],'func': print},'format')
#-
{
    "0": "item 0",
    "list": [
        0,
        1,
        2
    ],
    "func": "<function: 00410310>"
}
-#

Math Module

This module is used to provide support for mathematical functions, such as commonly used trigonometric functions and square root functions. To use the math module, first use the import math statement to import. All examples in this section assume that the module has been imported correctly.

Description

The approximate value of Pi π, a real number type, approximately equal to 3.141592654.

Example
math.pi # 3.14159
usage
abs(value)
Description

This function returns the absolute value of the parameter, which can be an integer or a real number. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. abs The return type of the function is a real number.

Example
math.abs(-1) # 1
math.abs(1.5) # 1.5
usage
ceil(value)
Description

This function returns the rounded up value of the parameter, that is, the smallest integer value greater than or equal to the parameter. The parameter can be an integer or a real number. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. ceil The return type of the function is a real number.

Example
math.ceil(-1.2) # -1
math.ceil(1.5) # 2
usage
floor(value)
Description

This function returns the rounded down value of the parameter, which is not greater than the maximum integer value of the parameter. The parameter can be an integer or a real number. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. floor The return type of the function is a real number.

Example
math.floor(-1.2) # -2
math.floor(1.5) # 1
usage
sin(value)
Description

This function returns the sine function value of the parameter. The parameter can be an integer or a real number, and the unit is radians. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. sin The return type of the function is a real number.

Example
math.sin(1) # 0.841471
math.sin(math.pi * 0.5) # 1
usage
cos(value)
Description

This function returns the value of the cosine function of the parameter. The parameter can be an integer or a real number in radians. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. cos The return type of the function is a real number.

Example
math.cos(1) # 0.540302
math.cos(math.pi) # -1
usage
tan(value)
Description

This function returns the value of the tangent function of the parameter. The parameter can be an integer or a real number, in radians. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. tan The return type of the function is a real number.

Example
math.tan(1) # 1.55741
math.tan(math.pi / 4) # 1
usage
asin(value)
Description

This function returns the arc sine function value of the parameter. The parameter can be an integer or a real number. The value range is [−1,1]. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. asin The return type of the function is a real number and the unit is radians.

Example
math.asin(1) # 1.5708
math.asin(0.5) * 180 / math.pi # 30
usage
acos(value)
Description

This function returns the arc cosine function value of the parameter. The parameter can be an integer or a real number. The value range is [−1,1]. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. acos The return type of the function is a real number and the unit is radians.

Example
math.acos(1) # 0
math.acos(0) # 1.5708
usage
atan(value)
Description

This function returns the arctangent function value of the parameter. The parameter can be an integer or a real number. The value range is [−∞,+∞]. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. atan The return type of the function is a real number and the unit is radians.

Example
math.atan(1) * 180 / math.pi # 45
usage
sinh(value)
Description

This function returns the hyperbolic sine function value of the parameter. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. sinh The return type of the function is a real number.

Example
math.sinh(1) # 1.1752
usage
cosh(value)
Description

This function returns the hyperbolic cosine function value of the parameter. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. cosh The return type of the function is a real number.

Example
math.cosh(1) # 1.54308
usage
tanh(value)
Description

This function returns the hyperbolic tangent function value of the parameter. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. tanh The return type of the function is a real number.

Example
math.tanh(1) # 0.761594
usage
sqrt(value)
Description

This function returns the square root of the argument. The parameter of this function cannot be negative. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. sqrt The return type of the function is a real number.

Example
math.sqrt(2) # 1.41421
usage
exp(value)
Description

This function returns the value of the parameter’s exponential function based on the natural constant e. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. exp The return type of the function is a real number.

Example
math.exp(1) # 2.71828
usage
log(value)
Description

This function returns the natural logarithm of the argument. The parameter must be a positive number. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. log The return type of the function is a real number.

Example
math.log(2.718282) # 1
usage
log10(value)
Description

This function returns the logarithm of the parameter to the base 10. The parameter must be a positive number. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. log10 The return type of the function is a real number.

Example
math.log10(10) # 1
usage
deg(value)
Description

This function is used to convert radians to angles. The unit of the parameter is radians. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. deg The return type of the function is a real number and the unit is an angle.

Example
math.deg(math.pi) # 180
usage
rad(value)
Description

This function is used to convert angles to radians. The unit of the parameter is angle. If there are no parameters, the function returns 0, if there are multiple parameters, only the first parameter is processed. rad The return type of the function is a real number and the unit is radians.

Example
math.rad(180) # 3.14159
usage
pow(x, y)
Description

The return value of this function is the result of the expression xy, which is the parameter x to the y power. If the parameters are not complete, the function returns 0, if there are extra parameters, only the first two parameters are processed. pow The return type of the function is a real number.

Example
math.pow(2, 3) # 8
usage
srand(value)
Description

This function is used to set the seed of the random number generator. The type of the parameter should be an integer.

Example
math.srand(2)
usage
rand()
Description

This function is used to get a random integer.

Example
math.rand()

Time Module

This module is used to provide time-related functions.

prototype
time()
Description

Returns the current timestamp. The timestamp is the time elapsed since Unix Epoch (1st January 1970 00:00:00 UTC), in seconds.

prototype
dump(ts)
Description

The input timestamp ts is converted into a time map, and the key-value correspondence is shown in Table 1.3.

key value key value key value
’year’ Year (from 1900) ’month’ Month (1-12) ’day’ Day (1-31)
’hour’ Hour (0-23) ’min’ Points (0-59) ’sec’ Seconds (0-59)
’weekday’ Week (1-7)

time.dump The key-value relationship of the function return value

prototype
clock()
Description

This function returns the elapsed time from the start of execution of the interpreter to when the function is called in seconds. The return value of this function is of type real, and its timing accuracy is determined by the specific platform.

String Module

The String module provides string processing functions.

TODO

Module os

The OS module provides system-related functions, such as file and path-related functions. These functions are platform-related. Currently, Windows VC and POSIX style codes are implemented in the Berry interpreter. If it runs on other platforms, the functions in the OS module are not guaranteed to be provided.

TODO

Module global

TODO see #99

Module solidify

TODO see #98