diff options
Diffstat (limited to 'tests/objects.lua')
-rw-r--r-- | tests/objects.lua | 76 |
1 files changed, 76 insertions, 0 deletions
diff --git a/tests/objects.lua b/tests/objects.lua new file mode 100644 index 0000000..8f56a5f --- /dev/null +++ b/tests/objects.lua | |||
@@ -0,0 +1,76 @@ | |||
1 | -- | ||
2 | -- OBJECTS.LUA | ||
3 | -- | ||
4 | -- Tests that objects (metatables) can be passed between lanes. | ||
5 | -- | ||
6 | |||
7 | require "lanes" | ||
8 | |||
9 | local linda= lanes.linda() | ||
10 | |||
11 | local start_lane= lanes.gen( "io", | ||
12 | function( obj1 ) | ||
13 | |||
14 | assert( obj1.v ) | ||
15 | assert( obj1.print ) | ||
16 | |||
17 | assert( obj1 ) | ||
18 | local mt1= getmetatable(obj1) | ||
19 | assert(mt1) | ||
20 | |||
21 | local obj2= linda:receive("") | ||
22 | assert( obj2 ) | ||
23 | local mt2= getmetatable(obj2) | ||
24 | assert(mt2) | ||
25 | assert( mt1==mt2 ) | ||
26 | |||
27 | local v= obj1:print() | ||
28 | assert( v=="aaa" ) | ||
29 | |||
30 | v= obj2:print() | ||
31 | assert( v=="bbb" ) | ||
32 | |||
33 | return true | ||
34 | end | ||
35 | ) | ||
36 | |||
37 | |||
38 | local WR= function(str) | ||
39 | io.stderr:write( tostring(str).."\n") | ||
40 | end | ||
41 | |||
42 | |||
43 | -- Lanes identifies metatables and copies them only once per each lane. | ||
44 | -- | ||
45 | -- Having methods in the metatable will make passing objects lighter than | ||
46 | -- having the methods 'fixed' in the object tables themselves. | ||
47 | -- | ||
48 | local o_mt= { | ||
49 | __index= function( me, key ) | ||
50 | if key=="print" then | ||
51 | return function() WR(me.v); return me.v end | ||
52 | end | ||
53 | end | ||
54 | } | ||
55 | |||
56 | local function obj_gen(v) | ||
57 | local o= { v=v } | ||
58 | setmetatable( o, o_mt ) | ||
59 | return o | ||
60 | end | ||
61 | |||
62 | local a= obj_gen("aaa") | ||
63 | local b= obj_gen("bbb") | ||
64 | |||
65 | assert( a and b ) | ||
66 | |||
67 | local mt_a= getmetatable(a) | ||
68 | local mt_b= getmetatable(b) | ||
69 | assert( mt_a and mt_a==mt_b ) | ||
70 | |||
71 | local h= start_lane(a) -- 1st object as parameter | ||
72 | |||
73 | linda:send( "", b ) -- 2nd object via Linda | ||
74 | |||
75 | assert( h[1]==true ) -- wait for return | ||
76 | |||