runtime.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. /**
  2. * Copyright (c) 2006-2020 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "config.h"
  21. #include "runtime.h"
  22. // LOVE
  23. #include "Module.h"
  24. #include "Object.h"
  25. #include "Reference.h"
  26. #include "StringMap.h"
  27. // C++
  28. #include <algorithm>
  29. #include <iostream>
  30. #include <cstdio>
  31. #include <cstddef>
  32. #include <cmath>
  33. #include <sstream>
  34. // VS2013 doesn't support alignof
  35. #if defined(_MSC_VER) && _MSC_VER <= 1800
  36. #define LOVE_ALIGNOF(x) __alignof(x)
  37. #else
  38. #define LOVE_ALIGNOF(x) alignof(x)
  39. #endif
  40. namespace love
  41. {
  42. /**
  43. * Called when an object is collected. The object is released
  44. * once in this function, possibly deleting it.
  45. **/
  46. static int w__gc(lua_State *L)
  47. {
  48. Proxy *p = (Proxy *) lua_touserdata(L, 1);
  49. if (p->object != nullptr)
  50. {
  51. p->object->release();
  52. p->object = nullptr;
  53. }
  54. return 0;
  55. }
  56. static int w__tostring(lua_State *L)
  57. {
  58. Proxy *p = (Proxy *) lua_touserdata(L, 1);
  59. const char *typname = lua_tostring(L, lua_upvalueindex(1));
  60. lua_pushfstring(L, "%s: %p", typname, p->object);
  61. return 1;
  62. }
  63. static int w__type(lua_State *L)
  64. {
  65. lua_pushvalue(L, lua_upvalueindex(1));
  66. return 1;
  67. }
  68. static int w__typeOf(lua_State *L)
  69. {
  70. Proxy *p = (Proxy *)lua_touserdata(L, 1);
  71. Type *t = luax_type(L, 2);
  72. if (!t)
  73. luax_pushboolean(L, false);
  74. else
  75. luax_pushboolean(L, p->type->isa(*t));
  76. return 1;
  77. }
  78. static int w__eq(lua_State *L)
  79. {
  80. Proxy *p1 = (Proxy *)lua_touserdata(L, 1);
  81. Proxy *p2 = (Proxy *)lua_touserdata(L, 2);
  82. luax_pushboolean(L, p1->object == p2->object && p1->object != nullptr);
  83. return 1;
  84. }
  85. // For use with the love object pointer -> Proxy pointer registry.
  86. // Using the pointer directly via lightuserdata would be ideal, but LuaJIT
  87. // cannot use lightuserdata with more than 47 bits whereas some newer arm64
  88. // architectures allow pointers which use more than that.
  89. static lua_Number luax_computeloveobjectkey(lua_State *L, love::Object *object)
  90. {
  91. // love objects should be allocated on the heap, and thus are subject
  92. // to the alignment rules of operator new / malloc. Lua numbers (doubles)
  93. // can store all possible integers up to 2^53. We can store pointers that
  94. // use more than 53 bits if their alignment is guaranteed to be more than 1.
  95. // For example an alignment requirement of 8 means we can shift the
  96. // pointer's bits by 3.
  97. const size_t minalign = LOVE_ALIGNOF(std::max_align_t);
  98. uintptr_t key = (uintptr_t) object;
  99. if ((key & (minalign - 1)) != 0)
  100. {
  101. luaL_error(L, "Cannot push love object to Lua: unexpected alignment "
  102. "(pointer is %p but alignment should be %d)", object, minalign);
  103. }
  104. static const size_t shift = (size_t) log2(LOVE_ALIGNOF(std::max_align_t));
  105. key >>= shift;
  106. // Make sure our key isn't larger than 2^53.
  107. if (key > 0x20000000000000ULL)
  108. luaL_error(L, "Cannot push love object to Lua: pointer value %p is too large", object);
  109. return (lua_Number) key;
  110. }
  111. static int w__release(lua_State *L)
  112. {
  113. Proxy *p = (Proxy *) lua_touserdata(L, 1);
  114. Object *object = p->object;
  115. if (object != nullptr)
  116. {
  117. p->object = nullptr;
  118. object->release();
  119. // Fetch the registry table of instantiated objects.
  120. luax_getregistry(L, REGISTRY_OBJECTS);
  121. if (lua_istable(L, -1))
  122. {
  123. // loveobjects[object] = nil
  124. lua_Number objectkey = luax_computeloveobjectkey(L, object);
  125. lua_pushnumber(L, objectkey);
  126. lua_pushnil(L);
  127. lua_settable(L, -3);
  128. }
  129. lua_pop(L, 1);
  130. }
  131. luax_pushboolean(L, object != nullptr);
  132. return 1;
  133. }
  134. Reference *luax_refif(lua_State *L, int type)
  135. {
  136. Reference *r = nullptr;
  137. // Create a reference only if the test succeeds.
  138. if (lua_type(L, -1) == type)
  139. r = new Reference(L);
  140. else // Pop the value manually if it fails (done by Reference if it succeeds).
  141. lua_pop(L, 1);
  142. return r;
  143. }
  144. void luax_printstack(lua_State *L)
  145. {
  146. for (int i = 1; i <= lua_gettop(L); i++)
  147. std::cout << i << " - " << luaL_typename(L, i) << std::endl;
  148. }
  149. int luax_traceback(lua_State *L)
  150. {
  151. if (!lua_isstring(L, 1)) // 'message' not a string?
  152. return 1; // keep it intact
  153. lua_getglobal(L, "debug");
  154. if (!lua_istable(L, -1))
  155. {
  156. lua_pop(L, 1);
  157. return 1;
  158. }
  159. lua_getfield(L, -1, "traceback");
  160. if (!lua_isfunction(L, -1))
  161. {
  162. lua_pop(L, 2);
  163. return 1;
  164. }
  165. lua_pushvalue(L, 1); // pass error message
  166. lua_pushinteger(L, 2); // skip this function and traceback
  167. lua_call(L, 2, 1); // call debug.traceback
  168. return 1;
  169. }
  170. bool luax_isarrayoftables(lua_State *L, int idx)
  171. {
  172. if (!lua_istable(L, idx))
  173. return false;
  174. lua_rawgeti(L, idx, 1);
  175. bool tableoftables = lua_istable(L, -1);
  176. lua_pop(L, 1);
  177. return tableoftables;
  178. }
  179. bool luax_toboolean(lua_State *L, int idx)
  180. {
  181. return (lua_toboolean(L, idx) != 0);
  182. }
  183. bool luax_checkboolean(lua_State *L, int idx)
  184. {
  185. luaL_checktype(L, idx, LUA_TBOOLEAN);
  186. return luax_toboolean(L, idx);
  187. }
  188. void luax_pushboolean(lua_State *L, bool b)
  189. {
  190. lua_pushboolean(L, b ? 1 : 0);
  191. }
  192. bool luax_optboolean(lua_State *L, int idx, bool b)
  193. {
  194. if (lua_isboolean(L, idx) == 1)
  195. return (lua_toboolean(L, idx) == 1 ? true : false);
  196. return b;
  197. }
  198. std::string luax_tostring(lua_State *L, int idx)
  199. {
  200. size_t len;
  201. const char *str = lua_tolstring(L, idx, &len);
  202. return std::string(str, len);
  203. }
  204. std::string luax_checkstring(lua_State *L, int idx)
  205. {
  206. size_t len;
  207. const char *str = luaL_checklstring(L, idx, &len);
  208. return std::string(str, len);
  209. }
  210. void luax_pushstring(lua_State *L, const std::string &str)
  211. {
  212. lua_pushlstring(L, str.data(), str.size());
  213. }
  214. void luax_pushpointerasstring(lua_State *L, const void *pointer)
  215. {
  216. char str[sizeof(void *)];
  217. memcpy(str, &pointer, sizeof(void *));
  218. lua_pushlstring(L, str, sizeof(void *));
  219. }
  220. bool luax_boolflag(lua_State *L, int table_index, const char *key, bool defaultValue)
  221. {
  222. lua_getfield(L, table_index, key);
  223. bool retval;
  224. if (lua_isnoneornil(L, -1))
  225. retval = defaultValue;
  226. else
  227. retval = lua_toboolean(L, -1) != 0;
  228. lua_pop(L, 1);
  229. return retval;
  230. }
  231. int luax_intflag(lua_State *L, int table_index, const char *key, int defaultValue)
  232. {
  233. lua_getfield(L, table_index, key);
  234. int retval;
  235. if (!lua_isnumber(L, -1))
  236. retval = defaultValue;
  237. else
  238. retval = (int) lua_tointeger(L, -1);
  239. lua_pop(L, 1);
  240. return retval;
  241. }
  242. double luax_numberflag(lua_State *L, int table_index, const char *key, double defaultValue)
  243. {
  244. lua_getfield(L, table_index, key);
  245. double retval;
  246. if (!lua_isnumber(L, -1))
  247. retval = defaultValue;
  248. else
  249. retval = lua_tonumber(L, -1);
  250. lua_pop(L, 1);
  251. return retval;
  252. }
  253. bool luax_checkboolflag(lua_State *L, int table_index, const char *key)
  254. {
  255. lua_getfield(L, table_index, key);
  256. bool retval = false;
  257. if (lua_type(L, -1) != LUA_TBOOLEAN)
  258. {
  259. std::string err = "expected boolean field '" + std::string(key) + "' in table";
  260. return luaL_argerror(L, table_index, err.c_str());
  261. }
  262. else
  263. retval = luax_toboolean(L, -1);
  264. lua_pop(L, 1);
  265. return retval;
  266. }
  267. int luax_checkintflag(lua_State *L, int table_index, const char *key)
  268. {
  269. lua_getfield(L, table_index, key);
  270. int retval;
  271. if (!lua_isnumber(L, -1))
  272. {
  273. std::string err = "expected integer field '" + std::string(key) + "' in table";
  274. return luaL_argerror(L, table_index, err.c_str());
  275. }
  276. else
  277. retval = (int) luaL_checkinteger(L, -1);
  278. lua_pop(L, 1);
  279. return retval;
  280. }
  281. int luax_assert_argc(lua_State *L, int min)
  282. {
  283. int argc = lua_gettop(L);
  284. if (argc < min)
  285. return luaL_error(L, "Incorrect number of arguments. Got [%d], expected at least [%d]", argc, min);
  286. return 0;
  287. }
  288. int luax_assert_argc(lua_State *L, int min, int max)
  289. {
  290. int argc = lua_gettop(L);
  291. if (argc < min || argc > max)
  292. return luaL_error(L, "Incorrect number of arguments. Got [%d], expected [%d-%d]", argc, min, max);
  293. return 0;
  294. }
  295. int luax_assert_function(lua_State *L, int idx)
  296. {
  297. if (!lua_isfunction(L, idx))
  298. return luaL_error(L, "Argument must be of type \"function\".");
  299. return 0;
  300. }
  301. int luax_assert_nilerror(lua_State *L, int idx)
  302. {
  303. if (lua_isnoneornil(L, idx))
  304. {
  305. if (lua_isstring(L, idx + 1))
  306. return luaL_error(L, lua_tostring(L, idx + 1));
  307. else
  308. return luaL_error(L, "assertion failed!");
  309. }
  310. return 0;
  311. }
  312. void luax_setfuncs(lua_State *L, const luaL_Reg *l)
  313. {
  314. if (l == nullptr)
  315. return;
  316. for (; l->name != nullptr; l++)
  317. {
  318. lua_pushcfunction(L, l->func);
  319. lua_setfield(L, -2, l->name);
  320. }
  321. }
  322. int luax_require(lua_State *L, const char *name)
  323. {
  324. lua_getglobal(L, "require");
  325. lua_pushstring(L, name);
  326. lua_call(L, 1, 1);
  327. return 1;
  328. }
  329. int luax_register_module(lua_State *L, const WrappedModule &m)
  330. {
  331. m.type->init();
  332. // Put a reference to the C++ module in Lua.
  333. luax_insistregistry(L, REGISTRY_MODULES);
  334. Proxy *p = (Proxy *)lua_newuserdata(L, sizeof(Proxy));
  335. p->object = m.module;
  336. p->type = m.type;
  337. luaL_newmetatable(L, m.module->getName());
  338. lua_pushvalue(L, -1);
  339. lua_setfield(L, -2, "__index");
  340. lua_pushcfunction(L, w__gc);
  341. lua_setfield(L, -2, "__gc");
  342. lua_setmetatable(L, -2);
  343. lua_setfield(L, -2, m.name); // _modules[name] = proxy
  344. lua_pop(L, 1);
  345. // Gets the love table.
  346. luax_insistglobal(L, "love");
  347. // Create new table for module.
  348. lua_newtable(L);
  349. // Register all the functions.
  350. if (m.functions != nullptr)
  351. luax_setfuncs(L, m.functions);
  352. // Register types.
  353. if (m.types != nullptr)
  354. {
  355. for (const lua_CFunction *t = m.types; *t != nullptr; t++)
  356. (*t)(L);
  357. }
  358. lua_pushvalue(L, -1);
  359. lua_setfield(L, -3, m.name); // love.graphics = table
  360. lua_remove(L, -2); // love
  361. // Register module instance
  362. Module::registerInstance(m.module);
  363. return 1;
  364. }
  365. int luax_preload(lua_State *L, lua_CFunction f, const char *name)
  366. {
  367. lua_getglobal(L, "package");
  368. lua_getfield(L, -1, "preload");
  369. lua_pushcfunction(L, f);
  370. lua_setfield(L, -2, name);
  371. lua_pop(L, 2);
  372. return 0;
  373. }
  374. int luax_register_type(lua_State *L, love::Type *type, ...)
  375. {
  376. type->init();
  377. // Get the place for storing and re-using instantiated love types.
  378. luax_getregistry(L, REGISTRY_OBJECTS);
  379. // Create registry._loveobjects if it doesn't exist yet.
  380. if (!lua_istable(L, -1))
  381. {
  382. lua_newtable(L);
  383. lua_replace(L, -2);
  384. // Create a metatable.
  385. lua_newtable(L);
  386. // metatable.__mode = "v". Weak userdata values.
  387. lua_pushliteral(L, "v");
  388. lua_setfield(L, -2, "__mode");
  389. // setmetatable(newtable, metatable)
  390. lua_setmetatable(L, -2);
  391. // registry._loveobjects = newtable
  392. lua_setfield(L, LUA_REGISTRYINDEX, "_loveobjects");
  393. }
  394. else
  395. lua_pop(L, 1);
  396. luaL_newmetatable(L, type->getName());
  397. // m.__index = m
  398. lua_pushvalue(L, -1);
  399. lua_setfield(L, -2, "__index");
  400. // setup gc
  401. lua_pushcfunction(L, w__gc);
  402. lua_setfield(L, -2, "__gc");
  403. // Add equality
  404. lua_pushcfunction(L, w__eq);
  405. lua_setfield(L, -2, "__eq");
  406. // Add tostring function.
  407. lua_pushstring(L, type->getName());
  408. lua_pushcclosure(L, w__tostring, 1);
  409. lua_setfield(L, -2, "__tostring");
  410. // Add type
  411. lua_pushstring(L, type->getName());
  412. lua_pushcclosure(L, w__type, 1);
  413. lua_setfield(L, -2, "type");
  414. // Add typeOf
  415. lua_pushcfunction(L, w__typeOf);
  416. lua_setfield(L, -2, "typeOf");
  417. // Add release
  418. lua_pushcfunction(L, w__release);
  419. lua_setfield(L, -2, "release");
  420. va_list fs;
  421. va_start(fs, type);
  422. for (const luaL_Reg *f = va_arg(fs, const luaL_Reg *); f; f = va_arg(fs, const luaL_Reg *))
  423. luax_setfuncs(L, f);
  424. va_end(fs);
  425. lua_pop(L, 1); // Pops metatable.
  426. return 0;
  427. }
  428. void luax_gettypemetatable(lua_State *L, const love::Type &type)
  429. {
  430. const char *name = type.getName();
  431. lua_getfield(L, LUA_REGISTRYINDEX, name);
  432. }
  433. int luax_table_insert(lua_State *L, int tindex, int vindex, int pos)
  434. {
  435. if (tindex < 0)
  436. tindex = lua_gettop(L)+1+tindex;
  437. if (vindex < 0)
  438. vindex = lua_gettop(L)+1+vindex;
  439. if (pos == -1)
  440. {
  441. lua_pushvalue(L, vindex);
  442. lua_rawseti(L, tindex, (int) luax_objlen(L, tindex)+1);
  443. return 0;
  444. }
  445. else if (pos < 0)
  446. pos = (int) luax_objlen(L, tindex)+1+pos;
  447. for (int i = (int) luax_objlen(L, tindex)+1; i > pos; i--)
  448. {
  449. lua_rawgeti(L, tindex, i-1);
  450. lua_rawseti(L, tindex, i);
  451. }
  452. lua_pushvalue(L, vindex);
  453. lua_rawseti(L, tindex, pos);
  454. return 0;
  455. }
  456. int luax_register_searcher(lua_State *L, lua_CFunction f, int pos)
  457. {
  458. // Add the package loader to the package.loaders table.
  459. lua_getglobal(L, "package");
  460. if (lua_isnil(L, -1))
  461. return luaL_error(L, "Can't register searcher: package table does not exist.");
  462. lua_getfield(L, -1, "loaders");
  463. // Lua 5.2 renamed package.loaders to package.searchers.
  464. if (lua_isnil(L, -1))
  465. {
  466. lua_pop(L, 1);
  467. lua_getfield(L, -1, "searchers");
  468. }
  469. if (lua_isnil(L, -1))
  470. return luaL_error(L, "Can't register searcher: package.loaders table does not exist.");
  471. lua_pushcfunction(L, f);
  472. luax_table_insert(L, -2, -1, pos);
  473. lua_pop(L, 3);
  474. return 0;
  475. }
  476. void luax_rawnewtype(lua_State *L, love::Type &type, love::Object *object)
  477. {
  478. Proxy *u = (Proxy *)lua_newuserdata(L, sizeof(Proxy));
  479. object->retain();
  480. u->object = object;
  481. u->type = &type;
  482. const char *name = type.getName();
  483. luaL_newmetatable(L, name);
  484. lua_getfield(L, -1, "__gc");
  485. bool has_gc = !lua_isnoneornil(L, -1);
  486. lua_pop(L, 1);
  487. // Make sure mt.__gc exists, so Lua states which don't have the object's
  488. // module loaded will still clean the object up when it's collected.
  489. if (!has_gc)
  490. {
  491. lua_pushcfunction(L, w__gc);
  492. lua_setfield(L, -2, "__gc");
  493. }
  494. lua_setmetatable(L, -2);
  495. }
  496. void luax_pushtype(lua_State *L, love::Type &type, love::Object *object)
  497. {
  498. if (object == nullptr)
  499. {
  500. lua_pushnil(L);
  501. return;
  502. }
  503. // Fetch the registry table of instantiated objects.
  504. luax_getregistry(L, REGISTRY_OBJECTS);
  505. // The table might not exist - it should be insisted in luax_register_type.
  506. if (lua_isnoneornil(L, -1))
  507. {
  508. lua_pop(L, 1);
  509. return luax_rawnewtype(L, type, object);
  510. }
  511. lua_Number objectkey = luax_computeloveobjectkey(L, object);
  512. // Get the value of loveobjects[object] on the stack.
  513. lua_pushnumber(L, objectkey);
  514. lua_gettable(L, -2);
  515. // If the Proxy userdata isn't in the instantiated types table yet, add it.
  516. if (lua_type(L, -1) != LUA_TUSERDATA)
  517. {
  518. lua_pop(L, 1);
  519. luax_rawnewtype(L, type, object);
  520. lua_pushnumber(L, objectkey);
  521. lua_pushvalue(L, -2);
  522. // loveobjects[object] = Proxy.
  523. lua_settable(L, -4);
  524. }
  525. // Remove the loveobjects table from the stack.
  526. lua_remove(L, -2);
  527. // Keep the Proxy userdata on the stack.
  528. }
  529. bool luax_istype(lua_State *L, int idx, love::Type &type)
  530. {
  531. if (lua_type(L, idx) != LUA_TUSERDATA)
  532. return false;
  533. Proxy *p = (Proxy *) lua_touserdata(L, idx);
  534. if (p->type != nullptr)
  535. return p->type->isa(type);
  536. else
  537. return false;
  538. }
  539. static Proxy *tryextractproxy(lua_State *L, int idx)
  540. {
  541. Proxy *u = (Proxy *)lua_touserdata(L, idx);
  542. if (u == nullptr || u->type == nullptr)
  543. return nullptr;
  544. // We could get rid of the dynamic_cast for more performance, but it would
  545. // be less safe...
  546. if (dynamic_cast<Object *>(u->object) != nullptr)
  547. return u;
  548. return nullptr;
  549. }
  550. Variant luax_checkvariant(lua_State *L, int n, bool allowuserdata, std::set<const void*> *tableSet)
  551. {
  552. size_t len;
  553. const char *str;
  554. Proxy *p = nullptr;
  555. if (n < 0) // Fix the stack position, we might modify it later
  556. n += lua_gettop(L) + 1;
  557. switch (lua_type(L, n))
  558. {
  559. case LUA_TBOOLEAN:
  560. return Variant(luax_toboolean(L, n));
  561. case LUA_TNUMBER:
  562. return Variant(lua_tonumber(L, n));
  563. case LUA_TSTRING:
  564. str = lua_tolstring(L, n, &len);
  565. return Variant(str, len);
  566. case LUA_TLIGHTUSERDATA:
  567. return Variant(lua_touserdata(L, n));
  568. case LUA_TUSERDATA:
  569. if (!allowuserdata)
  570. {
  571. luax_typerror(L, n, "copyable Lua value");
  572. return Variant();
  573. }
  574. p = tryextractproxy(L, n);
  575. if (p != nullptr)
  576. return Variant(p->type, p->object);
  577. else
  578. {
  579. luax_typerror(L, n, "love type");
  580. return Variant();
  581. }
  582. case LUA_TNIL:
  583. return Variant();
  584. case LUA_TTABLE:
  585. {
  586. bool success = true;
  587. std::set<const void *> topTableSet;
  588. // We can use a pointer to a stack-allocated variable because it's
  589. // never used after the stack-allocated variable is destroyed.
  590. if (tableSet == nullptr)
  591. tableSet = &topTableSet;
  592. // Now make sure this table wasn't already serialised
  593. const void *tablePointer = lua_topointer(L, n);
  594. {
  595. auto result = tableSet->insert(tablePointer);
  596. if (!result.second) // insertion failed
  597. throw love::Exception("Cycle detected in table");
  598. }
  599. Variant::SharedTable *table = new Variant::SharedTable();
  600. size_t len = luax_objlen(L, -1);
  601. if (len > 0)
  602. table->pairs.reserve(len);
  603. lua_pushnil(L);
  604. while (lua_next(L, n))
  605. {
  606. table->pairs.emplace_back(
  607. luax_checkvariant(L, -2, allowuserdata, tableSet),
  608. luax_checkvariant(L, -1, allowuserdata, tableSet)
  609. );
  610. lua_pop(L, 1);
  611. const auto &p = table->pairs.back();
  612. if (p.first.getType() == Variant::UNKNOWN || p.second.getType() == Variant::UNKNOWN)
  613. {
  614. success = false;
  615. break;
  616. }
  617. }
  618. // And remove the table from the set again
  619. tableSet->erase(tablePointer);
  620. if (success)
  621. return Variant(table);
  622. else
  623. table->release();
  624. }
  625. break;
  626. }
  627. return Variant::unknown();
  628. }
  629. void luax_pushvariant(lua_State *L, const Variant &v)
  630. {
  631. const Variant::Data &data = v.getData();
  632. switch (v.getType())
  633. {
  634. case Variant::BOOLEAN:
  635. lua_pushboolean(L, data.boolean);
  636. break;
  637. case Variant::NUMBER:
  638. lua_pushnumber(L, data.number);
  639. break;
  640. case Variant::STRING:
  641. lua_pushlstring(L, data.string->str, data.string->len);
  642. break;
  643. case Variant::SMALLSTRING:
  644. lua_pushlstring(L, data.smallstring.str, data.smallstring.len);
  645. break;
  646. case Variant::LUSERDATA:
  647. lua_pushlightuserdata(L, data.userdata);
  648. break;
  649. case Variant::LOVEOBJECT:
  650. luax_pushtype(L, *data.objectproxy.type, data.objectproxy.object);
  651. break;
  652. case Variant::TABLE:
  653. {
  654. std::vector<std::pair<Variant, Variant>> &table = data.table->pairs;
  655. int tsize = (int) table.size();
  656. lua_createtable(L, 0, tsize);
  657. for (int i = 0; i < tsize; ++i)
  658. {
  659. std::pair<Variant, Variant> &kv = table[i];
  660. luax_pushvariant(L, kv.first);
  661. luax_pushvariant(L, kv.second);
  662. lua_settable(L, -3);
  663. }
  664. break;
  665. }
  666. case Variant::NIL:
  667. default:
  668. lua_pushnil(L);
  669. break;
  670. }
  671. }
  672. int luax_getfunction(lua_State *L, const char *mod, const char *fn)
  673. {
  674. lua_getglobal(L, "love");
  675. if (lua_isnil(L, -1)) return luaL_error(L, "Could not find global love!");
  676. lua_getfield(L, -1, mod);
  677. if (lua_isnil(L, -1)) return luaL_error(L, "Could not find love.%s!", mod);
  678. lua_getfield(L, -1, fn);
  679. if (lua_isnil(L, -1)) return luaL_error(L, "Could not find love.%s.%s!", mod, fn);
  680. lua_remove(L, -2); // remove mod
  681. lua_remove(L, -2); // remove fn
  682. return 0;
  683. }
  684. int luax_convobj(lua_State *L, int idx, const char *mod, const char *fn)
  685. {
  686. // Convert to absolute index if necessary.
  687. if (idx < 0 && idx > LUA_REGISTRYINDEX)
  688. idx += lua_gettop(L) + 1;
  689. // Convert string to a file.
  690. luax_getfunction(L, mod, fn);
  691. lua_pushvalue(L, idx); // The initial argument.
  692. lua_call(L, 1, 2); // Call the function, one arg, one return value (plus optional errstring.)
  693. luax_assert_nilerror(L, -2); // Make sure the function returned something.
  694. lua_pop(L, 1); // Pop the second return value now that we don't need it.
  695. lua_replace(L, idx); // Replace the initial argument with the new object.
  696. return 0;
  697. }
  698. int luax_convobj(lua_State *L, const int idxs[], int n, const char *mod, const char *fn)
  699. {
  700. luax_getfunction(L, mod, fn);
  701. for (int i = 0; i < n; i++)
  702. {
  703. lua_pushvalue(L, idxs[i]); // The arguments.
  704. }
  705. lua_call(L, n, 2); // Call the function, n args, one return value (plus optional errstring.)
  706. luax_assert_nilerror(L, -2); // Make sure the function returned something.
  707. lua_pop(L, 1); // Pop the second return value now that we don't need it.
  708. if (n > 0)
  709. lua_replace(L, idxs[0]); // Replace the initial argument with the new object.
  710. return 0;
  711. }
  712. int luax_convobj(lua_State *L, const std::vector<int>& idxs, const char *module, const char *function)
  713. {
  714. const int *idxPtr = idxs.size() > 0 ? &idxs[0] : nullptr;
  715. return luax_convobj(L, idxPtr, (int) idxs.size(), module, function);
  716. }
  717. int luax_pconvobj(lua_State *L, int idx, const char *mod, const char *fn)
  718. {
  719. // Convert string to a file.
  720. luax_getfunction(L, mod, fn);
  721. lua_pushvalue(L, idx); // The initial argument.
  722. int ret = lua_pcall(L, 1, 1, 0); // Call the function, one arg, one return value.
  723. if (ret == 0)
  724. lua_replace(L, idx); // Replace the initial argument with the new object.
  725. return ret;
  726. }
  727. int luax_pconvobj(lua_State *L, const int idxs[], int n, const char *mod, const char *fn)
  728. {
  729. luax_getfunction(L, mod, fn);
  730. for (int i = 0; i < n; i++)
  731. {
  732. lua_pushvalue(L, idxs[i]); // The arguments.
  733. }
  734. int ret = lua_pcall(L, n, 1, 0); // Call the function, n args, one return value.
  735. if (ret == 0)
  736. lua_replace(L, idxs[0]); // Replace the initial argument with the new object.
  737. return ret;
  738. }
  739. int luax_pconvobj(lua_State *L, const std::vector<int>& idxs, const char *module, const char *function)
  740. {
  741. const int *idxPtr = idxs.size() > 0 ? &idxs[0] : nullptr;
  742. return luax_pconvobj(L, idxPtr, (int) idxs.size(), module, function);
  743. }
  744. int luax_insist(lua_State *L, int idx, const char *k)
  745. {
  746. // Convert to absolute index if necessary.
  747. if (idx < 0 && idx > LUA_REGISTRYINDEX)
  748. idx += lua_gettop(L) + 1;
  749. lua_getfield(L, idx, k);
  750. // Create if necessary.
  751. if (!lua_istable(L, -1))
  752. {
  753. lua_pop(L, 1); // Pop the non-table.
  754. lua_newtable(L);
  755. lua_pushvalue(L, -1); // Duplicate the table to leave on top.
  756. lua_setfield(L, idx, k); // lua_stack[idx][k] = lua_stack[-1] (table)
  757. }
  758. return 1;
  759. }
  760. int luax_insistglobal(lua_State *L, const char *k)
  761. {
  762. lua_getglobal(L, k);
  763. if (!lua_istable(L, -1))
  764. {
  765. lua_pop(L, 1); // Pop the non-table.
  766. lua_newtable(L);
  767. lua_pushvalue(L, -1);
  768. lua_setglobal(L, k);
  769. }
  770. return 1;
  771. }
  772. int luax_c_insistglobal(lua_State *L, const char *k)
  773. {
  774. return luax_insistglobal(L, k);
  775. }
  776. int luax_insistlove(lua_State *L, const char *k)
  777. {
  778. luax_insistglobal(L, "love");
  779. luax_insist(L, -1, k);
  780. // The love table should be replaced with the top stack
  781. // item. Only the reqested table should remain on the stack.
  782. lua_replace(L, -2);
  783. return 1;
  784. }
  785. int luax_getlove(lua_State *L, const char *k)
  786. {
  787. lua_getglobal(L, "love");
  788. if (!lua_isnil(L, -1))
  789. {
  790. lua_getfield(L, -1, k);
  791. lua_replace(L, -2);
  792. }
  793. return 1;
  794. }
  795. int luax_insistregistry(lua_State *L, Registry r)
  796. {
  797. switch (r)
  798. {
  799. case REGISTRY_MODULES:
  800. return luax_insistlove(L, "_modules");
  801. case REGISTRY_OBJECTS:
  802. return luax_insist(L, LUA_REGISTRYINDEX, "_loveobjects");
  803. default:
  804. return luaL_error(L, "Attempted to use invalid registry.");
  805. }
  806. }
  807. int luax_getregistry(lua_State *L, Registry r)
  808. {
  809. switch (r)
  810. {
  811. case REGISTRY_MODULES:
  812. return luax_getlove(L, "_modules");
  813. case REGISTRY_OBJECTS:
  814. lua_getfield(L, LUA_REGISTRYINDEX, "_loveobjects");
  815. return 1;
  816. default:
  817. return luaL_error(L, "Attempted to use invalid registry.");
  818. }
  819. }
  820. static const char *MAIN_THREAD_KEY = "_love_mainthread";
  821. lua_State *luax_insistpinnedthread(lua_State *L)
  822. {
  823. lua_getfield(L, LUA_REGISTRYINDEX, MAIN_THREAD_KEY);
  824. if (lua_isnoneornil(L, -1))
  825. {
  826. lua_pop(L, 1);
  827. // lua_pushthread returns 1 if it's actually the main thread, but we
  828. // can't actually get the real main thread if lua_pushthread doesn't
  829. // return it (in Lua 5.1 at least), so we ignore that for now...
  830. // We do store a strong reference to the current thread/coroutine in
  831. // the registry, however.
  832. lua_pushthread(L);
  833. lua_pushvalue(L, -1);
  834. lua_setfield(L, LUA_REGISTRYINDEX, MAIN_THREAD_KEY);
  835. }
  836. lua_State *thread = lua_tothread(L, -1);
  837. lua_pop(L, 1);
  838. return thread;
  839. }
  840. lua_State *luax_getpinnedthread(lua_State *L)
  841. {
  842. lua_getfield(L, LUA_REGISTRYINDEX, MAIN_THREAD_KEY);
  843. lua_State *thread = lua_tothread(L, -1);
  844. lua_pop(L, 1);
  845. return thread;
  846. }
  847. void luax_markdeprecated(lua_State *L, const char *name, APIType api)
  848. {
  849. luax_markdeprecated(L, name, api, DEPRECATED_NO_REPLACEMENT, nullptr);
  850. }
  851. void luax_markdeprecated(lua_State *L, const char *name, APIType api, DeprecationType type, const char *replacement)
  852. {
  853. MarkDeprecated deprecated(name, api, type, replacement);
  854. if (deprecated.info != nullptr && deprecated.info->uses == 1)
  855. {
  856. luaL_where(L, 1);
  857. const char *where = lua_tostring(L, -1);
  858. if (where != nullptr)
  859. deprecated.info->where = where;
  860. lua_pop(L, 1);
  861. }
  862. }
  863. extern "C" int luax_typerror(lua_State *L, int narg, const char *tname)
  864. {
  865. int argtype = lua_type(L, narg);
  866. const char *argtname = nullptr;
  867. // We want to use the love type name for userdata, if possible.
  868. if (argtype == LUA_TUSERDATA && luaL_getmetafield(L, narg, "type") != 0)
  869. {
  870. lua_pushvalue(L, narg);
  871. if (lua_pcall(L, 1, 1, 0) == 0 && lua_type(L, -1) == LUA_TSTRING)
  872. {
  873. argtname = lua_tostring(L, -1);
  874. // Non-love userdata might have a type metamethod which doesn't
  875. // describe its type properly, so we only use it for love types.
  876. if (!Type::byName(argtname))
  877. argtname = nullptr;
  878. }
  879. }
  880. if (argtname == nullptr)
  881. argtname = lua_typename(L, argtype);
  882. const char *msg = lua_pushfstring(L, "%s expected, got %s", tname, argtname);
  883. return luaL_argerror(L, narg, msg);
  884. }
  885. int luax_enumerror(lua_State *L, const char *enumName, const char *value)
  886. {
  887. return luaL_error(L, "Invalid %s: %s", enumName, value);
  888. }
  889. int luax_enumerror(lua_State *L, const char *enumName, const std::vector<std::string> &values, const char *value)
  890. {
  891. std::stringstream valueStream;
  892. bool first = true;
  893. for (auto value : values)
  894. {
  895. valueStream << (first ? "'" : ", '") << value << "'";
  896. first = false;
  897. }
  898. std::string valueString = valueStream.str();
  899. return luaL_error(L, "Invalid %s '%s', expected one of: %s", enumName, value, valueString.c_str());
  900. }
  901. size_t luax_objlen(lua_State *L, int ndx)
  902. {
  903. #if LUA_VERSION_NUM == 501
  904. return lua_objlen(L, ndx);
  905. #else
  906. return lua_rawlen(L, ndx);
  907. #endif
  908. }
  909. void luax_register(lua_State *L, const char *name, const luaL_Reg *l)
  910. {
  911. if (name)
  912. lua_newtable(L);
  913. luax_setfuncs(L, l);
  914. if (name)
  915. {
  916. lua_pushvalue(L, -1);
  917. lua_setglobal(L, name);
  918. }
  919. }
  920. void luax_runwrapper(lua_State *L, const char *filedata, size_t datalen, const char *filename, const love::Type &type, void *ffifuncs)
  921. {
  922. luax_gettypemetatable(L, type);
  923. // Load and execute the given Lua file, sending the metatable and the ffi
  924. // functions struct pointer as arguments.
  925. if (lua_istable(L, -1))
  926. {
  927. luaL_loadbuffer(L, filedata, datalen, filename);
  928. lua_pushvalue(L, -2);
  929. if (ffifuncs != nullptr)
  930. luax_pushpointerasstring(L, ffifuncs);
  931. else
  932. lua_pushnil(L);
  933. lua_call(L, 2, 0);
  934. }
  935. // Pop the metatable.
  936. lua_pop(L, 1);
  937. }
  938. Type *luax_type(lua_State *L, int idx)
  939. {
  940. return Type::byName(luaL_checkstring(L, idx));
  941. }
  942. int luax_resume(lua_State *L, int nargs)
  943. {
  944. #if LUA_VERSION_NUM >= 502
  945. return lua_resume(L, nullptr, nargs);
  946. #else
  947. return lua_resume(L, nargs);
  948. #endif
  949. }
  950. } // love