Skip to content

Instantly share code, notes, and snippets.

@soasme
Last active April 21, 2021 04:01
Show Gist options
  • Save soasme/7ede641156d2a7bee4b8bec2e87c2197 to your computer and use it in GitHub Desktop.
Save soasme/7ede641156d2a7bee4b8bec2e87c2197 to your computer and use it in GitHub Desktop.
Attrs example.
// https://gist.github.com/soasme/7ede641156d2a7bee4b8bec2e87c2197
#include <stdio.h>
#include "attrs.h"
AttrsError CoordinatePrint(AttrsArgs args) {
AttrsRef self = AttrsGetSelf(args);
FILE* f = AttrsGetPtrArg(args, "f", FILE*); // Or, FILE* f = (FILE*) AttrsGetPtr (AttrsGetArg(args, "f"));
int x = AttrsGetInt(self, "x"); // Or, int x = AttrsGetInt(args, "self.x");
int y = AttrsGetInt(self, "y"); // Or, int x = AttrsGetInt(args, "self.y");
fprintf(f, "Coordinate(%u,%u)", x, y);
}
int main(int argc, char* argv[]) {
// call before any Attrs function.
AttrsInit();
// make a class
AttrsNewClass("Coordinate",
"x = type: int, default: 0;"
"y = type: int, default: 0;"
"r = type: int, default: 1, private: true;"
"o = type: Coordinate, private: true;"
"def Print(f: File);"
)
// bind method
AttrsDef("Coordinate:Print(f)", CoordinatePrint);
// check a class.
bool has_coordinate = AttrsGetFields("Coordinate");
// inspect all fields.
AttrsField* fields = AttrsGetFields("Coordinate");
// check a field.
bool has_a = AttrsHasField("Coordinate", "a");
// inspect a field.
AttrsField field = AttrsGetField("Coordinate", "a");
// create a new object.
AttrsRef c = AttrsCall("Coordinate:New(a, b)", 1, 2);
// call a method.
AttrsCall("Coordinate:Print(f)", c, AttrsBuiltin("stdout"));
// call when Attrs is no longer used.
AttrsDestroy();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment