24: Mixins - royal-lang/rl GitHub Wiki
Mixins can be used to mix-in a piece of code directly at compile-time either using a string or a template.
Mixins are alternatives to manipulating the AST directly. AST manipulation can be done during compile-time with CTFE.
Prior to a mixin statement the module of the mixin statement must be syntactic valid which means you cannot use mixins to create obscure syntaxes etc.
mixin(MIXIN_STRING);
mixin(MIXIN_TEMPLATE);
mixin template NAME(TEMPLATE_PARAMS)
{
CODE_TO_MIXIN
}
Example:
fn main()
{
mixin("var x = 10;");
mixin("var y = x * 10;");
mixin("var result = x + y");
mixin("writeln(result);");
}
Result:
fn main()
{
var x = 10;
var y = x * 10;
var result = x + y;
writeln(result);
}
mixin template Header
{
uint size;
uint id;
}
struct DataPacket
{
mixin(Header);
ushort magic;
}
var DataPacket packet;
packet.size = 10;
packet.id = 2002;
packet.magic = 3;