Tables with named indices

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

Tables with named indices

Post 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(,"-") .. "-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

User avatar
Posts: 4441
Joined: Fri Feb 12, 2010 2:33 pm
Location: Germany

Re: Tables with named indices

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

Posts: 967
Joined: Sun Feb 14, 2010 7:11 pm

Re: Tables with named indices

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


NotTableButClass = function prototype_Class:New()

And now you can rely on Func1() being executed before Func2()

Post Reply