Janet 1.41.2-0fea20c Documentation
(Other Versions: 1.41.1 1.40.1 1.40.0 1.39.1 1.38.0 1.37.1 1.36.0 1.35.0 1.34.0 1.31.0 1.29.1 1.28.0 1.27.0 1.26.0 1.25.1 1.24.0 1.23.0 1.22.0 1.21.0 1.20.0 1.19.0 1.18.1 1.17.1 1.16.1 1.15.0 1.13.1 1.12.2 1.11.1 1.10.1 1.9.1 1.8.1 1.7.0 1.6.0 1.5.1 1.5.0 1.4.0 1.3.1 )

Tuple C API

The Janet tuple data structure is exposed via the JanetTupleHead struct. Usually, you can interact with tuples without interacting with JanetTupleHead directly. However, interacting with a janet tuple head can be helpful when embedding in non-C languages. Just like arrays, it is recommended to use the provided API functions.

Definition

/* Prefix for a tuple */
struct JanetTupleHead {
    JanetGCObject gc;
    int32_t length;
    int32_t hash;
    int32_t sm_line;
    int32_t sm_column;
    const Janet data[];
};
typedef struct JanetTupleHead JanetTupleHead;

Creating a Tuple

You can create a tuple using janet_tuple_begin and janet_tuple_end:

Janet *dimensions = janet_tuple_begin(2);
dimensions[0] = janet_wrap_integer(400);
dimensions[1] = janet_wrap_integer(600);
Janet tuple = janet_wrap_tuple(janet_tuple_end(dimensions));

Accessing Tuple Values

From C, you can access tuple values from a tuple passed to a C function using array indexing:

static Janet cfun_color_tuple(int32_t argc, Janet *argv) {
    janet_fixarity(argc, 1);

    if (janet_checktype(argv[0], JANET_TUPLE)) {
        JanetTuple color_tup = janet_gettuple(argv, 0);
        if (janet_tuple_length(color_tup) == 4) {
            int r = janet_unwrap_integer(color_tup[0]);
            int g = janet_unwrap_integer(color_tup[1]);
            int b = janet_unwrap_integer(color_tup[2]);
            int a = janet_unwrap_integer(color_tup[3]);
        }
    }
    // ...
}

Functions

JANET_API Janet *janet_tuple_begin(int32_t length);

Create a new empty tuple of the given size. This will return memory which should subsequently be filled with your values. The memory will not be collected until janet_tuple_end is called.

JANET_API JanetTuple janet_tuple_end(Janet *tuple);

Finish building the tuple. Be sure to call this before using the tuple as it includes calculating the tuple hash used for equality checking.

JANET_API JanetTuple janet_tuple_n(const Janet *values, int32_t n);

Build a tuple with n values. Unlike janet_tuple_begin, this builds a tuple by copying an existing list of values that you provide.

#define janet_tuple_length(t) (janet_tuple_head(t)->length)

Returns the length of a tuple.

#define janet_tuple_head(t) ((JanetTupleHead *)((char *)t - offsetof(JanetTupleHead, data)))

Return the JanetTupleHead* from a Janet* pointing to the first Janet in the tuple.

#define janet_tuple_from_head(gcobject) ((JanetTuple)((char *)gcobject + offsetof(JanetTupleHead, data)))

Return the Janet* pointing to the first Janet element in the tuple from a JanetTupleHead*.