Page 1 of 1

Tables with named indices

Posted: Tue Apr 03, 2018 7:32 pm
by djrikki

Code: Select all

    	obj = {
    		id 			 = Layout:GetNewID(0),
    		class  	   = "button",
    		icon  	    = #AISSICON,
	    	name	  	 = base:ucFirst(obj.class)
    		toggle		 = False,
    		shorthelp 	= "button-shorthelp",
	    	node  		 = base:GetRightChars(obj.id,"-") .. "-node",
		    ckey	      = "",
		    contextmenu  = 0,
		    weight		 = 100,
		    disabled 	 = False,
		    hidden		 = False,    		
    	}
When I run the above code it rightly complains that 'name' and 'node' cannot be assigned because 'class' and 'id' have not yet been initalised.

Having already tried the self or even this keyword I wonder if there is any other way to declare 'name' and 'node' conveniently inside the obj table? I suspect the answer is no meaning I will have to do the assignment outside the table.

Re: Tables with named indices

Posted: Wed Apr 04, 2018 9:22 pm
by airsoftsoftwair
Sorry, that's not possible. When initializing a table using the {} constructor you mustn't make any assumptions about the order of initialization anyway, e.g.

Code: Select all

t = {x = func(0), y = func(1)}
You cannot rely on func(0) being called before func(1).

Re: Tables with named indices

Posted: Thu Apr 05, 2018 12:21 am
by Bugala
You could consider using class approach, although it is a bit different way of doing it. Hollywood (=LUA) doesnt actually have Class at all, but it can emulate it just fine.

One way to do it (not working code since it is missing func1 and func2):

Code: Select all

prototype_Class = {}

Function prototype_Class:New()
	Local d = {}
  
	SetMetaTable(d, self)
	self.__index = self
	
        d.varA = Func1()
        d.varB = Func2()

	Return(d)
EndFunction

NotTableButClass = function prototype_Class:New()

debugprint(NotTableButClass.varA)
And now you can rely on Func1() being executed before Func2()