coroutine.lua 25 KB

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