Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: VB6 - Use a variable within a variable's name  (Read 11582 times)

0 Members and 1 Guest are viewing this topic.

Helpmeh

    Topic Starter


    Guru

  • Roar.
  • Thanked: 123
    • Yes
    • Yes
  • Computer: Specs
  • Experience: Familiar
  • OS: Windows 8
VB6 - Use a variable within a variable's name
« on: August 20, 2010, 07:28:06 PM »
Is it possible to use a variable's value to influence a new variable's name? In batch, one could do this:
Code: [Select]
set variable=1
set newvar%variable%=hello world <--- I need this line in VB6
echo %newvar1%
But I'm having a little trouble trying to pull this off in VB. It would save quite a bit of code if this was possible.
Where's MagicSpeed?
Quote from: 'matt'
He's playing a game called IRL. Great graphics, *censored* gameplay.

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: VB6 - Use a variable within a variable's name
« Reply #1 on: August 20, 2010, 07:41:52 PM »
Is it possible to use a variable's value to influence a new variable's name? In batch, one could do this:
Code: [Select]
set variable=1
set newvar%variable%=hello world <--- I need this line in VB6
echo %newvar1%
But I'm having a little trouble trying to pull this off in VB. It would save quite a bit of code if this was possible.

What are you trying to do? By which I mean, what are you doing that this would save time with?
I was trying to dereference Null Pointers before it was cool.

Helpmeh

    Topic Starter


    Guru

  • Roar.
  • Thanked: 123
    • Yes
    • Yes
  • Computer: Specs
  • Experience: Familiar
  • OS: Windows 8
Re: VB6 - Use a variable within a variable's name
« Reply #2 on: August 20, 2010, 07:59:29 PM »
I'm making a program (just for the *censored* of it) which pretty much monitors a workplace (hypothetically speaking), in which the user (the manager) sets up how many workers there are, who they are, how much they work, etc. All the controls which display information and the timers are in control arrays (with an array value for each worker). Problem is, I have to repeat the same code over and over with different variables, the only change being a sequential number at the end of the variable name.
Where's MagicSpeed?
Quote from: 'matt'
He's playing a game called IRL. Great graphics, *censored* gameplay.

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: VB6 - Use a variable within a variable's name
« Reply #3 on: August 20, 2010, 08:00:35 PM »
Problem is, I have to repeat the same code over and over with different variables, the only change being a sequential number at the end of the variable name.


Use Arrays or collections instead.
I was trying to dereference Null Pointers before it was cool.

Helpmeh

    Topic Starter


    Guru

  • Roar.
  • Thanked: 123
    • Yes
    • Yes
  • Computer: Specs
  • Experience: Familiar
  • OS: Windows 8
Re: VB6 - Use a variable within a variable's name
« Reply #4 on: August 20, 2010, 08:03:01 PM »
#1 Arrays can be used with variables?
#2 Collections?
Where's MagicSpeed?
Quote from: 'matt'
He's playing a game called IRL. Great graphics, *censored* gameplay.

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: VB6 - Use a variable within a variable's name
« Reply #5 on: August 20, 2010, 08:38:10 PM »
#1 Arrays can be used with variables?

Of course they can. Control arrays are a deviant structure that simulates a normal array very badly. You could create User Defined type to store employee data, and then have an array of those types:
Code: [Select]
Option Explicit
Public Type EmployeeData
    FirstName As String
    LastName As String
    HoursWorked As Long
   

End Type
Private Employees() As EmployeeData
Private EmployeeCount As Long
Private CurrentEmployee as Long



CurrentEmployee indicates the current index into the array.

Wether you have "Next" or "Previous" buttons to move through the data or wether you use a list or some other control to switch between them, the first thing you need is special handling in your various editing controls (in this case, three- first name, last name, and hours worked) that either change the "current" employeedata or break out if EmployeeCount is 0.

Adding a new Employee:

Code: [Select]
Private Sub CmdAdd_Click()

EmployeeCount=EmployeeCount+1
Redim Preserve Employees(1 to EmployeeCount)
CurrentEmployee=EmployeeCount
RefreshView()


End Sub

This adds a new item, and then refreshes the controls displaying state. It calls the following routine to do that:

