initStdPairs method

void initStdPairs()

Implementation

void initStdPairs() {
  pairs() {
    final t = findVar('table');
    if (t?.skipSemanitcs ?? false) {
      return t;
    }

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

    t as LuaObject;
    final name = t.id;

    // t.isTable was true.
    final fields = t.fields!;

    final newFields = fields.map<String, LuaObject>((k, v) {
      final value = switch (v) {
        null => LuaObject.nil('value'),
        final LuaObject obj => obj,
      };

      final id = value.id;
      return MapEntry<String, LuaObject>(id, value);
    });

    return LuaObject.table('ipairs_$name', newFields);
  }

  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.
    ''',
  );
}