How to replace Arrayname in function?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Cainnech
    New Member
    • Nov 2007
    • 132

    How to replace Arrayname in function?

    Hey guys,

    I've got a question about arrays and I think it's related to the data types.

    I want to construct a generic function that I can use on multiple arrays.
    Basically I've got a number of arrays which I need to fill. To do that I created a generic function that adds a value to an array.

    Now I'm trying to put the Arrayname also in that function so that I only have to call the function with the name of the array and the value and the value is inserted in the array.

    I'll give you the code to make myself clear:
    Code:
    function AddToArray(arr, value)
    
        if ubound(arr) = -1 then
    
          ReDim arr(0)
          arr(0) = value
    
        else
    
          ReDim Preserve arr(ubound(arr) + 1)
          arr(ubound(arr)) = value
    
        end if
    
    
    end function
    
    Dim output 
    output = Array()
    
    AddToArray("output", "AnyGivenValue")
    The problem probably lies in the name of the array that I'm sending to the function. Here I put it in brackets like it is a string, but I know it's not. It's an array.

    Anybody have any ideas on how to solve this?

    Thanks.
    Cainnech
  • Cainnech
    New Member
    • Nov 2007
    • 132

    #2
    Ah, found it after much looking around.

    Code:
    AddToArray(output, "AnyGivenValue")
    Should have been:
    Code:
    AddToArray output, "AnyGivenValue"
    The brackets were not neccessary.

    Greets,
    Cainnech

    Comment

    • Stewart Ross
      Recognized Expert Moderator Specialist
      • Feb 2008
      • 2545

      #3
      Mmm. Function calls should have their argument in brackets, but as you are not assigning the value of the function to a variable you should be using

      Code:
      Call AddToArray(output, "AnyGivenValue")
      However, it's not the brackets that made the real difference - you didn't mention that you've removed the double-quote marks from the array name too, as indeed was essential. You are then passing the array itself by reference to the sub as a dynamic array argument, instead of the name of the array.

      Trying to pass the name of the array was a blind alley for you, as you can't recover the array itself from its name; you did indeed need to pass the array by reference instead.

      When you wish to pass arrays of differing dimensions you must use a dynamic array argument, as you are doing in line 19 of post 1.

      -Stewart
      Last edited by Stewart Ross; Feb 6 '11, 09:07 PM.

      Comment

      Working...