#include #include #include GroundValue boxGet(GroundScope* scope, List args) { GroundVariable* varptr = groundFindVariable(scope, "ptr"); GroundValue* ptr = (GroundValue*)varptr->value.data.intVal; if (ptr == NULL) { ERROR("No value in box", "ValueError"); } return *ptr; } GroundValue boxSet(GroundScope* scope, List args) { GroundVariable* varptr = groundFindVariable(scope, "ptr"); GroundValue** ptr = (GroundValue**)&varptr->value.data.intVal; if (*ptr == NULL) { *ptr = malloc(sizeof(GroundValue)); if (*ptr == NULL) { ERROR("Could not allocate memory", "AllocError"); } } **ptr = args.values[0]; return groundCreateValue(NONE); } GroundValue boxFree(GroundScope* scope, List args) { GroundVariable* varptr = groundFindVariable(scope, "ptr"); GroundValue** ptr = (GroundValue**)&varptr->value.data.intVal; if (*ptr != NULL) { free(*ptr); *ptr = 0; } return groundCreateValue(NONE); } void ground_init(GroundScope* scope) { GroundStruct boxStruct = groundCreateStruct(); groundAddFieldToStruct(&boxStruct, "ptr", groundCreateValue(INT, 0)); groundAddFunctionToStruct(&boxStruct, "get", boxGet, ANY, 0); groundAddFunctionToStruct(&boxStruct, "set", boxSet, ANY, 1, ANY, "item"); groundAddFunctionToStruct(&boxStruct, "free", boxFree, ANY, 0); groundAddValueToScope(scope, "_box", groundCreateValue(STRUCTVAL, boxStruct)); }