lauxlib.c 27 KB

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