howmanysmall / Janitor

Janitor library.
https://howmanysmall.github.io/Janitor/
MIT License
107 stars 17 forks source link

Issue with closing threads #36

Closed qurCoder closed 11 months ago

qurCoder commented 11 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 11 months ago

extremely old version of janitor that did not support threads

also i'd just use flamework for typescript

howmanysmall commented 11 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);
}
qurCoder commented 11 months ago

Alright thank you!