Skip to content

Instantly share code, notes, and snippets.

@back2dos
Created March 27, 2016 18:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save back2dos/0f0bdf8fc114464ab329 to your computer and use it in GitHub Desktop.
Save back2dos/0f0bdf8fc114464ab329 to your computer and use it in GitHub Desktop.
Macro based entity.
package;
import haxe.macro.Expr;
#if macro
using haxe.macro.Context;
using haxe.macro.Tools;
#end
class Entity {
#if macro
static var counter = 0;
static var mapping = new Map();
static function getId(type:haxe.macro.Type) {
var name = type.toString();
if (!mapping.exists(name))
mapping[name] = counter++;
return mapping[name];
}
#end
var registry:Map<Int, Dynamic>;
public function new() {
this.registry = new Map();
}
macro public function add(ethis:Expr, component:Expr) {
var id = getId(component.typeof());
return macro @:pos(component.pos) {
var entity = $ethis,
component = $component;
@:privateAccess (entity.registry[$v{id}] = component);
entity;
};
}
macro public function get<T>(ethis:Expr, component:ExprOf<Class<T>>):ExprOf<T> {
var type = (macro @:pos(component.pos) {
function ___<T>(c:Class<T>):T return null;
___($component);
}).typeof();
var id = getId(type),
ct = type.toComplexType();
return macro @:pos(component.pos) (@:privateAccess ($ethis).registry[$v{id}] : $ct);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment