coroutine.lua 24 KB

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