lauxlib.c 27 KB

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