1 The `__delete__` metamethod is consulted when a property is deleted which is 2 not an own property of the object. It is invoked as a method on the instance, 3 with the key as single argument. A truthy return value means "deleted". 4 5 -- Testcase -- 6 {% 7 let log = []; 8 9 let o = proto({ own: 1 }, { 10 __delete__(key) { 11 push(log, key); 12 return key == "virtual"; 13 } 14 }); 15 16 print(delete o.virtual, " ", delete o.other, " ", delete o.own, " ", o.own === null, "\n"); 17 print(log, " 18 "); 19 %} 20 -- End -- 21 22 -- Expect stdout -- 23 true false true true 24 [ "virtual", "other" ] 25 -- End -- 26 27 Deleting an own property does not consult the metamethod. 28 29 -- Testcase -- 30 {% 31 let o = proto({ own: 1 }, { 32 __delete__(key) { 33 die("intercepted " + key); 34 } 35 }); 36 37 print(delete o.own, "\n"); 38 %} 39 -- End -- 40 41 -- Expect stdout -- 42 true 43 -- End -- 44 45 A `__delete__` which is itself an object (rather than a function) delegates the 46 delete to that object. 47 48 -- Testcase -- 49 {% 50 let target = { a: 1, b: 2 }; 51 let o = proto({}, { __delete__: target }); 52 53 print(delete o.a, " ", delete o.c, "\n"); 54 print(target.a === null, " ", target.b, "\n"); 55 %} 56 -- End -- 57 58 -- Expect stdout -- 59 true false 60 true 2 61 -- End -- 62 63 A delegated delete re-dispatches the target's own metamethods. 64 65 -- Testcase -- 66 {% 67 let store = { x: 1 }; 68 let log = []; 69 let mid = proto({}, { 70 __delete__(key) { 71 push(log, key); 72 return delete store[key]; 73 } 74 }); 75 let o = proto({}, { __delete__: mid }); 76 77 print(delete o.x, " ", delete o.missing, "\n"); 78 print(store.x === null, " ", log, "\n"); 79 %} 80 -- End -- 81 82 -- Expect stdout -- 83 true false 84 true [ "x", "missing" ] 85 -- End --
This page was automatically generated by LXR 0.3.1. • OpenWrt