COMMUNITY

Trying to access extern object

haxe-js

(Alvaro Carvajal) #1

Hello all.

I am trying to access a NodeJS object (Game.spawns) this is a hash map of the class SpawnStructure.

Basically on node I am able to do the following console.log(Game.spawns["Spawn1"].hits) however on my Haxe code, after declaring some extern classes I keep getting errors:

Main.hx

class Main {
	public static function main() {

	}

	@:expose("loop")
	public static function loop() {
		trace(Game.time);
		trace("Hello World lol");
		
	}
}

Game.hx

package;

extern class Game {
	static var time : Int; 
	static var spawns : Map<String, StructureSpawn>;
}

Structure.hx

package;

extern class Structure {
	static var hits : Int;
	static var hitsMax : Int;
	static var id :  String;
}

StructureSpawn.hx

package;

extern class StructureSpawn extends Structure {
	static var energy : Int;
	static var energyCapacity : Int;
}

If I try the following on my loop function: trace(Game.spawns["Spawn1"]) I will get the following error:

TypeError: Cannot read property ‘Spawn1’ of undefined

This is the generated code:

// Generated by Haxe 3.4.7
(function ($hx_exports) { "use strict";
var Main = function() { };
Main.main = function() {
};
Main.loop = $hx_exports["loop"] = function() {
	console.log(Game.time);
	console.log("Hello World lol");
	var _this = Game.spawns;
	console.log(__map_reserved["Spawn1"] != null ? _this.getReserved("Spawn1") : _this.h["Spawn1"]);
};
var haxe_IMap = function() { };
var haxe_ds_StringMap = function() {
	this.h = { };
};
haxe_ds_StringMap.__interfaces__ = [haxe_IMap];
haxe_ds_StringMap.prototype = {
	getReserved: function(key) {
		if(this.rh == null) {
			return null;
		} else {
			return this.rh["$" + key];
		}
	}
};
var __map_reserved = {};
Main.main();
})(typeof exports != "undefined" ? exports : typeof window != "undefined" ? window : typeof self != "undefined" ? self : this);

Am I missing something? Thanks


(Kevin Leung) #2

Is Game.spawns really a Haxe Map? I doubt that because it is extern.

If it is a plain JS object then you may try:

static var spawns : haxe.DynamicAccess<StructureSpawn>;