arrays - VBScript nested class data structure -
my problem can illustrated in following example code, sets data array of friends, each of can have several phone numbers:
class clsphoneno dim strtype dim strnumber end class class clsperson dim strname dim aclsphoneno() end class dim clsfriends() redim clsfriends(3) set clsfriend(0) = new person clsfriend(0).strname = "fred" set clsfriends(0).aclsphoneno(0) = new clsphoneno redim clsfriend(0).aclsphoneno(2) set clsfriend(0).aclsphoneno(0).strtype = "home" set clsfriend(0).aclsphoneno(0) = "01234567890" set clsfriend(0).aclsphoneno(1).strtype = "work" set clsfriend(0).aclsphoneno(1) = "09876543210" however, vbscript says
microsoft vbscript compilation error: expected end of statement before . on second redim statement
i need have aclsphoneno element variable length code isn't address book, simple example demonstrating issue.
any ideas?
arrays wrong data structure solve problem. weapon of choice in other languages, not in vbscript, notoriously inflexible.
consider using dictionaries instead. , drop hungarian.
dim phonebook: set phonebook = new objectlist phonebook.append(new person) .name = "fred" .addphoneno "home", "01234567890" .addphoneno "work", "09876543210" end dim pers: set pers = phonebook.item(1) each id in pers.phonenos.list set num = pers.phonenos.list(id) wscript.echo pers.name & " #" & id & ": " & _ num.number & " (" & num.label & ")" next ' ------------------------------------------------------ class objectlist public list sub class_initialize() set list = createobject("scripting.dictionary") end sub sub class_terminate() set list = nothing end sub function append(anything) list.add cstr(list.count + 1), set append = end function function item(id) if list.exists(cstr(id)) set item = list(cstr(id)) else set item = nothing end if end function end class ' ------------------------------------------------------ class phoneno public label public number end class ' ------------------------------------------------------ class person public name public phonenos sub class_initialize() set phonenos = new objectlist end sub function addphoneno(label, number) set addphoneno = new phoneno phonenos.append(addphoneno) .label = label .number = number end end function end class note made use of few vb features here
- you can use functions , classes before defined in script, put plumbing @ bottom.
- you can have
public,privateclass variables - classes have
initiate,terminateevent can react to - function names variable declarations. no need declare temporary return variable in function, can use function name that.
- the
withblock can save temporary variable well. - even though dictionary comparatively convenient, can still benefit convenience wrapper, created one.
Comments
Post a Comment