Skip to content

Instantly share code, notes, and snippets.

@Dvergar
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save Dvergar/37b207268723b914fb6a to your computer and use it in GitHub Desktop.

Select an option

Save Dvergar/37b207268723b914fb6a to your computer and use it in GitHub Desktop.
Build Types (components) from a YAML file
import haxe.macro.Expr;
import haxe.macro.Context;
import yaml.Yaml;
import yaml.Parser;
import yaml.util.ObjectMap;
class BuildComponents {
macro static public function build():Array<Field> {
var data:AnyObjectMap = Yaml.read("components.yaml");
var fields = Context.getBuildFields();
var pos = Context.currentPos();
for(componentName in data.keys()) {
var newArgs:Array<haxe.macro.FunctionArg> = new Array();
var compFields:Array<Field> = new Array();
var component:AnyObjectMap = data.get(componentName);
var block:Array<haxe.macro.Expr> = [];
for(f in component.keys()) {
var type = component.get(f);
var tpath = TPath({name: type, pack: [], params: []});
newArgs.push({name:"_" + f, type:tpath, opt:false});
compFields.push({kind: FVar(tpath, null),
meta: [],
name: f,
pos: pos,
access: [APublic]});
block.push(macro $i{f} = $i{"_" + f});
}
compFields.push({kind: FFun({args: newArgs,
expr: {expr: EBlock(block),
pos: pos},
params: [],
ret: null}),
name: "new",
pos: pos,
access: [APublic]});
Context.defineType({
pos: pos,
params: [],
pack: [],
name: componentName,
fields: compFields,
isExtern: false,
meta: [],
kind: TDClass(null, [], false)});
}
return fields;
}
}
PositionComponent:
x: Int
y: Int
DescriptionComponent:
name: String
text: String
import BuildComponents;
@:build(BuildComponents.build())
class Main {
public function new() {
var pos = new PositionComponent(100, 200);
trace(pos.x);
trace(pos.y);
var weaponDescr = new DescriptionComponent("Sword", "Very pain!");
trace(weaponDescr.name);
trace(weaponDescr.text);
}
public static function main() {
new Main();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment