howmanysmall / Janitor

Janitor library.
https://howmanysmall.github.io/Janitor/
MIT License
105 stars 18 forks source link

Issue with closing threads #36

Closed qurxtscoder closed 8 months ago

qurxtscoder commented 8 months ago

When I add threads to the janitor, and put the method as true as the documentation says it ends up erroring

energyJanitor.Add(task.defer(() => {
        while (true) {
            task.wait(3)

            if ((zoneEnergy?.GetChildren().size() ?? 0) <= 30) {
                SpawnEnergy(world)
            }
        }
    }), true);

ReplicatedStorage.rbxts_include.node_modules.@rbxts.knit.Knit.Util.Janitor:76: attempt to index thread with boolean

howmanysmall commented 8 months ago

extremely old version of janitor that did not support threads

also i'd just use flamework for typescript

howmanysmall commented 8 months ago

here's a polyfill if you need one:

//!native
//!optimize 2

import { Janitor } from "@rbxts/janitor";

function smartThreadCancel(thread: thread) {
    let cancelled: boolean | undefined;
    if (coroutine.running() !== thread) [cancelled] = pcall(() => task.cancel(thread));

    if (!cancelled) {
        const toCancel = thread;
        task.defer(() => task.cancel(toCancel));
    }
}

export default function janitorAdd<
    O extends keyof U extends never
        ? object
        : I extends keyof U
            ? U[I]
            : M extends true
                ? Callback | thread
                : M extends undefined
                    ? RBXScriptConnection | { Destroy(): void }
                    : object,
    M extends undefined | ((this: O) => void) | ((_: O) => void) | ExtractKeys<O, () => void> | true,
    I extends keyof U | undefined = undefined,
    U extends object | void = void,
>(janitor: Janitor<U>, object: O, methodName?: M, index?: I) {
    if (typeIs(object, "thread")) {
        const localThread = object;
        janitor.Add((() => smartThreadCancel(localThread)) as never, true, index);
        return object;
    }

    return janitor.Add(object, methodName, index);
}
qurxtscoder commented 8 months ago

Alright thank you!