Skip to content

Passing Iterators #396

@dustinlacewell

Description

@dustinlacewell

It would be handy to be able to pass around iterators so that Typescript can be amenable to more refactoring. An example is being able to return the result of strings.gmatch and iterate it somewhere else:

export function parseMessage(message: string): [string, Iterable<string[]>] {
    const [command] = string.match(message, "^\.(%w+)");

    if (command == null) {
        return;
    }

    let args;
    let [_, argstr] = string.match(message, "^\.(%w+)%s+(.+)");

    if (argstr) {
        args = string.gmatch(argstr, "%S+");
    }
    return [command, args]
}
import * as commands from './commands';

function onChat(message: string, sender: any) {
    const [cmd, args] = commands.parseMessage(message);
    print(`cmd: ${cmd}`)
    for (const arg of args) {
        print(`arg: ${arg}`)
    }
}

Which fails with "attempt to call a nil value" within the Iterator implementation:

    __TS__Iterator = function(iterable)
        local iterator = iterable[Symbol.iterator](iterable);  <---
        return function()
            local result = iterator:next();
            if not result.done then
                return result.value;
            else
                return nil;
            end
        end;
    end;

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions