Page 1 of 1

Create nested class instance from variable

Posted: 02 Dec 2020, 06:55
by hoppfrosch
Hello everybody

I want to create an instance of a nested class. The class name is given through a variable.

Code: Select all

class a {}
o1 := a.new()    ; Works
cn := "a"
o2 :=  %cn%.new() ; Works
class b {
	class c {}
}
o3 := b.c.new() ; Works
cn := "b.c"
o4 :=  %cn%.new() ; !!!! Fails! "Variable name contains an illegal character" 
ExitApp
Generation of o4 fails as there is a dot in my variable name. How can I generate an instance of a nested class from a variable containing a dot?

Using Autohotkey V2.0.a122

Thanks in advance
hoppfrosch

Re: Create nested class instance from variable  Topic is solved

Posted: 02 Dec 2020, 07:32
by swagfag
u have to parse the string and iterate through the classes until u get to the one u wish to new up

Code: Select all

#Requires AutoHotkey v2.0-a122-f595abc2

class b {
	class c {}
}

cn := "b.c"
o4 :=  newFromString(cn)

newFromString(str, Args*) {
	ClassNames := StrSplit(str, '.')
	C := %ClassNames.RemoveAt(1)%

	for name in ClassNames
		C := C.%name%

	return C.New(Args*)
}

Re: Create nested class instance from variable

Posted: 03 Dec 2020, 00:22
by hoppfrosch
:thumbup: Great-works exactly the way I desired.

Just to understand it:

Code: Select all

class a{ }
C := a
Obviously classnames ("a") cannot be used as variable name anymore. Haven't noticed this yet.
Where can I find documentation about this? Don*t have even an idea where to search for ... :crazy:

Re: Create nested class instance from variable

Posted: 03 Dec 2020, 04:58
by swagfag
C is just a variable name i chose cause i couldnt come up with anything better. u should probably rename it to something more meaningful. it doesnt refer to the class class c {}(in ur code).
Where can I find documentation about this? Don*t have even an idea where to search for ...
u cant search for it, specifically. ud have to read the whole docs and make mental notes of where things are. or track the changelog/commit messages.
Objects->Classes wrote:When the script is loaded, this constructs a Class object and stores it in a super-global constant (read-only variable) with the name ClassName.

Re: Create nested class instance from variable

Posted: 03 Dec 2020, 07:36
by hoppfrosch
As a non-english native you have to read this, make mental notes AND understand all the intrisic details of those sentences :lol:

Re: Create nested class instance from variable

Posted: 11 Dec 2020, 10:05
by madsounds
No, you can't evaluate any code using %%. i.e. dot operator. Only variable names.