coroutine.lua 26 KB

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