2
0

lauxlib.c 27 KB

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