haxe add new key to object with variable -


i have defined object data use store various bit of data use code. want insert new room @ runtime. eg new key "r200" variable, have not been able far.

 static public var data =   {     room: {         "r100": {monstersleft: 2 }     }  }   // need add the object data : // reference like:  var newroom = "r200"; ???? data[newroom ].monstersleft = 5;  trace(data.r200.monstersleft) 

haxe's anonymous structures nothing more untyped, organised collections of data. structure immutable once set , property values can modified. array access (bracket notation) not defined on anonymous structures - instead, dot notation used.

because of untyped (dynamic) nature of anonymous structures, can have negative impact on performance when compiling static targets.

it recommended organise , type anonymous structures use of typedefs , typedef extensions. ensures type safety , helps compilation server pick on typing mistakes on-the-go.

to on point, you're trying best achieved use of maps , typedefs. maps let store proper key-value pairs - both through methods , bracket notation - , typedefs let type data structure, ensuring type safety.

with in mind, code snippet recreated follows:

class test {     static var data : map<string, room> = new map<string, room>();      static function main() {         data["r100"] = { monstercount: 5 };         data["r200"] = { monstercount: 10 };          trace(data["r100"].monstercount);         trace(data["r200"].monstercount);     } }  typedef room = {     var monstercount : int; } 

room type described { "monstercount": (int) } data structure, , mapped string keys denote room id.

the map api lets set , remove key-value pairs map, iterate on keys / values, , more. make sure check api docs more information.


edit (2016-07-26)

the answer provided lordkryss valid. however, there 2 main reasons why didn't bring reflection.

  • reflection runtime feature, use unnecessarily complicate code , not offer desired syntax.
  • reflection can costly , unpredictable on different targets.

generally should fare better reflection on dynamic rather static targets. keep in mind when developing project , deciding target platform be.

i recommend looking generated sources better understand impact of reflection. can use official try.haxe.org sandbox see haxe 3.2.0 generated javascript source code. there unofficial sandbox lets see haxe 3.3.0-rc.1 generated javascript source code.

personally, i not think reflection acceptable solution problem. see problem 1 of finding appropriate data structure represent data. reflection has use, not recommend in case.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -