Dynamic class property creation and access

I’m working to create a localization system for my software.

I plan to implement this using simple text files - each line begins with a variable name, then the text it should contain in quotations, e.g.

powerScreen “Make sure your laptop is plugged in”
session "Session Number: "

The plan is to read in these strings, split them to get the variable name and the corresponding text, then store them in a class.

To do this, I need to be able to create new class properties dynamically, and access them dynamically. My current attempt is along the lines of:

		var localeFile = File.read("locale/" + config.language + ".txt", false); 
			lineNum = 0;
			try 
			{
				while ( true )	
				{
					var str = localeFile.readLine();
					var r = ~/["]+/g;
					var ans = r.split(str); //split using | symbol
					trace(ans[0] + " | " + ans[1]);
					
					locale.(ans[0]) = ans[1];
					
					lineNum++; //increment at end (note that first line contains headers)
				}			
			}
			catch (ex:haxe.io.Eof)
			{}

Could I get some assistance in determining how to make this happen (or to let me know if it is even possible?)?

One solution is to store your data in JSON format, and then use haxe.Json.parse to have them in a Dynamic typed object.

It’s perfectly possible with Haxe. :smiley:

You can build & modify class fields on compile-time with macro.

You can also update anonymous structures / String maps on runtime.

1 Like