Use of engfunc(EngFunc_NumberOfEntities) would be incorrect in this case. You should use global_get(glb_maxEntities) instead of that.
Let's say that you have ent1, ent2 and ent3, then if you would remove the second one number of entities would be 2 and your method will not detect the last one.