IHATEMICROWAVEOVEN

experimenting

Apr 15th, 2022 (edited)
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. local class = {};
  2. local class_mt = {__index = class};
  3. local class_ref = setmetatable({}, {__mode = "k"});
  4.  
  5. function class.new(x, y)
  6. local self = {};
  7. self.x = x;
  8. self.y = y;
  9. self = setmetatable(self, class_mt);
  10. class_ref[self] = {};
  11. class_ref[self].magnitude = math.sqrt(x*x + y*y);
  12. return self;
  13. end
  14.  
  15. function class:getMagnitude()
  16. return class_ref[self].magnitude;
  17. end
  18.  
  19. local a = class.new(1, 2, 3);
  20. local b = class.new(-3, 7, 32/4*(-8));
  21.  
  22. print(a.x, b.y);
  23. print(a:getMagnitude());
  24.  
  25. for _, i in next, class_ref do
  26. for k, v in next, _ do
  27. print("Round 1: ",k,"; Value: ",v);
  28. end
  29. for k, v in next, i do
  30. print("Round 2: ",k,"; Value: ", v);
  31. end
  32. end
  33.  
  34.  
  35. -- class_ref = {
  36. -- {y = 2, x = 1} = {magnitude = math.sqrt(5)},
  37. -- {y = 7, x = -3} = {magnitude = math.sqrt(58)}
  38. -- }
  39.  
  40.  
  41.  
  42.  
  43.  
  44. -- both entries class_ref[a] and class_ref[b] exist
  45. for k, v in next, class_ref do
  46. print(k, v);
  47. end
  48.  
  49. b = nil;
  50. -- note: b was the only reference to this object outside a weak table
  51.  
  52. wait(1); -- garbage collection
  53.  
  54. -- only entry class_ref[a] exists
  55. for k, v in next, class_ref do print(k, v); end
  56.  
Add Comment
Please, Sign In to add comment