I am working on a piece of sample code to use in the next chapter of my guide to programming in Harbour and HMG and have spotted something that I think should NOT work but it actually does. I really do not know why although I have my suspicions; if any one of the experts on Objects can help, I would really appreciate it!
As you can see, I declared a LOCAL array in FUNCTION Main. There are several other LABEL and BUTTON definitions but the one I am confused by is BUTTON btn_09 where ONCLICK calls another function called SortArray(aTrolley) which passes the LOCAL array to the function.
In the SortArray function, I call the COPY of the aTrolley array declared in FUNCTION main something else and then sort that copy before doing a number of other things.
If my understanding is right, this should only sort the COPY of the array it has been passed and should not change the original array which is LOCAL in the original function. BUT somehow it does sort the original array as well and the program works the way I expect it to. Why?
Is this something to do with Object behaviour where Win_1.btn_09 can see the original LOCAL (aTrolley) array and works that no matter what my UDF calls the copy of the array that it receives?
I am not as good with objects as I need to be, so it's quite good that I spotted this because I should learn something!
Many thanks,
Zim
http://www.harbour-guide.com
Code: Select all
#include "hmg.ch"
FUNCTION Main()
LOCAL nlblRow := 16
LOCAL nlblCol := 16
// Create a LOCAL memory variable that will be an array
LOCAL aTrolley := ARRAY(0)
SET FONT TO "Arial", 10
SET DATE BRITISH
// Add new elements to the array
AADD(aTrolley, "Potatoes")
AADD(aTrolley, "Mushrooms")
AADD(aTrolley, "Large Steak")
AADD(aTrolley, "Small Steak")
AADD(aTrolley, "Asparagus")
AADD(aTrolley, "Bottle of Wine")
DEFINE WINDOW Win_1 ;
AT 0,0 ;
WIDTH 704 ;
HEIGHT 480 ;
TITLE "Array Test" ;
MAIN
// Other code appears here to display a number of labels - removed to focus on the problem
DEFINE BUTTON btn_09
ROW nlblRow * 10
COL nlblCol * 15
CAPTION "Sort Array"
AUTOSIZE .T.
// When this button is clicked on, I am calling a function (see below) that sorts the array. As I declared
// the array LOCAL, I have passed the name of the variable as a parameter to the sort function.
ONCLICK SortArray(aTrolley)
END BUTTON
END WINDOW
CENTER WINDOW Win_1
ACTIVATE WINDOW Win_1
Return Nil /* -- End of FUNCTION Main() -- */
FUNCTION SortArray(aToSort)
// A COPY of the LOCAL array declared in the main function is received in this UDF which is then sorted. What is VERY
// strange is that this actually sorts the main array (aTrolley) as well as the copy called aToSort. I suspect that
// this is because the Object Win_1.btn_01 can "see" the array called aTrolley so it sorts that array no matter what
// I call the copy passed to this array. Am I right?
ASORT(aToSort)
// A few properties are changed after the array is sorted - example: Win_1.btn_01.Caption := "Sorted 1"
RETURN Nil