Download MetaTrader 5
To add comments, please log in or register
Do you wonder how to use widgets? Read the article!
mar
1143
mar 2016.09.21 07:25 

Hi coders,

I have 10 objects in my chart. If I pop-up an alert with ObjectsTotal() the result is 10. When I want to color them all in green I do it this way:

for (int i=ObjectsTotal(); i>0; i--) {
   ObjectSetInteger(0, ObjectName(0, i), OBJPROP_COLOR, clrGreen);
}

Now my question is this:  when I run this code, only 9 objects are colored green. If I change i>0 to i>=0 all 10 objects are colored. But why?
ObjectsTotal() is 10. i>0 means that the loop should run as long as this condition is not met anymore. That is when i=0. So in my opinion i>=0 means that the loop runs 11 times instead of 10 times. The result shows me that I am wrong but can somebody explain me the logic? Why does the loop only run 9 times when using the code above?

Thanks! 

 

Edit:

Now I changed the code to:

for (int i=ObjectsTotal(); i>0; i--) {
   Alert(i+" "+ObjectName(0, i));
   ObjectSetInteger(0, ObjectName(0, i), OBJPROP_COLOR, clrRed);
}

The alert window looks like this:


What's the problem with the first run of the loop?

Fernando Carreiro
1571
Fernando Carreiro 2016.09.21 07:42  

Depending on what is done with the Objects, the correct way to "loop" is one of the following:

int ObjectCount = ObjectsTotal();

for( int i = ObjectCount - 1; i >= 0; i-- ) { ... }

// or 

for( int i = 0; i < ObjectCount; i++ ) { ... }

Had you consulted the documentation, you would have seen this in the examples.

peter.MT4Web
158
peter.MT4Web 2016.09.21 07:52  

This behavior belongs to the basics of the programming language.

If you have 10 elements you access then with index 0 to 9 and not 1 to 10.

Carl Schreiber
5965
Carl Schreiber 2016.09.21 08:27  

I am using mainly the while loop:

int o = ObjectsTotal();
while (o-->0) { 
   ...
]
mar
1143
mar 2016.09.21 08:56  

I understood that I have to use index 0-9 but my question is why?

Why can't I use 1-10? Or 11-20? Or even 1001-1010? These numbers only represent how often the code inside the loop has to be repeated. So why can't I use any numbers as long as the loop runs 10 times?

peter.MT4Web
158
peter.MT4Web 2016.09.21 09:13  
mar:

I understood that I have to use index 0-9 but my question is why?

Why can't I use 1-10? Or 11-20? Or even 1001-1010? These numbers only represent how often the code inside the loop has to be repeated. So why can't I use any numbers as long as the loop runs 10 times?

 


You can use for the loop what ever numbers you want.

But if you access the objects with ObjectName you have to use the parameters as defined.

There is no "it has to work as i want".

mar
1143
mar 2016.09.21 09:37  

Oh man, I feel so stupid now.... of course! It hasn't to do with the loop counter, it has to do with the object-reference!

Now I got it! Thanks!

/
To add comments, please log in or register