Tables with named indices

Discuss any general programming issues here
Post Reply
djrikki
Posts: 682
Joined: Wed Apr 06, 2011 12:26 am

Tables with named indices

Post by djrikki » Tue Apr 03, 2018 7:32 pm

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.
Evolve - Rapid GUI Development tool for MUI Royale and RapaGUI
http://myevolve.wordpress.com

User avatar
airsoftsoftwair
Posts: 2537
Joined: Fri Feb 12, 2010 3:33 pm
Location: Germany
Contact:

Re: Tables with named indices

Post by airsoftsoftwair » Wed Apr 04, 2018 9:22 pm

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).

Bugala
Posts: 689
Joined: Sun Feb 14, 2010 8:11 pm

Re: Tables with named indices

Post by Bugala » Thu Apr 05, 2018 12:21 am

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()

Post Reply