initStdIPairs method

void initStdIPairs()

Implementation

void initStdIPairs() {
  ipairs() {
    final t = findVar('table');

    if (t?.skipSemanitcs ?? false) {
      return t;
    }

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

    t as LuaObject;
    final name = t.id;
    // t.isTable was true.
    final fields = t.fields!;
    final Map<Object, LuaObject> newFields = {};

    int i = 0;
    while (i < fields.length) {
      if (fields.containsKey(i+1)) {
        newFields[i+1] = fields[i+1]!;
        i++;
      } else {
        break;
      }
    }

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

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

  defGlobal(LuaObject.func('ipairs', defIPairs, ipairs)).doc = LuaDoc(
    category: catRuntime,
    html: '''
    Enumerates over a lua table and returns a <code>{index, value}</code>
    pair. Used in for-loops where integer index is expected.
    ''',
  );
}