initStdPairs method

void initStdPairs()

Implementation

void initStdPairs() {
  pairs() {
    final t = findVar('table');

    if (!(t?.isTable ?? false)) {
      final type = t?.typeinfo;
      throw 'Expected table input for pairs(...). Was $type.';
    }

    int i = 1;
    t as LuaObject;

    final fields = t.fields ?? {};

    return LuaFuncBuilder
      .create('closure')
      .exec(call: () {
        // We loop because we must return a value
        // or null if the iterator has exhausted all
        // elements. If a field mapped by a key is nil,
        //it should be skipped, not returned.
        while(true) {
          if(i > fields.length) return null;
          final k = fields.keys.elementAt(i-1);
          i++;
          final v = fields[k];

          if(v?.isNil ?? true) continue;

          return [k,v];
        }
      });
  }

  final token = Token.synthesized('pairs');
  final defPairs = FuncExpr.named(
    token,
    body: [],
    args: [DeclArg(Token.synthesized('table'))],
    idParts: [RawExpr(token)],
  );

  defGlobal(LuaObject.func('pairs', defPairs, pairs)).doc = LuaDoc(
    category: catRuntime,
    html: '''
    Enumerates over a lua table and returns a <code>{key, value}</code>
    pair. Used in common for-loops.
    ''',
  );
}