lauxlib.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. /*
  2. ** $Id: lauxlib.c,v 1.257 2014/02/05 19:14:53 roberto Exp roberto $
  3. ** Auxiliary functions for building Lua libraries
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <errno.h>
  7. #include <stdarg.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. /* This file uses only the official API of Lua.
  12. ** Any function declared here could be written as an application function.
  13. */
  14. #define lauxlib_c
  15. #define LUA_LIB
  16. #include "lua.h"
  17. #include "lauxlib.h"
  18. /*
  19. ** {======================================================
  20. ** Traceback
  21. ** =======================================================
  22. */
  23. #define LEVELS1 12 /* size of the first part of the stack */
  24. #define LEVELS2 10 /* size of the second part of the stack */
  25. /*
  26. ** search for 'objidx' in table at index -1.
  27. ** return 1 + string at top if find a good name.
  28. */
  29. static int findfield (lua_State *L, int objidx, int level) {
  30. if (level == 0 || !lua_istable(L, -1))
  31. return 0; /* not found */
  32. lua_pushnil(L); /* start 'next' loop */
  33. while (lua_next(L, -2)) { /* for each pair in table */
  34. if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
  35. if (lua_rawequal(L, objidx, -1)) { /* found object? */
  36. lua_pop(L, 1); /* remove value (but keep name) */
  37. return 1;
  38. }
  39. else if (findfield(L, objidx, level - 1)) { /* try recursively */
  40. lua_remove(L, -2); /* remove table (but keep name) */
  41. lua_pushliteral(L, ".");
  42. lua_insert(L, -2); /* place '.' between the two names */
  43. lua_concat(L, 3);
  44. return 1;
  45. }
  46. }
  47. lua_pop(L, 1); /* remove value */
  48. }
  49. return 0; /* not found */
  50. }
  51. static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
  52. int top = lua_gettop(L);
  53. lua_getinfo(L, "f", ar); /* push function */
  54. lua_pushglobaltable(L);
  55. if (findfield(L, top + 1, 2)) {
  56. lua_copy(L, -1, top + 1); /* move name to proper place */
  57. lua_pop(L, 2); /* remove pushed values */
  58. return 1;
  59. }
  60. else {
  61. lua_settop(L, top); /* remove function and global table */
  62. return 0;
  63. }
  64. }
  65. static void pushfuncname (lua_State *L, lua_Debug *ar) {
  66. if (*ar->namewhat != '\0') /* is there a name? */
  67. lua_pushfstring(L, "function " LUA_QS, ar->name);
  68. else if (*ar->what == 'm') /* main? */
  69. lua_pushliteral(L, "main chunk");
  70. else if (*ar->what == 'C') {
  71. if (pushglobalfuncname(L, ar)) {
  72. lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1));
  73. lua_remove(L, -2); /* remove name */
  74. }
  75. else
  76. lua_pushliteral(L, "?");
  77. }
  78. else
  79. lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
  80. }
  81. static int countlevels (lua_State *L) {
  82. lua_Debug ar;
  83. int li = 1, le = 1;
  84. /* find an upper bound */
  85. while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
  86. /* do a binary search */
  87. while (li < le) {
  88. int m = (li + le)/2;
  89. if (lua_getstack(L, m, &ar)) li = m + 1;
  90. else le = m;
  91. }
  92. return le - 1;
  93. }
  94. LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
  95. const char *msg, int level) {
  96. lua_Debug ar;
  97. int top = lua_gettop(L);
  98. int numlevels = countlevels(L1);
  99. int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0;
  100. if (msg) lua_pushfstring(L, "%s\n", msg);
  101. lua_pushliteral(L, "stack traceback:");
  102. while (lua_getstack(L1, level++, &ar)) {
  103. if (level == mark) { /* too many levels? */
  104. lua_pushliteral(L, "\n\t..."); /* add a '...' */
  105. level = numlevels - LEVELS2; /* and skip to last ones */
  106. }
  107. else {
  108. lua_getinfo(L1, "Slnt", &ar);
  109. lua_pushfstring(L, "\n\t%s:", ar.short_src);
  110. if (ar.currentline > 0)
  111. lua_pushfstring(L, "%d:", ar.currentline);
  112. lua_pushliteral(L, " in ");
  113. pushfuncname(L, &ar);
  114. if (ar.istailcall)
  115. lua_pushliteral(L, "\n\t(...tail calls...)");
  116. lua_concat(L, lua_gettop(L) - top);
  117. }
  118. }
  119. lua_concat(L, lua_gettop(L) - top);
  120. }
  121. /* }====================================================== */
  122. /*
  123. ** {======================================================
  124. ** Error-report functions
  125. ** =======================================================
  126. */
  127. LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
  128. lua_Debug ar;
  129. if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
  130. return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
  131. lua_getinfo(L, "n", &ar);
  132. if (strcmp(ar.namewhat, "method") == 0) {
  133. arg--; /* do not count `self' */
  134. if (arg == 0) /* error is in the self argument itself? */
  135. return luaL_error(L, "calling " LUA_QS " on bad self (%s)",
  136. ar.name, extramsg);
  137. }
  138. if (ar.name == NULL)
  139. ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
  140. return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
  141. arg, ar.name, extramsg);
  142. }
  143. static int typeerror (lua_State *L, int arg, const char *tname) {
  144. const char *msg;
  145. const char *typearg = luaL_typename(L, arg);
  146. if (lua_getmetatable(L, arg)) {
  147. lua_getfield(L, -1, "__name");
  148. if (lua_isstring(L, -1))
  149. typearg = lua_tostring(L, -1);
  150. }
  151. msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
  152. return luaL_argerror(L, arg, msg);
  153. }
  154. static void tag_error (lua_State *L, int arg, int tag) {
  155. typeerror(L, arg, lua_typename(L, tag));
  156. }
  157. LUALIB_API void luaL_where (lua_State *L, int level) {
  158. lua_Debug ar;
  159. if (lua_getstack(L, level, &ar)) { /* check function at level */
  160. lua_getinfo(L, "Sl", &ar); /* get info about it */
  161. if (ar.currentline > 0) { /* is there info? */
  162. lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
  163. return;
  164. }
  165. }
  166. lua_pushliteral(L, ""); /* else, no information available... */
  167. }
  168. LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
  169. va_list argp;
  170. va_start(argp, fmt);
  171. luaL_where(L, 1);
  172. lua_pushvfstring(L, fmt, argp);
  173. va_end(argp);
  174. lua_concat(L, 2);
  175. return lua_error(L);
  176. }
  177. LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
  178. int en = errno; /* calls to Lua API may change this value */
  179. if (stat) {
  180. lua_pushboolean(L, 1);
  181. return 1;
  182. }
  183. else {
  184. lua_pushnil(L);
  185. if (fname)
  186. lua_pushfstring(L, "%s: %s", fname, strerror(en));
  187. else
  188. lua_pushstring(L, strerror(en));
  189. lua_pushinteger(L, en);
  190. return 3;
  191. }
  192. }
  193. #if !defined(inspectstat) /* { */
  194. #if defined(LUA_USE_POSIX)
  195. #include <sys/wait.h>
  196. /*
  197. ** use appropriate macros to interpret 'pclose' return status
  198. */
  199. #define inspectstat(stat,what) \
  200. if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
  201. else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
  202. #else
  203. #define inspectstat(stat,what) /* no op */
  204. #endif
  205. #endif /* } */
  206. LUALIB_API int luaL_execresult (lua_State *L, int stat) {
  207. const char *what = "exit"; /* type of termination */
  208. if (stat == -1) /* error? */
  209. return luaL_fileresult(L, 0, NULL);
  210. else {
  211. inspectstat(stat, what); /* interpret result */
  212. if (*what == 'e' && stat == 0) /* successful termination? */
  213. lua_pushboolean(L, 1);
  214. else
  215. lua_pushnil(L);
  216. lua_pushstring(L, what);
  217. lua_pushinteger(L, stat);
  218. return 3; /* return true/nil,what,code */
  219. }
  220. }
  221. /* }====================================================== */
  222. /*
  223. ** {======================================================
  224. ** Userdata's metatable manipulation
  225. ** =======================================================
  226. */
  227. LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
  228. luaL_getmetatable(L, tname); /* try to get metatable */
  229. if (!lua_isnil(L, -1)) /* name already in use? */
  230. return 0; /* leave previous value on top, but return 0 */
  231. lua_pop(L, 1);
  232. lua_newtable(L); /* create metatable */
  233. lua_pushstring(L, tname);
  234. lua_setfield(L, -2, "__name"); /* metatable.__name = tname */
  235. lua_pushvalue(L, -1);
  236. lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
  237. return 1;
  238. }
  239. LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
  240. luaL_getmetatable(L, tname);
  241. lua_setmetatable(L, -2);
  242. }
  243. LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
  244. void *p = lua_touserdata(L, ud);
  245. if (p != NULL) { /* value is a userdata? */
  246. if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
  247. luaL_getmetatable(L, tname); /* get correct metatable */
  248. if (!lua_rawequal(L, -1, -2)) /* not the same? */
  249. p = NULL; /* value is a userdata with wrong metatable */
  250. lua_pop(L, 2); /* remove both metatables */
  251. return p;
  252. }
  253. }
  254. return NULL; /* value is not a userdata with a metatable */
  255. }
  256. LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
  257. void *p = luaL_testudata(L, ud, tname);
  258. if (p == NULL) typeerror(L, ud, tname);
  259. return p;
  260. }
  261. /* }====================================================== */
  262. /*
  263. ** {======================================================
  264. ** Argument check functions
  265. ** =======================================================
  266. */
  267. LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
  268. const char *const lst[]) {
  269. const char *name = (def) ? luaL_optstring(L, arg, def) :
  270. luaL_checkstring(L, arg);
  271. int i;
  272. for (i=0; lst[i]; i++)
  273. if (strcmp(lst[i], name) == 0)
  274. return i;
  275. return luaL_argerror(L, arg,
  276. lua_pushfstring(L, "invalid option " LUA_QS, name));
  277. }
  278. LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
  279. /* keep some extra space to run error routines, if needed */
  280. const int extra = LUA_MINSTACK;
  281. if (!lua_checkstack(L, space + extra)) {
  282. if (msg)
  283. luaL_error(L, "stack overflow (%s)", msg);
  284. else
  285. luaL_error(L, "stack overflow");
  286. }
  287. }
  288. LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
  289. if (lua_type(L, arg) != t)
  290. tag_error(L, arg, t);
  291. }
  292. LUALIB_API void luaL_checkany (lua_State *L, int arg) {
  293. if (lua_type(L, arg) == LUA_TNONE)
  294. luaL_argerror(L, arg, "value expected");
  295. }
  296. LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
  297. const char *s = lua_tolstring(L, arg, len);
  298. if (!s) tag_error(L, arg, LUA_TSTRING);
  299. return s;
  300. }
  301. LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
  302. const char *def, size_t *len) {
  303. if (lua_isnoneornil(L, arg)) {
  304. if (len)
  305. *len = (def ? strlen(def) : 0);
  306. return def;
  307. }
  308. else return luaL_checklstring(L, arg, len);
  309. }
  310. LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
  311. int isnum;
  312. lua_Number d = lua_tonumberx(L, arg, &isnum);
  313. if (!isnum)
  314. tag_error(L, arg, LUA_TNUMBER);
  315. return d;
  316. }
  317. LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
  318. return luaL_opt(L, luaL_checknumber, arg, def);
  319. }
  320. static void interror (lua_State *L, int arg) {
  321. if (lua_type(L, arg) == LUA_TNUMBER)
  322. luaL_argerror(L, arg, "float value out of range");
  323. else
  324. tag_error(L, arg, LUA_TNUMBER);
  325. }
  326. LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
  327. int isnum;
  328. lua_Integer d = lua_tointegerx(L, arg, &isnum);
  329. if (!isnum) {
  330. interror(L, arg);
  331. }
  332. return d;
  333. }
  334. LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int arg) {
  335. int isnum;
  336. lua_Unsigned d = lua_tounsignedx(L, arg, &isnum);
  337. if (!isnum)
  338. interror(L, arg);
  339. return d;
  340. }
  341. LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
  342. lua_Integer def) {
  343. return luaL_opt(L, luaL_checkinteger, arg, def);
  344. }
  345. LUALIB_API lua_Unsigned luaL_optunsigned (lua_State *L, int arg,
  346. lua_Unsigned def) {
  347. return luaL_opt(L, luaL_checkunsigned, arg, def);
  348. }
  349. /* }====================================================== */
  350. /*
  351. ** {======================================================
  352. ** Generic Buffer manipulation
  353. ** =======================================================
  354. */
  355. /*
  356. ** check whether buffer is using a userdata on the stack as a temporary
  357. ** buffer
  358. */
  359. #define buffonstack(B) ((B)->b != (B)->initb)
  360. /*
  361. ** returns a pointer to a free area with at least 'sz' bytes
  362. */
  363. LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
  364. lua_State *L = B->L;
  365. if (B->size - B->n < sz) { /* not enough space? */
  366. char *newbuff;
  367. size_t newsize = B->size * 2; /* double buffer size */
  368. if (newsize - B->n < sz) /* not big enough? */
  369. newsize = B->n + sz;
  370. if (newsize < B->n || newsize - B->n < sz)
  371. luaL_error(L, "buffer too large");
  372. /* create larger buffer */
  373. newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char));
  374. /* move content to new buffer */
  375. memcpy(newbuff, B->b, B->n * sizeof(char));
  376. if (buffonstack(B))
  377. lua_remove(L, -2); /* remove old buffer */
  378. B->b = newbuff;
  379. B->size = newsize;
  380. }
  381. return &B->b[B->n];
  382. }
  383. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  384. char *b = luaL_prepbuffsize(B, l);
  385. memcpy(b, s, l * sizeof(char));
  386. luaL_addsize(B, l);
  387. }
  388. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  389. luaL_addlstring(B, s, strlen(s));
  390. }
  391. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  392. lua_State *L = B->L;
  393. lua_pushlstring(L, B->b, B->n);
  394. if (buffonstack(B))
  395. lua_remove(L, -2); /* remove old buffer */
  396. }
  397. LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
  398. luaL_addsize(B, sz);
  399. luaL_pushresult(B);
  400. }
  401. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  402. lua_State *L = B->L;
  403. size_t l;
  404. const char *s = lua_tolstring(L, -1, &l);
  405. if (buffonstack(B))
  406. lua_insert(L, -2); /* put value below buffer */
  407. luaL_addlstring(B, s, l);
  408. lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
  409. }
  410. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  411. B->L = L;
  412. B->b = B->initb;
  413. B->n = 0;
  414. B->size = LUAL_BUFFERSIZE;
  415. }
  416. LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
  417. luaL_buffinit(L, B);
  418. return luaL_prepbuffsize(B, sz);
  419. }
  420. /* }====================================================== */
  421. /*
  422. ** {======================================================
  423. ** Reference system
  424. ** =======================================================
  425. */
  426. /* index of free-list header */
  427. #define freelist 0
  428. LUALIB_API int luaL_ref (lua_State *L, int t) {
  429. int ref;
  430. if (lua_isnil(L, -1)) {
  431. lua_pop(L, 1); /* remove from stack */
  432. return LUA_REFNIL; /* `nil' has a unique fixed reference */
  433. }
  434. t = lua_absindex(L, t);
  435. lua_rawgeti(L, t, freelist); /* get first free element */
  436. ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
  437. lua_pop(L, 1); /* remove it from stack */
  438. if (ref != 0) { /* any free element? */
  439. lua_rawgeti(L, t, ref); /* remove it from list */
  440. lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
  441. }
  442. else /* no free elements */
  443. ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
  444. lua_rawseti(L, t, ref);
  445. return ref;
  446. }
  447. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  448. if (ref >= 0) {
  449. t = lua_absindex(L, t);
  450. lua_rawgeti(L, t, freelist);
  451. lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
  452. lua_pushinteger(L, ref);
  453. lua_rawseti(L, t, freelist); /* t[freelist] = ref */
  454. }
  455. }
  456. /* }====================================================== */
  457. /*
  458. ** {======================================================
  459. ** Load functions
  460. ** =======================================================
  461. */
  462. typedef struct LoadF {
  463. int n; /* number of pre-read characters */
  464. FILE *f; /* file being read */
  465. char buff[LUAL_BUFFERSIZE]; /* area for reading file */
  466. } LoadF;
  467. static const char *getF (lua_State *L, void *ud, size_t *size) {
  468. LoadF *lf = (LoadF *)ud;
  469. (void)L; /* not used */
  470. if (lf->n > 0) { /* are there pre-read characters to be read? */
  471. *size = lf->n; /* return them (chars already in buffer) */
  472. lf->n = 0; /* no more pre-read characters */
  473. }
  474. else { /* read a block from file */
  475. /* 'fread' can return > 0 *and* set the EOF flag. If next call to
  476. 'getF' called 'fread', it might still wait for user input.
  477. The next check avoids this problem. */
  478. if (feof(lf->f)) return NULL;
  479. *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */
  480. }
  481. return lf->buff;
  482. }
  483. static int errfile (lua_State *L, const char *what, int fnameindex) {
  484. const char *serr = strerror(errno);
  485. const char *filename = lua_tostring(L, fnameindex) + 1;
  486. lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
  487. lua_remove(L, fnameindex);
  488. return LUA_ERRFILE;
  489. }
  490. static int skipBOM (LoadF *lf) {
  491. const char *p = "\xEF\xBB\xBF"; /* Utf8 BOM mark */
  492. int c;
  493. lf->n = 0;
  494. do {
  495. c = getc(lf->f);
  496. if (c == EOF || c != *(const unsigned char *)p++) return c;
  497. lf->buff[lf->n++] = c; /* to be read by the parser */
  498. } while (*p != '\0');
  499. lf->n = 0; /* prefix matched; discard it */
  500. return getc(lf->f); /* return next character */
  501. }
  502. /*
  503. ** reads the first character of file 'f' and skips an optional BOM mark
  504. ** in its beginning plus its first line if it starts with '#'. Returns
  505. ** true if it skipped the first line. In any case, '*cp' has the
  506. ** first "valid" character of the file (after the optional BOM and
  507. ** a first-line comment).
  508. */
  509. static int skipcomment (LoadF *lf, int *cp) {
  510. int c = *cp = skipBOM(lf);
  511. if (c == '#') { /* first line is a comment (Unix exec. file)? */
  512. do { /* skip first line */
  513. c = getc(lf->f);
  514. } while (c != EOF && c != '\n') ;
  515. *cp = getc(lf->f); /* skip end-of-line, if present */
  516. return 1; /* there was a comment */
  517. }
  518. else return 0; /* no comment */
  519. }
  520. LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename,
  521. const char *mode) {
  522. LoadF lf;
  523. int status, readstatus;
  524. int c;
  525. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  526. if (filename == NULL) {
  527. lua_pushliteral(L, "=stdin");
  528. lf.f = stdin;
  529. }
  530. else {
  531. lua_pushfstring(L, "@%s", filename);
  532. lf.f = fopen(filename, "r");
  533. if (lf.f == NULL) return errfile(L, "open", fnameindex);
  534. }
  535. if (skipcomment(&lf, &c)) /* read initial portion */
  536. lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */
  537. if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
  538. lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
  539. if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
  540. skipcomment(&lf, &c); /* re-read initial portion */
  541. }
  542. if (c != EOF)
  543. lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */
  544. status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode);
  545. readstatus = ferror(lf.f);
  546. if (filename) fclose(lf.f); /* close file (even in case of errors) */
  547. if (readstatus) {
  548. lua_settop(L, fnameindex); /* ignore results from `lua_load' */
  549. return errfile(L, "read", fnameindex);
  550. }
  551. lua_remove(L, fnameindex);
  552. return status;
  553. }
  554. typedef struct LoadS {
  555. const char *s;
  556. size_t size;
  557. } LoadS;
  558. static const char *getS (lua_State *L, void *ud, size_t *size) {
  559. LoadS *ls = (LoadS *)ud;
  560. (void)L; /* not used */
  561. if (ls->size == 0) return NULL;
  562. *size = ls->size;
  563. ls->size = 0;
  564. return ls->s;
  565. }
  566. LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size,
  567. const char *name, const char *mode) {
  568. LoadS ls;
  569. ls.s = buff;
  570. ls.size = size;
  571. return lua_load(L, getS, &ls, name, mode);
  572. }
  573. LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
  574. return luaL_loadbuffer(L, s, strlen(s), s);
  575. }
  576. /* }====================================================== */
  577. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  578. if (!lua_getmetatable(L, obj)) /* no metatable? */
  579. return 0;
  580. lua_pushstring(L, event);
  581. lua_rawget(L, -2);
  582. if (lua_isnil(L, -1)) {
  583. lua_pop(L, 2); /* remove metatable and metafield */
  584. return 0;
  585. }
  586. else {
  587. lua_remove(L, -2); /* remove only metatable */
  588. return 1;
  589. }
  590. }
  591. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  592. obj = lua_absindex(L, obj);
  593. if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
  594. return 0;
  595. lua_pushvalue(L, obj);
  596. lua_call(L, 1, 1);
  597. return 1;
  598. }
  599. LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
  600. lua_Integer l;
  601. int isnum;
  602. lua_len(L, idx);
  603. l = lua_tointegerx(L, -1, &isnum);
  604. if (!isnum)
  605. luaL_error(L, "object length is not an integer");
  606. lua_pop(L, 1); /* remove object */
  607. return l;
  608. }
  609. LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
  610. if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */
  611. switch (lua_type(L, idx)) {
  612. case LUA_TNUMBER: {
  613. if (lua_isinteger(L, idx))
  614. lua_pushfstring(L, "%I", lua_tointeger(L, idx));
  615. else {
  616. const char *s = lua_pushfstring(L, "%f", lua_tonumber(L, idx));
  617. if (s[strspn(s, "-0123456789")] == '\0') { /* looks like an int? */
  618. lua_pushliteral(L, ".0"); /* add a '.0' to result */
  619. lua_concat(L, 2);
  620. }
  621. }
  622. break;
  623. }
  624. case LUA_TSTRING:
  625. lua_pushvalue(L, idx);
  626. break;
  627. case LUA_TBOOLEAN:
  628. lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
  629. break;
  630. case LUA_TNIL:
  631. lua_pushliteral(L, "nil");
  632. break;
  633. default:
  634. lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
  635. lua_topointer(L, idx));
  636. break;
  637. }
  638. }
  639. return lua_tolstring(L, -1, len);
  640. }
  641. /*
  642. ** {======================================================
  643. ** Compatibility with 5.1 module functions
  644. ** =======================================================
  645. */
  646. #if defined(LUA_COMPAT_MODULE)
  647. static const char *luaL_findtable (lua_State *L, int idx,
  648. const char *fname, int szhint) {
  649. const char *e;
  650. if (idx) lua_pushvalue(L, idx);
  651. do {
  652. e = strchr(fname, '.');
  653. if (e == NULL) e = fname + strlen(fname);
  654. lua_pushlstring(L, fname, e - fname);
  655. lua_rawget(L, -2);
  656. if (lua_isnil(L, -1)) { /* no such field? */
  657. lua_pop(L, 1); /* remove this nil */
  658. lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
  659. lua_pushlstring(L, fname, e - fname);
  660. lua_pushvalue(L, -2);
  661. lua_settable(L, -4); /* set new table into field */
  662. }
  663. else if (!lua_istable(L, -1)) { /* field has a non-table value? */
  664. lua_pop(L, 2); /* remove table and value */
  665. return fname; /* return problematic part of the name */
  666. }
  667. lua_remove(L, -2); /* remove previous table */
  668. fname = e + 1;
  669. } while (*e == '.');
  670. return NULL;
  671. }
  672. /*
  673. ** Count number of elements in a luaL_Reg list.
  674. */
  675. static int libsize (const luaL_Reg *l) {
  676. int size = 0;
  677. for (; l && l->name; l++) size++;
  678. return size;
  679. }
  680. /*
  681. ** Find or create a module table with a given name. The function
  682. ** first looks at the _LOADED table and, if that fails, try a
  683. ** global variable with that name. In any case, leaves on the stack
  684. ** the module table.
  685. */
  686. LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
  687. int sizehint) {
  688. luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */
  689. lua_getfield(L, -1, modname); /* get _LOADED[modname] */
  690. if (!lua_istable(L, -1)) { /* not found? */
  691. lua_pop(L, 1); /* remove previous result */
  692. /* try global variable (and create one if it does not exist) */
  693. lua_pushglobaltable(L);
  694. if (luaL_findtable(L, 0, modname, sizehint) != NULL)
  695. luaL_error(L, "name conflict for module " LUA_QS, modname);
  696. lua_pushvalue(L, -1);
  697. lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */
  698. }
  699. lua_remove(L, -2); /* remove _LOADED table */
  700. }
  701. LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
  702. const luaL_Reg *l, int nup) {
  703. luaL_checkversion(L);
  704. if (libname) {
  705. luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */
  706. lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
  707. }
  708. if (l)
  709. luaL_setfuncs(L, l, nup);
  710. else
  711. lua_pop(L, nup); /* remove upvalues */
  712. }
  713. #endif
  714. /* }====================================================== */
  715. /*
  716. ** set functions from list 'l' into table at top - 'nup'; each
  717. ** function gets the 'nup' elements at the top as upvalues.
  718. ** Returns with only the table at the stack.
  719. */
  720. LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
  721. luaL_checkstack(L, nup, "too many upvalues");
  722. for (; l->name != NULL; l++) { /* fill the table with given functions */
  723. int i;
  724. for (i = 0; i < nup; i++) /* copy upvalues to the top */
  725. lua_pushvalue(L, -nup);
  726. lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
  727. lua_setfield(L, -(nup + 2), l->name);
  728. }
  729. lua_pop(L, nup); /* remove upvalues */
  730. }
  731. /*
  732. ** ensure that stack[idx][fname] has a table and push that table
  733. ** into the stack
  734. */
  735. LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
  736. lua_getfield(L, idx, fname);
  737. if (lua_istable(L, -1)) return 1; /* table already there */
  738. else {
  739. lua_pop(L, 1); /* remove previous result */
  740. idx = lua_absindex(L, idx);
  741. lua_newtable(L);
  742. lua_pushvalue(L, -1); /* copy to be left at top */
  743. lua_setfield(L, idx, fname); /* assign new table to field */
  744. return 0; /* false, because did not find table there */
  745. }
  746. }
  747. /*
  748. ** stripped-down 'require'. Calls 'openf' to open a module,
  749. ** registers the result in 'package.loaded' table and, if 'glb'
  750. ** is true, also registers the result in the global table.
  751. ** Leaves resulting module on the top.
  752. */
  753. LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
  754. lua_CFunction openf, int glb) {
  755. lua_pushcfunction(L, openf);
  756. lua_pushstring(L, modname); /* argument to open function */
  757. lua_call(L, 1, 1); /* open module */
  758. luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
  759. lua_pushvalue(L, -2); /* make copy of module (call result) */
  760. lua_setfield(L, -2, modname); /* _LOADED[modname] = module */
  761. lua_pop(L, 1); /* remove _LOADED table */
  762. if (glb) {
  763. lua_pushvalue(L, -1); /* copy of 'mod' */
  764. lua_setglobal(L, modname); /* _G[modname] = module */
  765. }
  766. }
  767. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
  768. const char *r) {
  769. const char *wild;
  770. size_t l = strlen(p);
  771. luaL_Buffer b;
  772. luaL_buffinit(L, &b);
  773. while ((wild = strstr(s, p)) != NULL) {
  774. luaL_addlstring(&b, s, wild - s); /* push prefix */
  775. luaL_addstring(&b, r); /* push replacement in place of pattern */
  776. s = wild + l; /* continue after `p' */
  777. }
  778. luaL_addstring(&b, s); /* push last suffix */
  779. luaL_pushresult(&b);
  780. return lua_tostring(L, -1);
  781. }
  782. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  783. (void)ud; (void)osize; /* not used */
  784. if (nsize == 0) {
  785. free(ptr);
  786. return NULL;
  787. }
  788. else
  789. return realloc(ptr, nsize);
  790. }
  791. static int panic (lua_State *L) {
  792. luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
  793. lua_tostring(L, -1));
  794. return 0; /* return to Lua to abort */
  795. }
  796. LUALIB_API lua_State *luaL_newstate (void) {
  797. lua_State *L = lua_newstate(l_alloc, NULL);
  798. if (L) lua_atpanic(L, &panic);
  799. return L;
  800. }
  801. LUALIB_API void luaL_checkversion_ (lua_State *L, int ver, size_t sz) {
  802. const lua_Number *v = lua_version(L);
  803. if (v != lua_version(NULL))
  804. luaL_error(L, "multiple Lua VMs detected");
  805. else if (*v != ver)
  806. luaL_error(L, "version mismatch: app. needs %d, Lua core provides %f",
  807. ver, *v);
  808. /* check numeric types */
  809. if (sz != LUAL_NUMSIZES)
  810. luaL_error(L, "core and library have incompatible numeric types");
  811. }