value.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include "value.h"
  2. #include "memory.h"
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include "object.h"
  6. void initValueArray(ValueArray *array) {
  7. array->values = NULL;
  8. array->capacity = 0;
  9. array->count = 0;
  10. };
  11. void writeValueArray(ValueArray *array, Value value) {
  12. if (array->capacity < array->count + 1) {
  13. int oldCapacity = array->capacity;
  14. array->capacity = GROW_CAPACITY(oldCapacity);
  15. array->values = GROW_ARRAY(Value, array->values, oldCapacity, array->capacity);
  16. }
  17. array->values[array->count] = value;
  18. array->count++;
  19. };
  20. void freeValueArray(ValueArray *array) {
  21. FREE_ARRAY(Value, array->values, array->capacity);
  22. initValueArray(array);
  23. }
  24. void printValue(Value value) {
  25. switch (value.type) {
  26. case VAL_BOOL:
  27. printf(AS_BOOL(value) ? "true" : "false");
  28. break;
  29. case VAL_NIL:
  30. printf("nil");
  31. break;
  32. case VAL_NUMBER:
  33. printf("%g", AS_NUMBER(value));
  34. break;
  35. case VAL_OBJ:
  36. printObject(value);
  37. break;
  38. }
  39. }
  40. bool valuesEqual(Value a, Value b) {
  41. if (a.type != b.type) return false;
  42. switch (a.type) {
  43. case VAL_BOOL: return AS_BOOL(a) == AS_BOOL(b);
  44. case VAL_NIL: return true;
  45. case VAL_NUMBER: return AS_NUMBER(a) == AS_NUMBER(b);
  46. case VAL_OBJ: return AS_OBJ(a) == AS_OBJ(b);
  47. default: return false;
  48. }
  49. }