coroutine.lua 25 KB

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