coroutine.lua 26 KB

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