Code: [Select]
Private Sub RefreshView()
If CurrentEmployee=0 then Exit Sub
txtFirstName.Text = Employees(CurrentEmployee).FirstName
txtLastName.Text = Employees(CurrentEmployee).LastName
txtHoursWorked.Text = Employees(CurrentEmployee).HoursWorked
if(currentemployee) = Ubound(Employees) then cmdNext.Enabled=False Else cmdNext.Enabled=True
if(currentemployee) = Lbound(Employees) then cmdPrev.Enabled=False Else cmdPrev.Enabled=True
End Sub


To move between the various employees, you merely change the "CurrentEmployee" variable and refresh the view again:

Code: [Select]
private sub CmdNext_Click()
    CurrentEmployee=CurrentEmployee+1
    RefreshView()
End Sub
Private Sub CmdPrev_Click()
    CurrentEmployee=CurrentEmployee-1
    RefreshView()
End Sub


And so on.

The various text boxes in question  (txtFirstName,txtLastName, txtHoursWorked) can be used to update the "current" employee.

You can either take advantage of the Change event, or use a "Save" button, or save in the cmdNext and cmdPrev routines:

Code: [Select]
Private Sub SaveEmployee()
With Employees(CurrentEmployee)
    .FirstName=txtFirstName.Text
    .LastName = txtLastName.Text
    .HoursWorked = Val(txtHoursWorked.Text)
End With
End Sub

Then, wherever you need to "save" the current value (either a Specified Save button, in the next or previous buttons, etc) you simply call "SaveEmployee".

Removing an Employee is a tad more tricky. We need to Remove an element, and this is done by moving all the higher elements down one index. You can do this manually:

Code: [Select]
Private Sub RemoveEmployee(RemoveIndex as Long)
Dim I as Long
For I = RemoveIndex to Ubound(Employees)-1
    Employees(RemoveIndex) = Employees(RemoveIndex+1)
Next
EmployeeCount=EmployeeCount-1
Redim Preserve Employees(EmployeeCount)




Quote
#2 Collections?


The other option is, instead of using a User Defined Type, you could define an "Employee" Class Module and keep a collection of them. Slightly more "involved" in a few ways, but a lot more flexible as well.
I was trying to dereference Null Pointers before it was cool.

Helpmeh

    Topic Starter


    Guru

  • Roar.
  • Thanked: 123
    • Yes
    • Yes
  • Computer: Specs
  • Experience: Familiar
  • OS: Windows 8
Re: VB6 - Use a variable within a variable's name
« Reply #6 on: August 20, 2010, 09:03:50 PM »
Wow...I guess that explains why it took so long for a reply, lol  :D

I'm not quite sure how to implement this into my program, as all the information is being displayed at once, in multiple controls.

I basically decided to follow through with just copying and pasting the code over and over, it wasn't so hard, only 5 changes per paste.
Where's MagicSpeed?
Quote from: 'matt'
He's playing a game called IRL. Great graphics, *censored* gameplay.

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: VB6 - Use a variable within a variable's name
« Reply #7 on: August 20, 2010, 09:10:22 PM »
I'm not quite sure how to implement this into my program, as all the information is being displayed at once, in multiple controls.

Personally, I would start over, and redesign it from scratch. From the sounds of things it doesn't sound too complicated, you've just overcomplicated it with multiple unnecessary control arrays.
I was trying to dereference Null Pointers before it was cool.

Salmon Trout

  • Guest
Re: VB6 - Use a variable within a variable's name
« Reply #8 on: August 21, 2010, 08:34:08 AM »
This question, "how do I make variable1, variable2 ... variableN?", is the classic indicator that the person needs to find out about arrays. You often see it the other way around as "how do I implement arrays in batch?"


