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(...). Was $type.';
    }

    t as LuaObject;
    final name = t.id;

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

    // Null fields are marked as deleted in lua.
    // I don't remove them in this implementation,
    // but we do exclude them from all operations that
    // expose keys.
    final newFields = fields.entries
        .where((e) => e.value?.isNil == false)
        .map((e) => MapEntry(e.key, e.value!));

    return LuaObject.table(
      'ipairs_$name',
      Map<Object, LuaObject>.fromEntries(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.
    ''',
  );
}