Please help. use loop to access class variables

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
oldbrother
Posts: 273
Joined: 23 Oct 2013, 05:08

Please help. use loop to access class variables

19 Jul 2017, 12:07

Error message got from my code:

Line Text : .X%A_Index%
Error: Ambiguous or invalid use of "."

How to make the loop work? The real class of my code has many variables. I need to use the loop.

Test code:

Code: Select all

T := New TestClass(1,2,3,4,5)
T.Test()

Class TestClass
{
	_New(X1,X2,X3,X4,X5)
	{
		This.X1 := X1
		This.X2 := X2
		This.X3 := X3
		This.X4 := X4
		This.X5 := X5
	}
	
	Test()
	{
		Loop 5
		 Msgbox % This.X%A_Index%
	}
}
kon
Posts: 1756
Joined: 29 Sep 2013, 17:11

Re: Please help. use loop to access class variables

19 Jul 2017, 12:31

Try this:

Code: Select all

Class TestClass
{
    __New(X1,X2,X3,X4,X5)  ; <-- Changed. Needs to be '__New' not '_New'
    {
        This.X1 := X1
        This.X2 := X2
        This.X3 := X3
        This.X4 := X4
        This.X5 := X5
    }
    
    Test()
    {
        Loop 5
            Msgbox % This["X" . A_Index]
    }
}
Or:

Code: Select all

Class TestClass
{
    __New(X1,X2,X3,X4,X5)
    {
        This["X", 1] := X1
        This["X", 2] := X2
        This["X", 3] := X3
        This["X", 4] := X4
        This["X", 5] := X5
    }
    
    Test()
    {
        for i, val in This.X
            Msgbox % val
    }
}
Or:

Code: Select all

Class TestClass
{
    __New(Params*)
    {
        for i, val in Params
            This["X", i] := val
    }
    
    Test()
    {
        for i, val in This.X
            Msgbox % val
    }
}
HTH :)
If anything needs further explanation, just ask.
User avatar
oldbrother
Posts: 273
Joined: 23 Oct 2013, 05:08

Re: Please help. use loop to access class variables

19 Jul 2017, 13:34

Thank you Kon!

Is there any reason that lexikos didn't make the syntax of my code working? should I add it to the wish list?
kon
Posts: 1756
Joined: 29 Sep 2013, 17:11

Re: Please help. use loop to access class variables

19 Jul 2017, 14:43

oldbrother wrote:Is there any reason that lexikos didn't make the syntax of my code working?
I don't know, but I suspect some of the reasons are:
- There is already a way to do this. No need to add another way to do the same thing.
- It is not consistent with other languages.
- (Guessing) There are probably some technical reasons relating to how expressions are parsed.
oldbrother wrote:should I add it to the wish list?
:arrow: https://autohotkey.com/boards/viewtopic.php?t=4674
I don't think it should be added.

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Google [Bot] and 391 guests