runtime.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. /**
  2. * Copyright (c) 2006-2016 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. #ifndef LOVE_RUNTIME_H
  21. #define LOVE_RUNTIME_H
  22. // LOVE
  23. #include "types.h"
  24. // Lua
  25. extern "C" {
  26. #define LUA_COMPAT_ALL
  27. #include <lua.h>
  28. #include <lualib.h>
  29. #include <lauxlib.h>
  30. }
  31. // C++
  32. #include <exception>
  33. namespace love
  34. {
  35. // Forward declarations.
  36. class Object;
  37. class Module;
  38. class Reference;
  39. /**
  40. * Registries represent special tables which can be accessed with
  41. * luax_insistregistry and luax_getregistry.
  42. **/
  43. enum Registry
  44. {
  45. REGISTRY_MODULES,
  46. REGISTRY_OBJECTS
  47. };
  48. /**
  49. * This structure wraps all Lua-exposed objects. It exists in the
  50. * Lua state as a full userdata (so we can catch __gc "events"),
  51. * though the Object it refers to is light userdata in the sense
  52. * that it is not allocated by the Lua VM.
  53. **/
  54. struct Proxy
  55. {
  56. // Holds type information (see types.h).
  57. Type type;
  58. // Pointer to the actual object.
  59. Object *object;
  60. };
  61. /**
  62. * A Module with Lua wrapper functions and other data.
  63. **/
  64. struct WrappedModule
  65. {
  66. // The module containing the functions.
  67. Module *module;
  68. // The name for the table to put the functions in, without the 'love'-prefix.
  69. const char *name;
  70. // The type of this module.
  71. love::Type type;
  72. // The functions of the module (last element {0,0}).
  73. const luaL_Reg *functions;
  74. // A list of functions which expose the types of the modules (last element 0).
  75. const lua_CFunction *types;
  76. };
  77. /**
  78. * Returns a reference to the top stack element (-1) if the value
  79. * is of the specified type. If the value is incorrect, zero is returned.
  80. *
  81. * In any case, the top stack element is popped, regardless of its type.
  82. **/
  83. Reference *luax_refif(lua_State *L, int type);
  84. /**
  85. * Prints the current contents of the stack. Only useful for debugging.
  86. * @param L The Lua state.
  87. **/
  88. void luax_printstack(lua_State *L);
  89. /**
  90. * Converts the value at idx to a bool. It follow the same rules
  91. * as lua_toboolean, but returns a bool instead of an int.
  92. * @param L The Lua state.
  93. * @param idx The index on the Lua stack.
  94. * @return True if the value evaluates to true, false otherwise.
  95. **/
  96. bool luax_toboolean(lua_State *L, int idx);
  97. /**
  98. * Pushes a bool onto the stack. It's the same as lua_pushboolean,
  99. * but with bool instead of int.
  100. * @param L The Lua state.
  101. * @param b The bool to push.
  102. **/
  103. void luax_pushboolean(lua_State *L, bool b);
  104. /**
  105. * Converts the value at idx to a bool, or if not present, b is returned.
  106. * @param L The Lua state.
  107. * @param idx The index of the Lua stack.
  108. * @param b The value to return if no value exist at the specified index.
  109. * @return True if the value evaluates to true, false otherwise.
  110. **/
  111. bool luax_optboolean(lua_State *L, int idx, bool b);
  112. /**
  113. * Converts the value at idx to a std::string. It takes care of the string
  114. * size and possible embedded nulls.
  115. * @param L The Lua state.
  116. * @param idx The index on the Lua stack.
  117. * @return Copy of the string at the specified index.
  118. **/
  119. std::string luax_tostring(lua_State *L, int idx);
  120. /**
  121. * Converts the value at idx to a std::string. It takes care of the string
  122. * size and possible embedded nulls.
  123. * @param L The Lua state.
  124. * @param idx The index on the Lua stack.
  125. * @return Copy of the string at the specified index.
  126. **/
  127. std::string luax_checkstring(lua_State *L, int idx);
  128. /**
  129. * Pushes a std::string onto the stack. It uses the length of the string
  130. * for lua_pushlstring's len argument.
  131. * @param L The Lua state.
  132. * @param str The string to push.
  133. **/
  134. void luax_pushstring(lua_State *L, const std::string &str);
  135. bool luax_boolflag(lua_State *L, int table_index, const char *key, bool defaultValue);
  136. int luax_intflag(lua_State *L, int table_index, const char *key, int defaultValue);
  137. /**
  138. * Convert the value at the specified index to an Lua number, and then
  139. * convert to a float.
  140. *
  141. * @param L The Lua state.
  142. * @param idx The index on the stack.
  143. */
  144. inline float luax_tofloat(lua_State *L, int idx)
  145. {
  146. return static_cast<float>(lua_tonumber(L, idx));
  147. }
  148. /**
  149. * Like luax_tofloat, but checks that the value is a number.
  150. *
  151. * @see luax_tofloat
  152. */
  153. inline float luax_checkfloat(lua_State *L, int idx)
  154. {
  155. return static_cast<float>(luaL_checknumber(L, idx));
  156. }
  157. /**
  158. * Require at least 'min' number of items on the stack.
  159. * @param L The Lua state.
  160. * @param min The minimum number of items on the stack.
  161. * @return Zero if conditions are met, otherwise a Lua error (longjmp).
  162. **/
  163. int luax_assert_argc(lua_State *L, int min);
  164. /**
  165. * Require at least 'min', but more than 'max' items on the stack.
  166. * @param L The Lua state.
  167. * @param min The minimum number of items on the stack.
  168. * @param max The maximum number of items on the stack.
  169. * @return Zero if conditions are met, otherwise a Lua error (longjmp).
  170. **/
  171. int luax_assert_argc(lua_State *L, int min, int max);
  172. /**
  173. * Require that the value at idx is a function.
  174. * @param L The Lua state.
  175. *@param idx The index on the stack.
  176. **/
  177. int luax_assert_function(lua_State *L, int idx);
  178. /**
  179. * Require that the value at idx is not nil. If it is, the function throws an
  180. * error using an optional error string at idx+1.
  181. * @param L The Lua state.
  182. * @param idx The index on the stack.
  183. **/
  184. int luax_assert_nilerror(lua_State *L, int idx);
  185. /**
  186. * Registers all functions in the array l (see luaL_Reg) into the table at the
  187. * top of the stack.
  188. * Similar to Lua 5.2's luaL_setfuncs without the upvalues, and to Lua 5.1's
  189. * luaL_register without the library name.
  190. **/
  191. void luax_setfuncs(lua_State *L, const luaL_Reg *l);
  192. /**
  193. * Loads a Lua module using the 'require' function. Leaves the return result on
  194. * the stack.
  195. * @param name The name of the module to require.
  196. **/
  197. int luax_require(lua_State *L, const char *name);
  198. /**
  199. * Register a module in the love table. The love table will be created if it does not exist.
  200. * NOTE: The module-object is expected to have a +1 reference count before calling
  201. * this function, as it doesn't retain the object itself but Lua will release it
  202. * upon garbage collection.
  203. * @param L The Lua state.
  204. **/
  205. int luax_register_module(lua_State *L, const WrappedModule &m);
  206. /**
  207. * Inserts a module with 'name' into the package.preloaded table.
  208. * @param f The function to be called when the module is opened.
  209. * @param name The name of the module, with 'love'-prefix, for instance 'love.graphics'.
  210. **/
  211. int luax_preload(lua_State *L, lua_CFunction f, const char *name);
  212. /**
  213. * Register a new type.
  214. * @param type The type.
  215. * @param name The type's human-readable name
  216. * @param ... The list of lists of member functions for the type. (of type luaL_Reg*)
  217. **/
  218. int luax_register_type(lua_State *L, love::Type type, const char *name, ...);
  219. /**
  220. * Pushes the metatable of the specified type onto the stack.
  221. **/
  222. void luax_gettypemetatable(lua_State *L, love::Type type);
  223. /**
  224. * Do a table.insert from C
  225. * @param L the state
  226. * @param tindex the stack index of the table
  227. * @param vindex the stack index of the value
  228. * @param pos the position to insert it in
  229. **/
  230. int luax_table_insert(lua_State *L, int tindex, int vindex, int pos = -1);
  231. /**
  232. * Register a new searcher function for package.loaders. This can for instance enable
  233. * loading of files through love.filesystem using standard require.
  234. * @param L The Lua state.
  235. * @param f The searcher function.
  236. * @param pos The position to insert the loader in.
  237. **/
  238. int luax_register_searcher(lua_State *L, lua_CFunction f, int pos = -1);
  239. /**
  240. * Pushes a Lua representation of the given object onto the stack, creating and
  241. * storing the Lua representation in a weak table if it doesn't exist yet.
  242. * NOTE: The object will be retained by Lua and released upon garbage collection.
  243. * @param L The Lua state.
  244. * @param type The type information of the object.
  245. * @param object The pointer to the actual object.
  246. **/
  247. void luax_pushtype(lua_State *L, const love::Type type, love::Object *object);
  248. /**
  249. * Creates a new Lua representation of the given object *without* checking if it
  250. * exists yet, and *without* storing it in a weak table.
  251. * This should only be used when performance is an extreme concern and the
  252. * object is not ever expected to be pushed to Lua again, as it prevents the
  253. * Lua-side objects from working in some cases when used as keys in tables.
  254. * NOTE: The object will be retained by Lua and released upon garbage collection.
  255. * @param L The Lua state.
  256. * @param type The type information of the object.
  257. * @param object The pointer to the actual object.
  258. **/
  259. void luax_rawnewtype(lua_State *L, love::Type type, love::Object *object);
  260. /**
  261. * Checks whether the value at idx is a certain type.
  262. * @param L The Lua state.
  263. * @param idx The index on the stack.
  264. * @param type The type to check for.
  265. * @return True if the value is Proxy of the specified type, false otherwise.
  266. **/
  267. bool luax_istype(lua_State *L, int idx, love::Type type);
  268. /**
  269. * Gets the function love.module.function and puts it on top of the stack (alone). If the
  270. * love table, the module, or the function does not exist, an error is returned.
  271. * @return An error if nonexistent, or 1 if successful.
  272. **/
  273. int luax_getfunction(lua_State *L, const char *module, const char *function);
  274. /**
  275. * Converts an object into another object by the specified function love.module.function.
  276. * The conversion function must accept a single object of the relevant type as a parameter,
  277. * and returnone value. If the function does not exist (see luax_getfunction), an error is returned.
  278. *
  279. * Note that the initial object at idx is replaced by the new object.
  280. *
  281. * @param L The Lua state.
  282. * @param idx The index on the stack.
  283. * @param module The module in the love table.
  284. * @param function The function in the module.
  285. **/
  286. int luax_convobj(lua_State *L, int idx, const char *module, const char *function);
  287. /**
  288. * Converts an object into another object by the specified function love.module.function.
  289. * The conversion function must accept a single object of the relevant type as its first parameter,
  290. * and return one value. If the function does not exist (see luax_getfunction), an error is returned.
  291. *
  292. * Note that the initial object at idx is replaced by the new object.
  293. *
  294. * @param L The Lua state.
  295. * @param idxs An array of indices on the stack.
  296. * @param n How many arguments are being passed.
  297. * @param module The module in the love table.
  298. * @param function The function in the module.
  299. **/
  300. int luax_convobj(lua_State *L, int idxs[], int n, const char *module, const char *function);
  301. // pcall versions of the above
  302. int luax_pconvobj(lua_State *L, int idx, const char *module, const char *function);
  303. int luax_pconvobj(lua_State *L, int idxs[], int n, const char *module, const char *function);
  304. /**
  305. * 'Insist' that a table 'k' exists in the table at idx. Insistence involves that the
  306. * table (k) is created if it does not exist in the table at idx. The table at idx must
  307. * pre-exist, however. Also note that if the a non-table value exists at the specified
  308. * location, it will be overwritten with a new table. The insisted table, and only the
  309. * insisted table, will be placed on top of the stack.
  310. *
  311. * @param idx The index on the stack containing a table.
  312. * @param k The name of the table we are insisting exist.
  313. **/
  314. int luax_insist(lua_State *L, int idx, const char *k);
  315. /**
  316. * Insist that a global table 'k' exists. See luax_insist.
  317. * @param k The name of the table we are insisting exist.
  318. **/
  319. int luax_insistglobal(lua_State *L, const char *k);
  320. /**
  321. * Insists that a table 'k' exists inside the 'love' table. See luax_insist.
  322. * @param k The name of the table we are insisting exist.
  323. **/
  324. int luax_insistlove(lua_State *L, const char *k);
  325. /**
  326. * Pushes the table 'k' in the love table onto the stack. Pushes nil if the
  327. * table doesn't exist.
  328. * @param k The name of the table we want to get.
  329. **/
  330. int luax_getlove(lua_State *L, const char *k);
  331. /**
  332. * Gets (creates if needed) the specified Registry, and pushes it into the
  333. * stack.
  334. * @param L The Lua state.
  335. * @param r The Registry to get.
  336. **/
  337. int luax_insistregistry(lua_State *L, Registry r);
  338. /**
  339. * Gets the specified Registry, and pushes it onto the stack. Pushes nil if the
  340. * registry hasn't been created (see luax_insistregistry.)
  341. * @param L The Lua state.
  342. * @param r The Registry to get.
  343. **/
  344. int luax_getregistry(lua_State *L, Registry r);
  345. /**
  346. * Gets (and pins if needed) a "pinned" Lua thread (coroutine) in the specified
  347. * Lua state. This will usually be the main Lua thread, unless the first call
  348. * to this function for a specific Lua state is made from within a coroutine.
  349. * NOTE: This does not push anything to the stack.
  350. **/
  351. lua_State *luax_insistpinnedthread(lua_State *L);
  352. /**
  353. * Gets a "pinned" Lua thread (coroutine) in the specified Lua state. This will
  354. * usually be the main Lua thread. This can be used to access global variables
  355. * in a specific Lua state without needing another alive lua_State value.
  356. * PRECONDITION: luax_insistpinnedthread must have been called on a lua_State
  357. * value corresponding to the Lua state which will be used with this function.
  358. * NOTE: This does not push anything to the stack.
  359. **/
  360. lua_State *luax_getpinnedthread(lua_State *L);
  361. extern "C" { // Also called from luasocket
  362. int luax_typerror(lua_State *L, int narg, const char *tname);
  363. }
  364. /**
  365. * Calls luax_objlen/lua_rawlen depending on version
  366. **/
  367. size_t luax_objlen(lua_State *L, int ndx);
  368. extern "C" { // Called by enet and luasocket
  369. void luax_register(lua_State *L, const char *name, const luaL_Reg *l);
  370. int luax_c_insistglobal(lua_State *L, const char *k);
  371. }
  372. /**
  373. * Like luax_totype, but causes an error if the value at idx is not Proxy,
  374. * or is not the specified type.
  375. * @param L The Lua state.
  376. * @param idx The index on the stack.
  377. * @param type The type bit.
  378. **/
  379. template <typename T>
  380. T *luax_checktype(lua_State *L, int idx, love::Type type)
  381. {
  382. if (lua_type(L, idx) != LUA_TUSERDATA)
  383. {
  384. const char *name = "Invalid";
  385. getTypeName(type, name);
  386. luax_typerror(L, idx, name);
  387. }
  388. Proxy *u = (Proxy *)lua_touserdata(L, idx);
  389. if (u->type <= INVALID_ID || u->type >= TYPE_MAX_ENUM || !typeFlags[u->type][type])
  390. {
  391. const char *name = "Invalid";
  392. getTypeName(type, name);
  393. luax_typerror(L, idx, name);
  394. }
  395. return (T *)u->object;
  396. }
  397. template <typename T>
  398. T *luax_getmodule(lua_State *L, love::Type type)
  399. {
  400. const char *name = "Invalid";
  401. getTypeName(type, name);
  402. luax_insistregistry(L, REGISTRY_MODULES);
  403. lua_getfield(L, -1, name);
  404. if (!lua_isuserdata(L, -1))
  405. luaL_error(L, "Tried to get nonexistent module %s.", name);
  406. Proxy *u = (Proxy *)lua_touserdata(L, -1);
  407. if (u->type <= INVALID_ID || u->type >= TYPE_MAX_ENUM || !typeFlags[u->type][type])
  408. luaL_error(L, "Incorrect module %s", name);
  409. lua_pop(L, 2);
  410. return (T *)u->object;
  411. }
  412. template <typename T>
  413. T *luax_optmodule(lua_State *L, love::Type type)
  414. {
  415. const char *name = "Invalid";
  416. getTypeName(type, name);
  417. luax_insistregistry(L, REGISTRY_MODULES);
  418. lua_getfield(L, -1, name);
  419. if (!lua_isuserdata(L, -1))
  420. {
  421. lua_pop(L, 2);
  422. return 0;
  423. }
  424. Proxy *u = (Proxy *)lua_touserdata(L, -1);
  425. if (!typeFlags[u->type][type])
  426. luaL_error(L, "Incorrect module %s", name);
  427. lua_pop(L, 2);
  428. return (T *) u->object;
  429. }
  430. /**
  431. * Converts the value at idx to the specified type without checking that
  432. * this conversion is valid. If the type has been previously verified with
  433. * luax_istype, then this can be safely used. Otherwise, use luax_checktype.
  434. * @param L The Lua state.
  435. * @param idx The index on the stack.
  436. * @param type The type of the object.
  437. **/
  438. template <typename T>
  439. T *luax_totype(lua_State *L, int idx, love::Type /*type*/)
  440. {
  441. return (T *)(((Proxy *)lua_touserdata(L, idx))->object);
  442. }
  443. Type luax_type(lua_State *L, int idx);
  444. /**
  445. * Converts any exceptions thrown by the passed lambda function into a Lua error.
  446. * lua_error (and luaL_error) cannot be called from inside the exception handler
  447. * because they use longjmp, which causes undefined behaviour when the
  448. * destructor of the exception would have been called.
  449. **/
  450. template <typename T>
  451. int luax_catchexcept(lua_State *L, const T& func)
  452. {
  453. bool should_error = false;
  454. try
  455. {
  456. func();
  457. }
  458. catch (const std::exception &e)
  459. {
  460. should_error = true;
  461. lua_pushstring(L, e.what());
  462. }
  463. if (should_error)
  464. return luaL_error(L, "%s", lua_tostring(L, -1));
  465. return 0;
  466. }
  467. template <typename T, typename F>
  468. int luax_catchexcept(lua_State *L, const T& func, const F& finallyfunc)
  469. {
  470. bool should_error = false;
  471. try
  472. {
  473. func();
  474. }
  475. catch (const std::exception &e)
  476. {
  477. should_error = true;
  478. lua_pushstring(L, e.what());
  479. }
  480. finallyfunc(should_error);
  481. if (should_error)
  482. return luaL_error(L, "%s", lua_tostring(L, -1));
  483. return 0;
  484. }
  485. } // love
  486. #endif // LOVE_RUNTIME_H