ghostdog74



    Specialist

    Thanked: 27
    Re: VB6 - Use a variable within a variable's name
    « Reply #9 on: August 21, 2010, 10:24:01 AM »
    @helpmeh, what you basically want is arrays. But i think vb6 ( its been a long time) doesn't have arrays that can use strings as the index for the arrays (called dictionaries or hashes). Later implementation of vb may make use of the dictionary object (or collections), like those in vbscript.

    BC_Programmer


      Mastermind
    • Typing is no substitute for thinking.
    • Thanked: 1140
      • Yes
      • Yes
      • BC-Programming.com
    • Certifications: List
    • Computer: Specs
    • Experience: Beginner
    • OS: Windows 11
    Re: VB6 - Use a variable within a variable's name
    « Reply #10 on: August 21, 2010, 11:14:21 AM »
    @helpmeh, what you basically want is arrays. But i think vb6 ( its been a long time) doesn't have arrays that can use strings as the index for the arrays (called dictionaries or hashes). Later implementation of vb may make use of the dictionary object (or collections), like those in vbscript.

    VB can either use the built in Collection object:

    Code: [Select]
    Private Sub Test_Collection()
    Dim Col as Collection
    Set Col = new Collection
    Col.Add "Dog","Woof"
    Col.Add "Cat","Meow"
    Col.Add "Cow","Moo"
    Msgbox Col.Item("Dog") 'Shows "Woof"
    Msgbox Col!Dog 'Also shows "Woof" (! is a freaky weird Collection operator)


    End Sub

    The collection object is rather tricky to use in many situations, since you cannot map the value back into the key (since you no longer have access to any of the keys).

    Of course you can always reference the Scripting Runtime, where you can find the very same dictionary object that is exposed by the script host. You don't even need to reference them, actually, if you use late binding:

    Code: [Select]
    Public Sub testdictionary()
    Dim dict As ObjectSet dict = CreateObject("Scripting.Dictionary")
    dict.Add "Dog", "Woof"
    dict.Add "Cat", "Meow"
    dict.Add "Cow", "Moo"

    MsgBox dict.Item("Dog")
    MsgBox dict!Dog




    End Sub

    Of course this looks exactly the same as the collection example, but the dictionary has as you know a number of other useful properties/methods, including being able to retrieve the item keys. It has the slight disadvantage in that you cannot use a numeric index as you can for a collection.

    With VB.NET there are a number of choices. you could simply create a List<T> of the specified type T (String, int, whatever) or you could create a sort of dictionary by creating a List<KeyValuePair<String,Object>>, then you can use Linq to acquire values from it:

    Code: [Select]
    //assume _list is of type List<KeyValuePair<String,Object>>, skey is the key for the item we want.
    queryget = from var x in _list where x.Key.Equals(skey,StringComparison.OrdinalIgnoreCase) select x;
    foreach(var loopval in queryget)
    {
    //loopval is a KeyValuePair<String,Object> whose Key field matches skey.


    }

    And, if you were REALLY crazy, you could use an actual dictionary (but real men just fake it with Lists of KeyValuePairs):


    Code: [Select]
      public static void testdictionary()
            {

                Dictionary<String, String> dicty = new Dictionary<string, string>();


                dicty.Add("Dog", "Woof");
                dicty.Add("Cat", "Meow");
                dicty.Add("Cow", "Moo");

                Debug.Print(dicty["Dog"]);
                foreach (var q in (from x in dicty where x.Key.StartsWith("C", StringComparison.OrdinalIgnoreCase) select x).ToArray())
                {
                    Debug.Print(q.Key + "=" + q.Value);
                }


            }
    which gives us the following in the debug window:

    Woof
    Cat=Meow
    Cow=Moo


    All of this can be done in VB.NET (using the  various classes in System.Collections.Generic) but I'm not sure of the syntax.

     (Dim Variable as List(Of KeyValuePair(Of String,String)) or something like that.
    I was trying to dereference Null Pointers before it was cool.

    ghostdog74



      Specialist

      Thanked: 27
      Re: VB6 - Use a variable within a variable's name
      « Reply #11 on: August 21, 2010, 02:01:40 PM »
      when i look at how its implemented in VB, i can't help but wonder why its not as simple and straightforward to use as in Perl/Python.

      Salmon Trout

      • Guest
      Re: VB6 - Use a variable within a variable's name
      « Reply #12 on: August 21, 2010, 02:06:51 PM »
      Why oh why can't Visual Basic be more like Python? Or Perl? Or APL?



      Fleexy



        Intermediate

      • OW NEXT TIME I SHOULD TURN IT OFF BEFORE SERVICING
      • Thanked: 2
        • Yes
        • Yes
      • Experience: Experienced
      • OS: Windows XP
      Re: VB6 - Use a variable within a variable's name
      « Reply #13 on: August 21, 2010, 03:13:09 PM »
      Why can't Perl and Python be like VB? ;)
      I love .NET!

      ghostdog74



        Specialist

        Thanked: 27
        Re: VB6 - Use a variable within a variable's name
        « Reply #14 on: August 21, 2010, 04:07:31 PM »
        Why can't Perl and Python be like VB? ;)
        You want Perl/Python to be like VB ? in what sense? And have you used Python/Perl before?


        Salmon Trout

        • Guest
        Re: VB6 - Use a variable within a variable's name
        « Reply #15 on: August 21, 2010, 05:01:02 PM »
        APL beats the crap out of toy languages like Perl or Python.

        Quote
        It is concise, using symbols rather than words and applying functions to entire arrays without using explicit loops. It is solution focused, emphasizing the expression of algorithms independently of machine architecture or operating system.

        This immediate mode expression generates a typical set of Pick 6 lottery numbers: six pseudo-random integers ranging from 1 through 40, guaranteed non-repeating, and displays them sorted in ascending order:

        x[⍋x←6?40]


        Eat your heart out.


         

        ghostdog74



          Specialist

          Thanked: 27
          Re: VB6 - Use a variable within a variable's name
          « Reply #16 on: August 21, 2010, 08:48:02 PM »
          APL beats the crap out of toy languages like Perl or Python.
          like real. Perl/Python are for practical purposes. APL is for children who wants to play with toys.

          Salmon Trout

          • Guest
          Re: VB6 - Use a variable within a variable's name
          « Reply #17 on: August 21, 2010, 11:37:20 PM »
          ... and he rose to the bait!


          BC_Programmer


            Mastermind
          • Typing is no substitute for thinking.
          • Thanked: 1140
            • Yes
            • Yes
            • BC-Programming.com
          • Certifications: List
          • Computer: Specs
          • Experience: Beginner
          • OS: Windows 11
          Re: VB6 - Use a variable within a variable's name
          « Reply #18 on: August 22, 2010, 09:31:52 AM »
          when i look at how its implemented in VB, i can't help but wonder why its not as simple and straightforward to use as in Perl/Python.

          First off, I'll tell you this: It is not straightforward to use in Perl (Python is good, but hardly much different from VB6). I just struggled to get this to work for nearly half an hour:

          Code: [Select]
          #!/usr/bin/perl
          %hash = ('Dog',=> 'Woof',
          'Cat'=>'Meow',
          'Cow'=>'Moo');
          print "$hash{Dog}\n";
          print "$hash{Cow}\n";


          So, easy to follow. right, I create a hash like this:
          Code: [Select]
          %hash = ('Dog',=> 'Woof',
          'Cat'=>'Meow',
          'Cow'=>'Moo');
          Ok, sensible enough. uses the % sign to access it as a hash variable, or in hash context. I don't know, I don't have a second monitor to keep it's man page up all the time. It would certainly make sense to somebody with more experience with the language.

          but to access the actual item, you need to use $.How is that straightforward? It might be straightforward to somebody familiar with it, but it's a *censored* of a pain in the *censored* to wrap ones head around when you haven't been playing with perl since you were in a playpen. In this case, I imagine that the characters aren't a sort of type-declaration characters at all, but more or less a type of access modifier that changes how the variable is accessed. in order to read a element from a hash, we need to access it in "scalar context", Usable? of course it is. But to claim this is easy and straightforward is to express how deeply polarized your opinions on the matter are.



          VB6:
          Code: [Select]
          Dim dict As ObjectSet dict = CreateObject("Scripting.Dictionary")
          dict.Add "Dog", "Woof"
          dict.Add "Cat", "Meow"
          dict.Add "Cow", "Moo"
          Msgbox dict.Item("Dog")
          Msgbox dict!Cow

          Now, here, the main annoyance is that you add each item on a separate line. This is actually fully optional.If you don't like it, just write a function to do it all at once. (later)



          Python:
          Code: [Select]
          dict = {'Dog':'Woof', 'Cat':'Meow','Cow':'Moo'}
          print dict['Dog'];
          print dict['Cow'];


          Aside from allowing the dictionary/hash elements to be defined in a single statement (which is fully possible in VB.NET since it added variable initializers) I fail to see that much difference. And since one could easily write a short function that can create a dictionary out of a parameter array in VB6:

          Code: [Select]
          Public Function CreateDictionary(ParamArray Elements())
              Dim I As Long
              Dim returnDictionary As Dictionary
              Set returnDictionary = CreateObject("Scripting.Dictionary")
              For I = LBound(Elements) To UBound(Elements) - 1 Step 2
                  returnDictionary.Add Elements(I), Elements(I + 1)
              Next I
              Set CreateDictionary = returnDictionary
          End Function

          Which allows the code to be shortened:


          Code: [Select]
          Dim dict As Object
          Set dict = CreateDictionary("Dog", "Woof", "Cat", "Meow", "Cow", "Moo")
          MsgBox dict.Item("Dog")
          MsgBox dict!Dog

          Of course turning off Option Explicit would mean that the declaration could be removed as well. Which of course would certainly fit with your own concepts on the issue (that typing is bad, it would seem).

          The C# code I presented was apparently not simple or straightforward either, because it followed the clearly flawed idea that showing steps one at a time (adding each item) was confusing and difficult. I present this modified version that uses the Collection Initializer syntax to initialize the Dictionary upon creation:

          Code: [Select]
          public static void testdictionary(){
                      //Dictionary<String,String> dicty = new String[] {"test"}.ToDictionary((w,String)=>
                      Dictionary<String, String> dicty = new Dictionary<String, String>()
                      {
                          { "Dog","Woof"},
                          { "Cat","Meow"},
                          { "Cow", "Moo"}

                      };

                      Debug.Print(dicty["Dog"]);
                      foreach (var q in (from x in dicty
                                         where x.Key.StartsWith("C", StringComparison.OrdinalIgnoreCase)
                                         select x).ToArray())
                      {
                          Debug.Print(q.Key + "=" + q.Value);
                      }
                  }

          The Collection initializer syntax can work for any class that implements IEnumerable<T>, or on Dictionaries that have more dictionaries as either their key or value (for whatever reason). I do not believe this is available in Python. (it probably is but I only did a very quick google).


          But, this is all rather redundant. The reason Python and Perl are  constantly mentioned has absolutely nothing to do with wether they are better (which is not even a metric one can measure, because it implies there are "right" ways of doing things, which is a complete lie. There is no "correct" way for a language to initialize a Dictionary, just as there is no "correct" way to Add elements to it. The only reason you continue to argue such a case is because you refuse to accept any other. For example you believe that strongly typed languages are "wrong" and should "only be used for systems programming". Why? You made no case against this, you simply stated it as a fact. You line of reasoning here seems to be that everything that python does is all you need. and the syntax is uses is the only right syntax for said feature in any language. Therefore, because Python is statically typed, that is the only way any good language could possibly represent types. The way it implements Lambda Expressions (which present a somewhat limited syntax compared to, say, C# or F#, but still powerful) is therefore the definitive way to represent it. Anything that differs from python (or perl) is therefore clunky and awkward.

          The thing is, it's not clunky and awkward to everyone else, just as not everybody will find python or perls syntaxes "simple and straightforward). You believe, for whatever reason, that Python, perl, and whatever scripting languages that you know are the one true way.

          Quoted from http://blogs.msdn.com/b/rick_schaut/archive/2004/03/04/83679.aspx with a minor change:

          Quote
          You’ll find it in American politics, and you’ll find it in the religious wars of the software industry (from vi vs. emacs to Mac vs. Wintel to open source vs. proprietary software).  The root cause is fanaticism, and that begins with the fervent belief that one is in possession of the One True Way.  We’ve all met fanatics in one way or another.  These are the people for whom there are only two ways to do things; their way and the wrong way.  We might have even exhibited signs of fanaticism ourselves.

          Now I know what you’re thinking.  We don’t kill each other in the vi vs. emacs debate, and members of Congress don’t shoot at each other from across the aisle, or at least not yet anyway; that, somehow, this is what distinguishes us from the religious fanatics who strap bombs to their bodies.  That would be a mistake.  The only reason we don’t kill over our fanaticism is because the stakes aren’t as high.  Our perceived way of life isn’t seriously threatened.

          Once fanaticism takes root, the next step is polarization.  Tim O’Reilly has written a couple of times about polarization.  In a post last January, Tim pointed to some analysis done by Valdis Krebs, using the “related books” tool on Amazon, that shows how the books that people read tend reinforce their political preconceptions.  The stark feature of Krebs’ graph is how few people read books that appeal to the other side of the map.  The distance from this kind of polarization to Limbaughesque demonization isn’t very far.

          Now, I wouldn’t write about all this, except for one thing: bloggers are in an interesting position with potential for combating fanaticism.  First, with the variety of RSS feeds out there, we have the ability to expose ourselves to continuous streams of ideas from a number of backgrounds.  If we disagree with someone, we can strive to understand what’s right about what they say, not just what’s wrong with it.  Secondly, when we write, we can write to inform rather than write to convince.  We can try to synthesize ideas from a number of camps into a more comprehensive understanding of the issues we’re discussing.

          When it comes to polarizing issues, we tend to fall into confrontational patterns of behavior.  Unfortunately, confrontational patterns of behavior very rarely, if ever, change the opinions of others.  It might have a viscerally positive feel to it, but the outcome is no different than if we had not written at all.  Most of the time, it only serves to polarize us even more.





          I was trying to dereference Null Pointers before it was cool.

          ghostdog74



            Specialist

            Thanked: 27
            Re: VB6 - Use a variable within a variable's name
            « Reply #19 on: August 22, 2010, 10:38:46 AM »
            First off, I'll tell you this: It is not straightforward to use in Perl (Python is good, but hardly much different from VB6). I just struggled to get this to work for nearly half an hour:
            that's because you are not familiar with either of them. If you are, you would not hit this problem.  Here's how simple it is to do it with Python (similarly with Perl, but I like using Python, hence this example)
            Code: [Select]
            >>> animals={}
            >>> animals["cat"]="meow"
            >>> animals["dog"]="woof"
            >>> animals["cow"]="moo"
            >>> animals
            {'dog': 'woof', 'cow': 'moo', 'cat': 'meow'}
            >>>

            Quote
            but to access the actual item, you need to use $.How is that straightforward? It might be straightforward to somebody familiar with it, but it's a *censored* of a pain in the *censored* to wrap ones head around when you haven't been playing with perl since you were in a playpen. In this case, I imagine that the characters aren't a sort of type-declaration characters at all, but more or less a type of access modifier that changes how the variable is accessed. in order to read a element from a hash, we need to access it in "scalar context", Usable? of course it is. But to claim this is easy and straightforward is to express how deeply polarized your opinions on the matter are.
            stop whining. You have to be familiar with all 3 languages to make a fair comparison. What you are describing is a minor syntax issue. When you play with Perl more, you will be accustomed to it. We are actually talking about how hashes/dictionaries in these languages differ in terms of their flexibility using them

            Now let's see a few examples of how easy it is to manipulate dictionaries in Python.
            To get keys and values
            Code: [Select]
            >>> animals.values()
            ['woof', 'moo', 'meow']
            >>> animals.keys()
            ['dog', 'cow', 'cat']

            Adding something to values of the items
            Code: [Select]
            >>> animals["dog"]+="bark"
            >>> animals
            {'dog': 'woofbark', 'cow': 'moo', 'cat': 'meow'}
            >>>

            Now try  doing that with VB.

            How about sorting a dictionary. Python comes with sort utilities inbuilt. Where can i find that in VB?
            Code: [Select]

            >>> d = {'a':2, 'b':23, 'c':5, 'd':17, 'e':1}
            >>> items = [(v, k) for k, v in d.items()]  # reverse the values and keys
            >>> items
            [(2, 'a'), (5, 'c'), (23, 'b'), (1, 'e'), (17, 'd')]
            >>> items.sort()  #sort
            >>> items.reverse()  #reverse back
            >>> items = [(k, v) for v, k in items] 
            >>> items
            [('b', 23), ('d', 17), ('c', 5), ('a', 2), ('e', 1)]  #now they are sorted.


            Note the above is old way of doing sorting by dictionary values. Python's sort now comes with added functionality which makes it even easier to do sorting. Anyhow, how about doing that in VB. ? If you do a help(dict) at the python interpreter, you can use other dictionary methods that makes manipulation of dictionaries easy. Do you find that many in VB's version?


            Finally, how about adding items from another dictionary to the the animals one?
            Code: [Select]
            >>> vegetables={"spinach":"green","carrot":"orange"}
            >>> animals.update(vegetables)
            >>> animals
            {'spinach': 'green', 'carrot': 'orange', 'dog': 'woofbark', 'cow': 'moo', 'cat': 'meow'}

            Quote
            But, this is all rather redundant. The reason Python and Perl are  constantly mentioned has absolutely nothing to do with wether they are better (which is not even a metric one can measure, because it implies there are "right" ways of doing things, which is a complete lie. There is no "correct" way for a language to initialize a Dictionary, just as there is no "correct" way to Add elements to it. The only reason you continue to argue such a case is because you refuse to accept any other. For example you believe that strongly typed languages are "wrong" and should "only be used for systems programming". Why? You made no case against this, you simply stated it as a fact. You line of reasoning here seems to be that everything that python does is all you need. and the syntax is uses is the only right syntax for said feature in any language. Therefore, because Python is statically typed, that is the only way any good language could possibly represent types. The way it implements Lambda Expressions (which present a somewhat limited syntax compared to, say, C# or F#, but still powerful) is therefore the definitive way to represent it. Anything that differs from python (or perl) is therefore clunky and awkward.
            You sure can ramble  a lot of crap. Whatever defence of your favourite language you come to, the fact still remains. Dictionary manipulation in VB still does not compare to Python's. (Or Perl).
            I do not have to convince you about anything, since you are obviously the same kind of person you say i am.

            Quote
            The thing is, it's not clunky and awkward to everyone else, just as not everybody will find python or perls syntaxes "simple and straightforward). You believe, for whatever reason, that Python, perl, and whatever scripting languages that you know are the one true way.
            speak of the devil. You swear by VB don't you?








            [/quote]
            « Last Edit: August 22, 2010, 10:50:38 AM by ghostdog74 »

            Salmon Trout

            • Guest
            Re: VB6 - Use a variable within a variable's name
            « Reply #20 on: August 22, 2010, 11:26:22 AM »
            Quote
            The distance from this kind of polarization to Limbaughesque demonization isn’t very far.

            I so agree.

            BC_Programmer


              Mastermind
            • Typing is no substitute for thinking.
            • Thanked: 1140
              • Yes
              • Yes
              • BC-Programming.com
            • Certifications: List
            • Computer: Specs
            • Experience: Beginner
            • OS: Windows 11
            Re: VB6 - Use a variable within a variable's name
            « Reply #21 on: August 22, 2010, 03:24:48 PM »
            I so agree.


            Indeed. I believe we have case and point proof above. Oh well.



            Quote
            Dictionary manipulation in VB still does not compare to Python's. (Or Perl).

            I agree. I would imagine this difference is due at least in part on the fact that VB6 was pretty much evolved from the original BASIC, at least in some form. That, as well as the fact that it is more a "give you a few tools, you work out the rest" type of mantra. Python and Perl were both designed much later, and for different purposes. (BASIC was, at it's inception, "all-purpose"... Although I'm not sure what that meant back then, clearly not very much) Perl was, as it's name implies, originally designed for creating "reports" both languages have clearly grown into something else, with VBScript being used in ASP pages and Perl and Python also finding themselves available for use online in Apache modules.

            The only difference is that dictionary support is built right into Python and perl as part of the language itself. Visual Basic had to be backwards compatible (for business reasons I guess) with QBasic and even to a point BASICA and GW-BASIC, so it didn't really have the luxury of introducing new syntaxes for things like dictionaries and collections. Besides, it didn't even support being a provider of objects (it could consume objects I VB2, I think, but I don't think they were COM based). Visual Basic 4 integrated VBA into the mix, which meant VB4 applications could use collections.

            The main problem with the collection is, as you passively pointed out using a carefully constructed python snippet, is that the collection object, for whatever reason, is immutable. Or more precisely, it's elements are. in order to "change" a value you would need to actually remove it and add it again.

            This is why the collection is best used to store a collection of objects, the objects themselves can have their properties changes and so forth without a problem from the collection. I believe this particular limitation may be because of the way the collection is implemented internally. 

            However, the Dictionary Object is almost purely the same as a collection with most of the limitations removed. for example, you provide the following:

            Code: [Select]
            animals={}
            animals["cat"]="meow"
            animals["dog"]="woof"
            animals["cow"]="moo"
            animals
            animals.values()
            ['woof', 'moo', 'meow']
            animals.keys()
            ['dog', 'cow', 'cat']
            animals["dog"]+="bark"
            animals

            You ask me to do something similar in VB. not too difficult.

            [code]

                Set Animals = CreateObject("Scripting.Dictionary")
                Animals!cat = "Meow"
                Animals!dog = "Woof"
                Animals!cow = "Moo"
                OutLn Join(Animals.Items(), ",")
                OutLn Join(Animals.Keys(), ",")
                Animals!dog = Animals!dog + "Bark"
                OutDict Animals

            Of course since the dictionary doesn't expose a way to get a string representation of itself it doesn't output those. And outln and out were both redefined by me to output to a textbox (as opposed to using Debug.Print).

            As for a sorting routine, I would just use the class I wrote for that purpose. Besides, writing a sort routine isn't that hard, and one would only need to do it once. (bear in mind particularly the different problem domains of both python and VB6, VB6 comprises of "projects" and is used for creating applications. Python consists of an interpreter interpreting a single python file that may or may not reference other python files- it makes more sense in that case to try to put things such as sorting into built-in routines.


            Quote
            You have to be familiar with all 3 languages to make a fair comparison. What you are describing is a minor syntax issue

            Funny, most of your problems with VB so far (aside from the sort one, I guess) have been "minor syntax issues". Besides, I even said as much in that paragraph:

            Quote
            It might be straightforward to somebody familiar with it




            Quote
            Finally, how about adding items from another dictionary to the the animals one?
            For VB I would simply loop through all the keys and adding each key-value pair to the new array, just as I'm sure python is doing for you automagically behind the scenes. This isn't a problem in VB when you are familiar with it.


            Quote
            If you do a help(dict) at the python interpreter, you can use other dictionary methods that makes manipulation of dictionaries easy. Do you find that many in VB's version?

            VB Classic? No. Of course not, it's based on COM which in and of itself is rather limited. and The person who developed the Scripting runtime did so in a single afternoon (Dead serious, I read that on Lieppert's blog I think) so they didn't think to add all this stuff. Besides, you can always write routines later.

            Quote
            speak of the devil. You swear by VB don't you?


            Not counting this post I had an equal number of examples in C#. C# is now my main language, pretty much for the same reasons you go with python- more versatile... stuff. Generics alone would be enough for me to avoid returning to VB6 but combine that with LINQ and the gigantic class library and I may as well tear down the road back. But I still need to maintain my old VB6 applications.

            I notice how you specifically pointed out VB6. VB.NET and C# have access to the framework and therefor have direct access to the many number of data structures available in the class library, such as List<T>,SortedList<T>,Dictionary<TKey,TValue>,Stack<T>,Queue<T> and a number of others. No Tree structures for some reason though.[/code]
            I was trying to dereference Null Pointers before it was cool.

            ghostdog74



              Specialist

              Thanked: 27
              Re: VB6 - Use a variable within a variable's name
              « Reply #22 on: August 22, 2010, 06:27:52 PM »
              As for a sorting routine, I would just use the class I wrote for that purpose. Besides, writing a sort routine isn't that hard, and one would only need to do it once. (bear in mind particularly the different problem domains of both python and VB6, VB6 comprises of "projects" and is used for creating applications. Python consists of an interpreter interpreting a single python file that may or may not reference other python files- it makes more sense in that case to try to put things such as sorting into built-in routines.
              if you have to write your own subroutines, then how is it easy as compared to inbuilt subroutines ? Are you going to distribute your subroutine so that every body who uses VB can use it ?

              Quote
              For VB I would simply loop through all the keys and adding each key-value pair to the new array, just as I'm sure python is doing for you automagically behind the scenes. This isn't a problem in VB when you are familiar with it.
              but its still not easier than Python's like i said. You need to create a new array, loop through the items etc. I am sure Python also does that behind the scene, but I am spared from doing that myself.