Home > Back-end >  C Lambda - Loop over integer array
C Lambda - Loop over integer array

Time:02-12

I'm trying to loop over an integer array using a lambda template.

The code to invoke the lambda would look something like this (demo purposes, not functional code):

menu.option("Set Pedestrian Health to 0").allpeds(ped => {
     SET_ENTITY_HEALTH(ped, 0);
});

The problem: how would I make the allpeds lambda template?

allpeds would loop over an array of unique integers representing a pedestrian in the game.

I have this code so far:

template<typename T> Menu& allpeds() {
    if (pressed()) {
        int numElements = 20;
        int arrSize = numElements * 2   2;

        int peds[arrSize];
        peds[0] = numElements;

        int countPeds = PED::GET_PED_NEARBY_PEDS(playerPed, peds, -1);

        for (int i = 0; i < countPeds; i  ) {
            int ped = peds[i * 2   2];

            // if this is the right way to do it,
            // how to put `ped` in an integer array, and return it
            // so I can use it in the lambda template?
        }
    }

    //return *this;
}

I'm trying to keep the code as C as possible.

If more explanation is needed, please let me know!

CodePudding user response:

The example you have shown is more C# than C , as far as the lambda syntax is concerned. But even then, the example is clearly passing the lambda as a parameter to allpeds(), and the lambda itself takes an input parameter, too. allpeds() is not returning an array that the lambda then iterates, allpeds() calls the lambda passing it each integer value as needed.

In C , you can use something like this:

menu.option("Set Pedestrian Health to 0").allpeds(
    [](int ped) {
        SET_ENTITY_HEALTH(ped, 0);
    }
);
template<typename FuncType>
Menu& allpeds(FuncType func) {
    if (pressed()) {
        int numElements = 20;
        int arrSize = numElements * 2   2;

        std::vector<int> peds(arrSize);
        peds[0] = numElements;

        int countPeds = PED::GET_PED_NEARBY_PEDS(playerPed, peds.data(), -1);

        for (int i = 0; i < countPeds;   i) {
            int ped = peds[i * 2   2];
            func(ped);
        }
    }

    return *this;
}
  • Related