Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local class = {};
- local class_mt = {__index = class};
- local class_ref = setmetatable({}, {__mode = "k"});
- function class.new(x, y)
- local self = {};
- self.x = x;
- self.y = y;
- self = setmetatable(self, class_mt);
- class_ref[self] = {};
- class_ref[self].magnitude = math.sqrt(x*x + y*y);
- return self;
- end
- function class:getMagnitude()
- return class_ref[self].magnitude;
- end
- local a = class.new(1, 2, 3);
- local b = class.new(-3, 7, 32/4*(-8));
- print(a.x, b.y);
- print(a:getMagnitude());
- for _, i in next, class_ref do
- for k, v in next, _ do
- print("Round 1: ",k,"; Value: ",v);
- end
- for k, v in next, i do
- print("Round 2: ",k,"; Value: ", v);
- end
- end
- -- class_ref = {
- -- {y = 2, x = 1} = {magnitude = math.sqrt(5)},
- -- {y = 7, x = -3} = {magnitude = math.sqrt(58)}
- -- }
- -- both entries class_ref[a] and class_ref[b] exist
- for k, v in next, class_ref do
- print(k, v);
- end
- b = nil;
- -- note: b was the only reference to this object outside a weak table
- wait(1); -- garbage collection
- -- only entry class_ref[a] exists
- for k, v in next, class_ref do print(k, v); end
Add Comment
Please, Sign In to add comment