coroutine.lua 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. -- $Id: testes/coroutine.lua $
  2. -- See Copyright Notice in file all.lua
  3. print "testing coroutines"
  4. local debug = require'debug'
  5. local f
  6. local main, ismain = coroutine.running()
  7. assert(type(main) == "thread" and ismain)
  8. assert(not coroutine.resume(main))
  9. assert(not coroutine.isyieldable(main) and not coroutine.isyieldable())
  10. assert(not pcall(coroutine.yield))
  11. -- trivial errors
  12. assert(not pcall(coroutine.resume, 0))
  13. assert(not pcall(coroutine.status, 0))
  14. -- tests for multiple yield/resume arguments
  15. local function eqtab (t1, t2)
  16. assert(#t1 == #t2)
  17. for i = 1, #t1 do
  18. local v = t1[i]
  19. assert(t2[i] == v)
  20. end
  21. end
  22. _G.x = nil -- declare x
  23. function foo (a, ...)
  24. local x, y = coroutine.running()
  25. assert(x == f and y == false)
  26. -- next call should not corrupt coroutine (but must fail,
  27. -- as it attempts to resume the running coroutine)
  28. assert(coroutine.resume(f) == false)
  29. assert(coroutine.status(f) == "running")
  30. local arg = {...}
  31. assert(coroutine.isyieldable(x))
  32. for i=1,#arg do
  33. _G.x = {coroutine.yield(table.unpack(arg[i]))}
  34. end
  35. return table.unpack(a)
  36. end
  37. f = coroutine.create(foo)
  38. assert(coroutine.isyieldable(f))
  39. assert(type(f) == "thread" and coroutine.status(f) == "suspended")
  40. assert(string.find(tostring(f), "thread"))
  41. local s,a,b,c,d
  42. s,a,b,c,d = coroutine.resume(f, {1,2,3}, {}, {1}, {'a', 'b', 'c'})
  43. assert(coroutine.isyieldable(f))
  44. assert(s and a == nil and coroutine.status(f) == "suspended")
  45. s,a,b,c,d = coroutine.resume(f)
  46. eqtab(_G.x, {})
  47. assert(s and a == 1 and b == nil)
  48. assert(coroutine.isyieldable(f))
  49. s,a,b,c,d = coroutine.resume(f, 1, 2, 3)
  50. eqtab(_G.x, {1, 2, 3})
  51. assert(s and a == 'a' and b == 'b' and c == 'c' and d == nil)
  52. s,a,b,c,d = coroutine.resume(f, "xuxu")
  53. eqtab(_G.x, {"xuxu"})
  54. assert(s and a == 1 and b == 2 and c == 3 and d == nil)
  55. assert(coroutine.status(f) == "dead")
  56. s, a = coroutine.resume(f, "xuxu")
  57. assert(not s and string.find(a, "dead") and coroutine.status(f) == "dead")
  58. -- yields in tail calls
  59. local function foo (i) return coroutine.yield(i) end
  60. f = coroutine.wrap(function ()
  61. for i=1,10 do
  62. assert(foo(i) == _G.x)
  63. end
  64. return 'a'
  65. end)
  66. for i=1,10 do _G.x = i; assert(f(i) == i) end
  67. _G.x = 'xuxu'; assert(f('xuxu') == 'a')
  68. -- recursive
  69. function pf (n, i)
  70. coroutine.yield(n)
  71. pf(n*i, i+1)
  72. end
  73. f = coroutine.wrap(pf)
  74. local s=1
  75. for i=1,10 do
  76. assert(f(1, 1) == s)
  77. s = s*i
  78. end
  79. -- sieve
  80. function gen (n)
  81. return coroutine.wrap(function ()
  82. for i=2,n do coroutine.yield(i) end
  83. end)
  84. end
  85. function filter (p, g)
  86. return coroutine.wrap(function ()
  87. while 1 do
  88. local n = g()
  89. if n == nil then return end
  90. if math.fmod(n, p) ~= 0 then coroutine.yield(n) end
  91. end
  92. end)
  93. end
  94. local x = gen(80)
  95. local a = {}
  96. while 1 do
  97. local n = x()
  98. if n == nil then break end
  99. table.insert(a, n)
  100. x = filter(n, x)
  101. end
  102. assert(#a == 22 and a[#a] == 79)
  103. x, a = nil
  104. -- coroutine closing
  105. do
  106. -- ok to close a dead coroutine
  107. local co = coroutine.create(print)
  108. assert(coroutine.resume(co, "testing 'coroutine.close'"))
  109. assert(coroutine.status(co) == "dead")
  110. assert(coroutine.close(co))
  111. -- cannot close the running coroutine
  112. local st, msg = pcall(coroutine.close, coroutine.running())
  113. assert(not st and string.find(msg, "running"))
  114. local main = coroutine.running()
  115. -- cannot close a "normal" coroutine
  116. ;(coroutine.wrap(function ()
  117. local st, msg = pcall(coroutine.close, main)
  118. assert(not st and string.find(msg, "normal"))
  119. end))()
  120. -- to-be-closed variables in coroutines
  121. local X
  122. local function func2close (f)
  123. return setmetatable({}, {__close = f})
  124. end
  125. co = coroutine.create(function ()
  126. local x <close> = func2close(function (self, err)
  127. assert(err == nil); X = false
  128. end)
  129. X = true
  130. coroutine.yield()
  131. end)
  132. coroutine.resume(co)
  133. assert(X)
  134. assert(coroutine.close(co))
  135. assert(not X and coroutine.status(co) == "dead")
  136. -- error closing a coroutine
  137. warn("@on")
  138. local x = 0
  139. co = coroutine.create(function()
  140. local y <close> = func2close(function (self,err)
  141. if (err ~= 111) then os.exit(false) end -- should not happen
  142. x = 200
  143. error("200")
  144. end)
  145. local x <close> = func2close(function (self, err)
  146. assert(err == nil); error(111)
  147. end)
  148. coroutine.yield()
  149. end)
  150. coroutine.resume(co)
  151. assert(x == 0)
  152. -- with test library, use 'store' mode to check warnings
  153. warn(not T and "@off" or "@store")
  154. local st, msg = coroutine.close(co)
  155. if not T then
  156. warn("@on")
  157. else -- test library
  158. assert(string.find(_WARN, "200")); _WARN = nil
  159. warn("@normal")
  160. end
  161. assert(st == false and coroutine.status(co) == "dead" and msg == 111)
  162. assert(x == 200)
  163. end
  164. -- yielding across C boundaries
  165. co = coroutine.wrap(function()
  166. assert(not pcall(table.sort,{1,2,3}, coroutine.yield))
  167. assert(coroutine.isyieldable())
  168. coroutine.yield(20)
  169. return 30
  170. end)
  171. assert(co() == 20)
  172. assert(co() == 30)
  173. local f = function (s, i) return coroutine.yield(i) end
  174. local f1 = coroutine.wrap(function ()
  175. return xpcall(pcall, function (...) return ... end,
  176. function ()
  177. local s = 0
  178. for i in f, nil, 1 do pcall(function () s = s + i end) end
  179. error({s})
  180. end)
  181. end)
  182. f1()
  183. for i = 1, 10 do assert(f1(i) == i) end
  184. local r1, r2, v = f1(nil)
  185. assert(r1 and not r2 and v[1] == (10 + 1)*10/2)
  186. function f (a, b) a = coroutine.yield(a); error{a + b} end
  187. function g(x) return x[1]*2 end
  188. co = coroutine.wrap(function ()
  189. coroutine.yield(xpcall(f, g, 10, 20))
  190. end)
  191. assert(co() == 10)
  192. r, msg = co(100)
  193. assert(not r and msg == 240)
  194. -- unyieldable C call
  195. do
  196. local function f (c)
  197. assert(not coroutine.isyieldable())
  198. return c .. c
  199. end
  200. local co = coroutine.wrap(function (c)
  201. assert(coroutine.isyieldable())
  202. local s = string.gsub("a", ".", f)
  203. return s
  204. end)
  205. assert(co() == "aa")
  206. end
  207. do -- testing single trace of coroutines
  208. local X
  209. local co = coroutine.create(function ()
  210. coroutine.yield(10)
  211. return 20;
  212. end)
  213. local trace = {}
  214. local function dotrace (event)
  215. trace[#trace + 1] = event
  216. end
  217. debug.sethook(co, dotrace, "clr")
  218. repeat until not coroutine.resume(co)
  219. local correcttrace = {"call", "line", "call", "return", "line", "return"}
  220. assert(#trace == #correcttrace)
  221. for k, v in pairs(trace) do
  222. assert(v == correcttrace[k])
  223. end
  224. end
  225. -- errors in coroutines
  226. function foo ()
  227. assert(debug.getinfo(1).currentline == debug.getinfo(foo).linedefined + 1)
  228. assert(debug.getinfo(2).currentline == debug.getinfo(goo).linedefined)
  229. coroutine.yield(3)
  230. error(foo)
  231. end
  232. function goo() foo() end
  233. x = coroutine.wrap(goo)
  234. assert(x() == 3)
  235. local a,b = pcall(x)
  236. assert(not a and b == foo)
  237. x = coroutine.create(goo)
  238. a,b = coroutine.resume(x)
  239. assert(a and b == 3)
  240. a,b = coroutine.resume(x)
  241. assert(not a and b == foo and coroutine.status(x) == "dead")
  242. a,b = coroutine.resume(x)
  243. assert(not a and string.find(b, "dead") and coroutine.status(x) == "dead")
  244. -- co-routines x for loop
  245. function all (a, n, k)
  246. if k == 0 then coroutine.yield(a)
  247. else
  248. for i=1,n do
  249. a[k] = i
  250. all(a, n, k-1)
  251. end
  252. end
  253. end
  254. local a = 0
  255. for t in coroutine.wrap(function () all({}, 5, 4) end) do
  256. a = a+1
  257. end
  258. assert(a == 5^4)
  259. -- access to locals of collected corroutines
  260. local C = {}; setmetatable(C, {__mode = "kv"})
  261. local x = coroutine.wrap (function ()
  262. local a = 10
  263. local function f () a = a+10; return a end
  264. while true do
  265. a = a+1
  266. coroutine.yield(f)
  267. end
  268. end)
  269. C[1] = x;
  270. local f = x()
  271. assert(f() == 21 and x()() == 32 and x() == f)
  272. x = nil
  273. collectgarbage()
  274. assert(C[1] == undef)
  275. assert(f() == 43 and f() == 53)
  276. -- old bug: attempt to resume itself
  277. function co_func (current_co)
  278. assert(coroutine.running() == current_co)
  279. assert(coroutine.resume(current_co) == false)
  280. coroutine.yield(10, 20)
  281. assert(coroutine.resume(current_co) == false)
  282. coroutine.yield(23)
  283. return 10
  284. end
  285. local co = coroutine.create(co_func)
  286. local a,b,c = coroutine.resume(co, co)
  287. assert(a == true and b == 10 and c == 20)
  288. a,b = coroutine.resume(co, co)
  289. assert(a == true and b == 23)
  290. a,b = coroutine.resume(co, co)
  291. assert(a == true and b == 10)
  292. assert(coroutine.resume(co, co) == false)
  293. assert(coroutine.resume(co, co) == false)
  294. -- other old bug when attempting to resume itself
  295. -- (trigger C-code assertions)
  296. do
  297. local A = coroutine.running()
  298. local B = coroutine.create(function() return coroutine.resume(A) end)
  299. local st, res = coroutine.resume(B)
  300. assert(st == true and res == false)
  301. local X = false
  302. A = coroutine.wrap(function()
  303. local _ <close> = setmetatable({}, {__close = function () X = true end})
  304. return pcall(A, 1)
  305. end)
  306. st, res = A()
  307. assert(not st and string.find(res, "non%-suspended") and X == true)
  308. end
  309. -- attempt to resume 'normal' coroutine
  310. local co1, co2
  311. co1 = coroutine.create(function () return co2() end)
  312. co2 = coroutine.wrap(function ()
  313. assert(coroutine.status(co1) == 'normal')
  314. assert(not coroutine.resume(co1))
  315. coroutine.yield(3)
  316. end)
  317. a,b = coroutine.resume(co1)
  318. assert(a and b == 3)
  319. assert(coroutine.status(co1) == 'dead')
  320. -- infinite recursion of coroutines
  321. a = function(a) coroutine.wrap(a)(a) end
  322. assert(not pcall(a, a))
  323. a = nil
  324. -- access to locals of erroneous coroutines
  325. local x = coroutine.create (function ()
  326. local a = 10
  327. _G.f = function () a=a+1; return a end
  328. error('x')
  329. end)
  330. assert(not coroutine.resume(x))
  331. -- overwrite previous position of local `a'
  332. assert(not coroutine.resume(x, 1, 1, 1, 1, 1, 1, 1))
  333. assert(_G.f() == 11)
  334. assert(_G.f() == 12)
  335. if not T then
  336. (Message or print)('\n >>> testC not active: skipping yield/hook tests <<<\n')
  337. else
  338. print "testing yields inside hooks"
  339. local turn
  340. function fact (t, x)
  341. assert(turn == t)
  342. if x == 0 then return 1
  343. else return x*fact(t, x-1)
  344. end
  345. end
  346. local A, B = 0, 0
  347. local x = coroutine.create(function ()
  348. T.sethook("yield 0", "", 2)
  349. A = fact("A", 6)
  350. end)
  351. local y = coroutine.create(function ()
  352. T.sethook("yield 0", "", 3)
  353. B = fact("B", 7)
  354. end)
  355. while A==0 or B==0 do -- A ~= 0 when 'x' finishes (similar for 'B','y')
  356. if A==0 then turn = "A"; assert(T.resume(x)) end
  357. if B==0 then turn = "B"; assert(T.resume(y)) end
  358. -- check that traceback works correctly after yields inside hooks
  359. debug.traceback(x)
  360. debug.traceback(y)
  361. end
  362. assert(B // A == 7) -- fact(7) // fact(6)
  363. local line = debug.getinfo(1, "l").currentline + 2 -- get line number
  364. local function foo ()
  365. local x = 10 --<< this line is 'line'
  366. x = x + 10
  367. _G.XX = x
  368. end
  369. -- testing yields in line hook
  370. local co = coroutine.wrap(function ()
  371. T.sethook("setglobal X; yield 0", "l", 0); foo(); return 10 end)
  372. _G.XX = nil;
  373. _G.X = nil; co(); assert(_G.X == line)
  374. _G.X = nil; co(); assert(_G.X == line + 1)
  375. _G.X = nil; co(); assert(_G.X == line + 2 and _G.XX == nil)
  376. _G.X = nil; co(); assert(_G.X == line + 3 and _G.XX == 20)
  377. assert(co() == 10)
  378. -- testing yields in count hook
  379. co = coroutine.wrap(function ()
  380. T.sethook("yield 0", "", 1); foo(); return 10 end)
  381. _G.XX = nil;
  382. local c = 0
  383. repeat c = c + 1; local a = co() until a == 10
  384. assert(_G.XX == 20 and c >= 5)
  385. co = coroutine.wrap(function ()
  386. T.sethook("yield 0", "", 2); foo(); return 10 end)
  387. _G.XX = nil;
  388. local c = 0
  389. repeat c = c + 1; local a = co() until a == 10
  390. assert(_G.XX == 20 and c >= 5)
  391. _G.X = nil; _G.XX = nil
  392. do
  393. -- testing debug library on a coroutine suspended inside a hook
  394. -- (bug in 5.2/5.3)
  395. c = coroutine.create(function (a, ...)
  396. T.sethook("yield 0", "l") -- will yield on next two lines
  397. assert(a == 10)
  398. return ...
  399. end)
  400. assert(coroutine.resume(c, 1, 2, 3)) -- start coroutine
  401. local n,v = debug.getlocal(c, 0, 1) -- check its local
  402. assert(n == "a" and v == 1)
  403. assert(debug.setlocal(c, 0, 1, 10)) -- test 'setlocal'
  404. local t = debug.getinfo(c, 0) -- test 'getinfo'
  405. assert(t.currentline == t.linedefined + 1)
  406. assert(not debug.getinfo(c, 1)) -- no other level
  407. assert(coroutine.resume(c)) -- run next line
  408. v = {coroutine.resume(c)} -- finish coroutine
  409. assert(v[1] == true and v[2] == 2 and v[3] == 3 and v[4] == undef)
  410. assert(not coroutine.resume(c))
  411. end
  412. do
  413. -- testing debug library on last function in a suspended coroutine
  414. -- (bug in 5.2/5.3)
  415. local c = coroutine.create(function () T.testC("yield 1", 10, 20) end)
  416. local a, b = coroutine.resume(c)
  417. assert(a and b == 20)
  418. assert(debug.getinfo(c, 0).linedefined == -1)
  419. a, b = debug.getlocal(c, 0, 2)
  420. assert(b == 10)
  421. end
  422. print "testing coroutine API"
  423. -- reusing a thread
  424. assert(T.testC([[
  425. newthread # create thread
  426. pushvalue 2 # push body
  427. pushstring 'a a a' # push argument
  428. xmove 0 3 2 # move values to new thread
  429. resume -1, 1 # call it first time
  430. pushstatus
  431. xmove 3 0 0 # move results back to stack
  432. setglobal X # result
  433. setglobal Y # status
  434. pushvalue 2 # push body (to call it again)
  435. pushstring 'b b b'
  436. xmove 0 3 2
  437. resume -1, 1 # call it again
  438. pushstatus
  439. xmove 3 0 0
  440. return 1 # return result
  441. ]], function (...) return ... end) == 'b b b')
  442. assert(X == 'a a a' and Y == 'OK')
  443. -- resuming running coroutine
  444. C = coroutine.create(function ()
  445. return T.testC([[
  446. pushnum 10;
  447. pushnum 20;
  448. resume -3 2;
  449. pushstatus
  450. gettop;
  451. return 3]], C)
  452. end)
  453. local a, b, c, d = coroutine.resume(C)
  454. assert(a == true and string.find(b, "non%-suspended") and
  455. c == "ERRRUN" and d == 4)
  456. a, b, c, d = T.testC([[
  457. rawgeti R 1 # get main thread
  458. pushnum 10;
  459. pushnum 20;
  460. resume -3 2;
  461. pushstatus
  462. gettop;
  463. return 4]])
  464. assert(a == coroutine.running() and string.find(b, "non%-suspended") and
  465. c == "ERRRUN" and d == 4)
  466. -- using a main thread as a coroutine
  467. local state = T.newstate()
  468. T.loadlib(state)
  469. assert(T.doremote(state, [[
  470. coroutine = require'coroutine';
  471. X = function (x) coroutine.yield(x, 'BB'); return 'CC' end;
  472. return 'ok']]))
  473. t = table.pack(T.testC(state, [[
  474. rawgeti R 1 # get main thread
  475. pushstring 'XX'
  476. getglobal X # get function for body
  477. pushstring AA # arg
  478. resume 1 1 # 'resume' shadows previous stack!
  479. gettop
  480. setglobal T # top
  481. setglobal B # second yielded value
  482. setglobal A # fist yielded value
  483. rawgeti R 1 # get main thread
  484. pushnum 5 # arg (noise)
  485. resume 1 1 # after coroutine ends, previous stack is back
  486. pushstatus
  487. return *
  488. ]]))
  489. assert(t.n == 4 and t[2] == 'XX' and t[3] == 'CC' and t[4] == 'OK')
  490. assert(T.doremote(state, "return T") == '2')
  491. assert(T.doremote(state, "return A") == 'AA')
  492. assert(T.doremote(state, "return B") == 'BB')
  493. T.closestate(state)
  494. print'+'
  495. end
  496. -- leaving a pending coroutine open
  497. _X = coroutine.wrap(function ()
  498. local a = 10
  499. local x = function () a = a+1 end
  500. coroutine.yield()
  501. end)
  502. _X()
  503. if not _soft then
  504. -- bug (stack overflow)
  505. local j = 2^9
  506. local lim = 1000000 -- (C stack limit; assume 32-bit machine)
  507. local t = {lim - 10, lim - 5, lim - 1, lim, lim + 1}
  508. for i = 1, #t do
  509. local j = t[i]
  510. co = coroutine.create(function()
  511. local t = {}
  512. for i = 1, j do t[i] = i end
  513. return table.unpack(t)
  514. end)
  515. local r, msg = coroutine.resume(co)
  516. assert(not r)
  517. end
  518. co = nil
  519. end
  520. assert(coroutine.running() == main)
  521. print"+"
  522. print"testing yields inside metamethods"
  523. local function val(x)
  524. if type(x) == "table" then return x.x else return x end
  525. end
  526. local mt = {
  527. __eq = function(a,b) coroutine.yield(nil, "eq"); return val(a) == val(b) end,
  528. __lt = function(a,b) coroutine.yield(nil, "lt"); return val(a) < val(b) end,
  529. __le = function(a,b) coroutine.yield(nil, "le"); return a - b <= 0 end,
  530. __add = function(a,b) coroutine.yield(nil, "add");
  531. return val(a) + val(b) end,
  532. __sub = function(a,b) coroutine.yield(nil, "sub"); return val(a) - val(b) end,
  533. __mul = function(a,b) coroutine.yield(nil, "mul"); return val(a) * val(b) end,
  534. __div = function(a,b) coroutine.yield(nil, "div"); return val(a) / val(b) end,
  535. __idiv = function(a,b) coroutine.yield(nil, "idiv");
  536. return val(a) // val(b) end,
  537. __pow = function(a,b) coroutine.yield(nil, "pow"); return val(a) ^ val(b) end,
  538. __mod = function(a,b) coroutine.yield(nil, "mod"); return val(a) % val(b) end,
  539. __unm = function(a,b) coroutine.yield(nil, "unm"); return -val(a) end,
  540. __bnot = function(a,b) coroutine.yield(nil, "bnot"); return ~val(a) end,
  541. __shl = function(a,b) coroutine.yield(nil, "shl");
  542. return val(a) << val(b) end,
  543. __shr = function(a,b) coroutine.yield(nil, "shr");
  544. return val(a) >> val(b) end,
  545. __band = function(a,b)
  546. coroutine.yield(nil, "band")
  547. return val(a) & val(b)
  548. end,
  549. __bor = function(a,b) coroutine.yield(nil, "bor");
  550. return val(a) | val(b) end,
  551. __bxor = function(a,b) coroutine.yield(nil, "bxor");
  552. return val(a) ~ val(b) end,
  553. __concat = function(a,b)
  554. coroutine.yield(nil, "concat");
  555. return val(a) .. val(b)
  556. end,
  557. __index = function (t,k) coroutine.yield(nil, "idx"); return t.k[k] end,
  558. __newindex = function (t,k,v) coroutine.yield(nil, "nidx"); t.k[k] = v end,
  559. }
  560. local function new (x)
  561. return setmetatable({x = x, k = {}}, mt)
  562. end
  563. local a = new(10)
  564. local b = new(12)
  565. local c = new"hello"
  566. local function run (f, t)
  567. local i = 1
  568. local c = coroutine.wrap(f)
  569. while true do
  570. local res, stat = c()
  571. if res then assert(t[i] == undef); return res, t end
  572. assert(stat == t[i])
  573. i = i + 1
  574. end
  575. end
  576. assert(run(function () if (a>=b) then return '>=' else return '<' end end,
  577. {"le", "sub"}) == "<")
  578. assert(run(function () if (a<=b) then return '<=' else return '>' end end,
  579. {"le", "sub"}) == "<=")
  580. assert(run(function () if (a==b) then return '==' else return '~=' end end,
  581. {"eq"}) == "~=")
  582. assert(run(function () return a & b + a end, {"add", "band"}) == 2)
  583. assert(run(function () return 1 + a end, {"add"}) == 11)
  584. assert(run(function () return a - 25 end, {"sub"}) == -15)
  585. assert(run(function () return 2 * a end, {"mul"}) == 20)
  586. assert(run(function () return a ^ 2 end, {"pow"}) == 100)
  587. assert(run(function () return a / 2 end, {"div"}) == 5)
  588. assert(run(function () return a % 6 end, {"mod"}) == 4)
  589. assert(run(function () return a // 3 end, {"idiv"}) == 3)
  590. assert(run(function () return a + b end, {"add"}) == 22)
  591. assert(run(function () return a - b end, {"sub"}) == -2)
  592. assert(run(function () return a * b end, {"mul"}) == 120)
  593. assert(run(function () return a ^ b end, {"pow"}) == 10^12)
  594. assert(run(function () return a / b end, {"div"}) == 10/12)
  595. assert(run(function () return a % b end, {"mod"}) == 10)
  596. assert(run(function () return a // b end, {"idiv"}) == 0)
  597. -- repeat tests with larger constants (to use 'K' opcodes)
  598. local a1000 = new(1000)
  599. assert(run(function () return a1000 + 1000 end, {"add"}) == 2000)
  600. assert(run(function () return a1000 - 25000 end, {"sub"}) == -24000)
  601. assert(run(function () return 2000 * a end, {"mul"}) == 20000)
  602. assert(run(function () return a1000 / 1000 end, {"div"}) == 1)
  603. assert(run(function () return a1000 % 600 end, {"mod"}) == 400)
  604. assert(run(function () return a1000 // 500 end, {"idiv"}) == 2)
  605. assert(run(function () return a % b end, {"mod"}) == 10)
  606. assert(run(function () return ~a & b end, {"bnot", "band"}) == ~10 & 12)
  607. assert(run(function () return a | b end, {"bor"}) == 10 | 12)
  608. assert(run(function () return a ~ b end, {"bxor"}) == 10 ~ 12)
  609. assert(run(function () return a << b end, {"shl"}) == 10 << 12)
  610. assert(run(function () return a >> b end, {"shr"}) == 10 >> 12)
  611. assert(run(function () return 10 & b end, {"band"}) == 10 & 12)
  612. assert(run(function () return a | 2 end, {"bor"}) == 10 | 2)
  613. assert(run(function () return a ~ 2 end, {"bxor"}) == 10 ~ 2)
  614. assert(run(function () return a >> 2 end, {"shr"}) == 10 >> 2)
  615. assert(run(function () return 1 >> a end, {"shr"}) == 1 >> 10)
  616. assert(run(function () return a << 2 end, {"shl"}) == 10 << 2)
  617. assert(run(function () return 1 << a end, {"shl"}) == 1 << 10)
  618. assert(run(function () return 2 ~ a end, {"bxor"}) == 2 ~ 10)
  619. assert(run(function () return a..b end, {"concat"}) == "1012")
  620. assert(run(function() return a .. b .. c .. a end,
  621. {"concat", "concat", "concat"}) == "1012hello10")
  622. assert(run(function() return "a" .. "b" .. a .. "c" .. c .. b .. "x" end,
  623. {"concat", "concat", "concat"}) == "ab10chello12x")
  624. do -- a few more tests for comparsion operators
  625. local mt1 = {
  626. __le = function (a,b)
  627. coroutine.yield(10)
  628. return (val(a) <= val(b))
  629. end,
  630. __lt = function (a,b)
  631. coroutine.yield(10)
  632. return val(a) < val(b)
  633. end,
  634. }
  635. local mt2 = { __lt = mt1.__lt, __le = mt1.__le }
  636. local function run (f)
  637. local co = coroutine.wrap(f)
  638. local res
  639. repeat
  640. res = co()
  641. until res ~= 10
  642. return res
  643. end
  644. local function test ()
  645. local a1 = setmetatable({x=1}, mt1)
  646. local a2 = setmetatable({x=2}, mt2)
  647. assert(a1 < a2)
  648. assert(a1 <= a2)
  649. assert(1 < a2)
  650. assert(1 <= a2)
  651. assert(2 > a1)
  652. assert(2 >= a2)
  653. return true
  654. end
  655. run(test)
  656. end
  657. assert(run(function ()
  658. a.BB = print
  659. return a.BB
  660. end, {"nidx", "idx"}) == print)
  661. -- getuptable & setuptable
  662. do local _ENV = _ENV
  663. f = function () AAA = BBB + 1; return AAA end
  664. end
  665. g = new(10); g.k.BBB = 10;
  666. debug.setupvalue(f, 1, g)
  667. assert(run(f, {"idx", "nidx", "idx"}) == 11)
  668. assert(g.k.AAA == 11)
  669. print"+"
  670. print"testing yields inside 'for' iterators"
  671. local f = function (s, i)
  672. if i%2 == 0 then coroutine.yield(nil, "for") end
  673. if i < s then return i + 1 end
  674. end
  675. assert(run(function ()
  676. local s = 0
  677. for i in f, 4, 0 do s = s + i end
  678. return s
  679. end, {"for", "for", "for"}) == 10)
  680. -- tests for coroutine API
  681. if T==nil then
  682. (Message or print)('\n >>> testC not active: skipping coroutine API tests <<<\n')
  683. print "OK"; return
  684. end
  685. print('testing coroutine API')
  686. local function apico (...)
  687. local x = {...}
  688. return coroutine.wrap(function ()
  689. return T.testC(table.unpack(x))
  690. end)
  691. end
  692. local a = {apico(
  693. [[
  694. pushstring errorcode
  695. pcallk 1 0 2;
  696. invalid command (should not arrive here)
  697. ]],
  698. [[return *]],
  699. "stackmark",
  700. error
  701. )()}
  702. assert(#a == 4 and
  703. a[3] == "stackmark" and
  704. a[4] == "errorcode" and
  705. _G.status == "ERRRUN" and
  706. _G.ctx == 2) -- 'ctx' to pcallk
  707. local co = apico(
  708. "pushvalue 2; pushnum 10; pcallk 1 2 3; invalid command;",
  709. coroutine.yield,
  710. "getglobal status; getglobal ctx; pushvalue 2; pushstring a; pcallk 1 0 4; invalid command",
  711. "getglobal status; getglobal ctx; return *")
  712. assert(co() == 10)
  713. assert(co(20, 30) == 'a')
  714. a = {co()}
  715. assert(#a == 10 and
  716. a[2] == coroutine.yield and
  717. a[5] == 20 and a[6] == 30 and
  718. a[7] == "YIELD" and a[8] == 3 and
  719. a[9] == "YIELD" and a[10] == 4)
  720. assert(not pcall(co)) -- coroutine is dead now
  721. f = T.makeCfunc("pushnum 3; pushnum 5; yield 1;")
  722. co = coroutine.wrap(function ()
  723. assert(f() == 23); assert(f() == 23); return 10
  724. end)
  725. assert(co(23,16) == 5)
  726. assert(co(23,16) == 5)
  727. assert(co(23,16) == 10)
  728. -- testing coroutines with C bodies
  729. f = T.makeCfunc([[
  730. pushnum 102
  731. yieldk 1 U2
  732. cannot be here!
  733. ]],
  734. [[ # continuation
  735. pushvalue U3 # accessing upvalues inside a continuation
  736. pushvalue U4
  737. return *
  738. ]], 23, "huu")
  739. x = coroutine.wrap(f)
  740. assert(x() == 102)
  741. eqtab({x()}, {23, "huu"})
  742. f = T.makeCfunc[[pushstring 'a'; pushnum 102; yield 2; ]]
  743. a, b, c, d = T.testC([[newthread; pushvalue 2; xmove 0 3 1; resume 3 0;
  744. pushstatus; xmove 3 0 0; resume 3 0; pushstatus;
  745. return 4; ]], f)
  746. assert(a == 'YIELD' and b == 'a' and c == 102 and d == 'OK')
  747. -- testing chain of suspendable C calls
  748. local count = 3 -- number of levels
  749. f = T.makeCfunc([[
  750. remove 1; # remove argument
  751. pushvalue U3; # get selection function
  752. call 0 1; # call it (result is 'f' or 'yield')
  753. pushstring hello # single argument for selected function
  754. pushupvalueindex 2; # index of continuation program
  755. callk 1 -1 .; # call selected function
  756. errorerror # should never arrive here
  757. ]],
  758. [[
  759. # continuation program
  760. pushnum 34 # return value
  761. return * # return all results
  762. ]],
  763. function () -- selection function
  764. count = count - 1
  765. if count == 0 then return coroutine.yield
  766. else return f
  767. end
  768. end
  769. )
  770. co = coroutine.wrap(function () return f(nil) end)
  771. assert(co() == "hello") -- argument to 'yield'
  772. a = {co()}
  773. -- three '34's (one from each pending C call)
  774. assert(#a == 3 and a[1] == a[2] and a[2] == a[3] and a[3] == 34)
  775. -- testing yields with continuations
  776. co = coroutine.wrap(function (...) return
  777. T.testC([[ # initial function
  778. yieldk 1 2
  779. cannot be here!
  780. ]],
  781. [[ # 1st continuation
  782. yieldk 0 3
  783. cannot be here!
  784. ]],
  785. [[ # 2nd continuation
  786. yieldk 0 4
  787. cannot be here!
  788. ]],
  789. [[ # 3th continuation
  790. pushvalue 6 # function which is last arg. to 'testC' here
  791. pushnum 10; pushnum 20;
  792. pcall 2 0 0 # call should throw an error and return to next line
  793. pop 1 # remove error message
  794. pushvalue 6
  795. getglobal status; getglobal ctx
  796. pcallk 2 2 5 # call should throw an error and jump to continuation
  797. cannot be here!
  798. ]],
  799. [[ # 4th (and last) continuation
  800. return *
  801. ]],
  802. -- function called by 3th continuation
  803. function (a,b) x=a; y=b; error("errmsg") end,
  804. ...
  805. )
  806. end)
  807. local a = {co(3,4,6)}
  808. assert(a[1] == 6 and a[2] == undef)
  809. a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 2)
  810. a = {co()}; assert(a[1] == undef and _G.status == "YIELD" and _G.ctx == 3)
  811. a = {co(7,8)};
  812. -- original arguments
  813. assert(type(a[1]) == 'string' and type(a[2]) == 'string' and
  814. type(a[3]) == 'string' and type(a[4]) == 'string' and
  815. type(a[5]) == 'string' and type(a[6]) == 'function')
  816. -- arguments left from fist resume
  817. assert(a[7] == 3 and a[8] == 4)
  818. -- arguments to last resume
  819. assert(a[9] == 7 and a[10] == 8)
  820. -- error message and nothing more
  821. assert(a[11]:find("errmsg") and #a == 11)
  822. -- check arguments to pcallk
  823. assert(x == "YIELD" and y == 4)
  824. assert(not pcall(co)) -- coroutine should be dead
  825. -- bug in nCcalls
  826. local co = coroutine.wrap(function ()
  827. local a = {pcall(pcall,pcall,pcall,pcall,pcall,pcall,pcall,error,"hi")}
  828. return pcall(assert, table.unpack(a))
  829. end)
  830. local a = {co()}
  831. assert(a[10] == "hi")
  832. print'OK'