Functions for controlling the garbage collector and for registering finalizers on userdata. Teascript frees unreachable objects automatically; the functions here let you force a collection, for diagnostics or benchmarking, and release non-memory resources (file handles, sockets, native buffers) when a userdata is collected.

tea_Finalizer

Signature

typedef void (*tea_Finalizer)(void* p);

Description

Type of a userdata finalizer, as registered with tea_set_finalizer. It receives a pointer to the userdata’s raw data block.

A finalizer is not given a tea_State, so it cannot call the C API. It should only release the resources the block refers to.

Parameters

p
Pointer to the userdata’s raw data block

Example

static void buffer_finalizer(void* p)
{
    Buffer* b = (Buffer*)p;
    free(b->data);
}

See also

tea_set_finalizer, tea_new_userdata

tea_gc

Signature

int tea_gc(tea_State* T);
[-0, +0, -]

Description

Performs a full garbage collection cycle immediately. The collector marks every object that is still reachable and frees the rest, calling the finalizers of any userdata that gets freed.

The return value is the amount of memory reclaimed, in kibibytes (KiB, bytes divided by 1024). It is mostly useful for diagnostics and for benchmarking allocator behavior.

Parameters

T
Teascript state

Returns

The memory reclaimed by this cycle, in KiB.

Example

/* build and drop a large amount of garbage */
tea_new_list(T, 0);
for(int i = 0; i < 100000; i++)
{
    tea_push_integer(T, i);
    tea_add_item(T, -2);
}
tea_pop(T, 1);

int kib = tea_gc(T);
printf("Reclaimed %d KiB\n", kib);

See also

tea_set_finalizer, tea_get_allocf

tea_set_finalizer

Signature

void tea_set_finalizer(tea_State* T, tea_Finalizer f);
[-0, +0, -]

Description

Registers the finalizer f for the userdata on top of the stack. The collector calls it when the userdata becomes unreachable, and tea_close calls it for userdata that are still alive, so native resources are always released.

The userdata is not popped. The value on top of the stack must be a userdata.

Parameters

T
Teascript state
f
Finalizer to run when the userdata is collected

Example

typedef struct FileHandle
{
    FILE* fp;
} FileHandle;

static void file_finalizer(void* p)
{
    FileHandle* fh = (FileHandle*)p;
    if(fh->fp)
        fclose(fh->fp);
}

static void open_file(tea_State* T)
{
    const char* path = tea_check_string(T, 1);
    FileHandle* fh = (FileHandle*)tea_new_userdata(T, sizeof(FileHandle));
    fh->fp = fopen(path, "r");
    tea_set_finalizer(T, file_finalizer);
    /* the userdata is left on top of the stack as the result */
}

See also

tea_Finalizer, tea_gc, tea_new_userdata, tea_close