lauxlib.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. /*
  2. ** $Id: lauxlib.c,v 1.192 2009/09/28 12:36:40 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. /* convert a stack index to positive */
  19. #define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \
  20. lua_gettop(L) + (i) + 1)
  21. /*
  22. ** {======================================================
  23. ** Traceback
  24. ** =======================================================
  25. */
  26. #define LEVELS1 12 /* size of the first part of the stack */
  27. #define LEVELS2 10 /* size of the second part of the stack */
  28. /*
  29. ** search for 'objidx' in table at index -1.
  30. ** return 1 + string at top if find a good name.
  31. */
  32. static int findfield (lua_State *L, int objidx, int level) {
  33. int found = 0;
  34. if (level == 0 || !lua_istable(L, -1))
  35. return 0; /* not found */
  36. lua_pushnil(L); /* start 'next' loop */
  37. while (!found && lua_next(L, -2)) { /* for each pair in table */
  38. if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */
  39. if (lua_rawequal(L, objidx, -1)) { /* found object? */
  40. lua_pop(L, 1); /* remove value (but keep name) */
  41. return 1;
  42. }
  43. else if (findfield(L, objidx, level - 1)) { /* try recursively */
  44. lua_remove(L, -2); /* remove table (but keep name) */
  45. lua_pushliteral(L, ".");
  46. lua_insert(L, -2); /* place '.' between the two names */
  47. lua_concat(L, 3);
  48. return 1;
  49. }
  50. }
  51. lua_pop(L, 1); /* remove value */
  52. }
  53. return 0; /* not found */
  54. }
  55. static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
  56. int top = lua_gettop(L);
  57. lua_getinfo(L, "f", ar); /* push function */
  58. lua_pushvalue(L, LUA_GLOBALSINDEX); /* push global table */
  59. if (findfield(L, top + 1, 2)) {
  60. lua_copy(L, -1, top + 1); /* move name to proper place */
  61. lua_pop(L, 2); /* remove pushed values */
  62. return 1;
  63. }
  64. else {
  65. lua_settop(L, top); /* remove function and global table */
  66. return 0;
  67. }
  68. }
  69. static void pushfuncname (lua_State *L, lua_Debug *ar) {
  70. if (*ar->namewhat != '\0') /* is there a name? */
  71. lua_pushfstring(L, "function " LUA_QS, ar->name);
  72. else if (*ar->what == 'm') /* main? */
  73. lua_pushfstring(L, "main chunk");
  74. else if (*ar->what == 'C' || *ar->what == 't') {
  75. if (pushglobalfuncname(L, ar)) {
  76. lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1));
  77. lua_remove(L, -2); /* remove name */
  78. }
  79. else
  80. lua_pushliteral(L, "?"); /* C function or tail call */
  81. }
  82. else
  83. lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
  84. }
  85. static int countlevels (lua_State *L) {
  86. lua_Debug ar;
  87. int li = 1, le = 1;
  88. /* find an upper bound */
  89. while (lua_getstack(L, le, &ar)) { li = le; le *= 2; }
  90. /* do a binary search */
  91. while (li < le) {
  92. int m = (li + le)/2;
  93. if (lua_getstack(L, m, &ar)) li = m + 1;
  94. else le = m;
  95. }
  96. return le - 1;
  97. }
  98. LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
  99. const char *msg, int level) {
  100. lua_Debug ar;
  101. int top = lua_gettop(L);
  102. int numlevels = countlevels(L1);
  103. int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0;
  104. if (msg) lua_pushfstring(L, "%s\n", msg);
  105. lua_pushliteral(L, "stack traceback:");
  106. while (lua_getstack(L1, level++, &ar)) {
  107. if (level == mark) { /* too many levels? */
  108. lua_pushliteral(L, "\n\t..."); /* add a '...' */
  109. level = numlevels - LEVELS2; /* and skip to last ones */
  110. }
  111. else {
  112. lua_getinfo(L1, "Sln", &ar);
  113. lua_pushfstring(L, "\n\t%s:", ar.short_src);
  114. if (ar.currentline > 0)
  115. lua_pushfstring(L, "%d:", ar.currentline);
  116. lua_pushliteral(L, " in ");
  117. pushfuncname(L, &ar);
  118. lua_concat(L, lua_gettop(L) - top);
  119. }
  120. }
  121. lua_concat(L, lua_gettop(L) - top);
  122. }
  123. /* }====================================================== */
  124. /*
  125. ** {======================================================
  126. ** Error-report functions
  127. ** =======================================================
  128. */
  129. LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
  130. lua_Debug ar;
  131. if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
  132. return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
  133. lua_getinfo(L, "n", &ar);
  134. if (strcmp(ar.namewhat, "method") == 0) {
  135. narg--; /* do not count `self' */
  136. if (narg == 0) /* error is in the self argument itself? */
  137. return luaL_error(L, "calling " LUA_QS " on bad self", ar.name);
  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 " LUA_QS " (%s)",
  142. narg, ar.name, extramsg);
  143. }
  144. LUALIB_API int luaL_typeerror (lua_State *L, int narg, const char *tname) {
  145. const char *msg = lua_pushfstring(L, "%s expected, got %s",
  146. tname, luaL_typename(L, narg));
  147. return luaL_argerror(L, narg, msg);
  148. }
  149. static void tag_error (lua_State *L, int narg, int tag) {
  150. luaL_typeerror(L, narg, lua_typename(L, tag));
  151. }
  152. LUALIB_API void luaL_where (lua_State *L, int level) {
  153. lua_Debug ar;
  154. if (lua_getstack(L, level, &ar)) { /* check function at level */
  155. lua_getinfo(L, "Sl", &ar); /* get info about it */
  156. if (ar.currentline > 0) { /* is there info? */
  157. lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
  158. return;
  159. }
  160. }
  161. lua_pushliteral(L, ""); /* else, no information available... */
  162. }
  163. LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
  164. va_list argp;
  165. va_start(argp, fmt);
  166. luaL_where(L, 1);
  167. lua_pushvfstring(L, fmt, argp);
  168. va_end(argp);
  169. lua_concat(L, 2);
  170. return lua_error(L);
  171. }
  172. /* }====================================================== */
  173. /*
  174. ** {======================================================
  175. ** Userdata's metatable manipulation
  176. ** =======================================================
  177. */
  178. LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
  179. lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */
  180. if (!lua_isnil(L, -1)) /* name already in use? */
  181. return 0; /* leave previous value on top, but return 0 */
  182. lua_pop(L, 1);
  183. lua_newtable(L); /* create metatable */
  184. lua_pushvalue(L, -1);
  185. lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
  186. return 1;
  187. }
  188. LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) {
  189. void *p = lua_touserdata(L, ud);
  190. if (p != NULL) { /* value is a userdata? */
  191. if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
  192. lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */
  193. if (!lua_rawequal(L, -1, -2)) /* not the same? */
  194. p = NULL; /* value is a userdata with wrong metatable */
  195. lua_pop(L, 2); /* remove both metatables */
  196. return p;
  197. }
  198. }
  199. return NULL; /* value is not a userdata with a metatable */
  200. }
  201. LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
  202. void *p = luaL_testudata(L, ud, tname);
  203. if (p == NULL) luaL_typeerror(L, ud, tname);
  204. return p;
  205. }
  206. /* }====================================================== */
  207. /*
  208. ** {======================================================
  209. ** Argument check functions
  210. ** =======================================================
  211. */
  212. LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
  213. const char *const lst[]) {
  214. const char *name = (def) ? luaL_optstring(L, narg, def) :
  215. luaL_checkstring(L, narg);
  216. int i;
  217. for (i=0; lst[i]; i++)
  218. if (strcmp(lst[i], name) == 0)
  219. return i;
  220. return luaL_argerror(L, narg,
  221. lua_pushfstring(L, "invalid option " LUA_QS, name));
  222. }
  223. LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
  224. if (!lua_checkstack(L, space)) {
  225. if (msg)
  226. luaL_error(L, "stack overflow (%s)", msg);
  227. else
  228. luaL_error(L, "stack overflow");
  229. }
  230. }
  231. LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
  232. if (lua_type(L, narg) != t)
  233. tag_error(L, narg, t);
  234. }
  235. LUALIB_API void luaL_checkany (lua_State *L, int narg) {
  236. if (lua_type(L, narg) == LUA_TNONE)
  237. luaL_argerror(L, narg, "value expected");
  238. }
  239. LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
  240. const char *s = lua_tolstring(L, narg, len);
  241. if (!s) tag_error(L, narg, LUA_TSTRING);
  242. return s;
  243. }
  244. LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
  245. const char *def, size_t *len) {
  246. if (lua_isnoneornil(L, narg)) {
  247. if (len)
  248. *len = (def ? strlen(def) : 0);
  249. return def;
  250. }
  251. else return luaL_checklstring(L, narg, len);
  252. }
  253. LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
  254. lua_Number d = lua_tonumber(L, narg);
  255. if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
  256. tag_error(L, narg, LUA_TNUMBER);
  257. return d;
  258. }
  259. LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
  260. return luaL_opt(L, luaL_checknumber, narg, def);
  261. }
  262. LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
  263. lua_Integer d = lua_tointeger(L, narg);
  264. if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
  265. tag_error(L, narg, LUA_TNUMBER);
  266. return d;
  267. }
  268. LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
  269. lua_Integer def) {
  270. return luaL_opt(L, luaL_checkinteger, narg, def);
  271. }
  272. /* }====================================================== */
  273. /*
  274. ** {======================================================
  275. ** Generic Buffer manipulation
  276. ** =======================================================
  277. */
  278. #define bufflen(B) ((B)->p - (B)->buffer)
  279. #define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
  280. #define LIMIT (LUA_MINSTACK/2)
  281. static int emptybuffer (luaL_Buffer *B) {
  282. size_t l = bufflen(B);
  283. if (l == 0) return 0; /* put nothing on stack */
  284. else {
  285. lua_pushlstring(B->L, B->buffer, l);
  286. B->p = B->buffer;
  287. B->lvl++;
  288. return 1;
  289. }
  290. }
  291. static void adjuststack (luaL_Buffer *B) {
  292. if (B->lvl > 1) {
  293. lua_State *L = B->L;
  294. int toget = 1; /* number of levels to concat */
  295. size_t toplen = lua_objlen(L, -1);
  296. do {
  297. size_t l = lua_objlen(L, -(toget+1));
  298. if (B->lvl - toget + 1 >= LIMIT || toplen > l) {
  299. toplen += l;
  300. toget++;
  301. }
  302. else break;
  303. } while (toget < B->lvl);
  304. lua_concat(L, toget);
  305. B->lvl = B->lvl - toget + 1;
  306. }
  307. }
  308. LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
  309. if (emptybuffer(B))
  310. adjuststack(B);
  311. return B->buffer;
  312. }
  313. LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
  314. while (l--)
  315. luaL_addchar(B, *s++);
  316. }
  317. LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
  318. luaL_addlstring(B, s, strlen(s));
  319. }
  320. LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
  321. emptybuffer(B);
  322. lua_concat(B->L, B->lvl);
  323. B->lvl = 1;
  324. }
  325. LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
  326. lua_State *L = B->L;
  327. size_t vl;
  328. const char *s = lua_tolstring(L, -1, &vl);
  329. if (vl <= bufffree(B)) { /* fit into buffer? */
  330. memcpy(B->p, s, vl); /* put it there */
  331. B->p += vl;
  332. lua_pop(L, 1); /* remove from stack */
  333. }
  334. else {
  335. if (emptybuffer(B))
  336. lua_insert(L, -2); /* put buffer before new value */
  337. B->lvl++; /* add new value into B stack */
  338. adjuststack(B);
  339. }
  340. }
  341. LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
  342. luaL_checkstack(L, LIMIT + LUA_MINSTACK, "no space for new buffer");
  343. B->L = L;
  344. B->p = B->buffer;
  345. B->lvl = 0;
  346. }
  347. /* }====================================================== */
  348. /*
  349. ** {======================================================
  350. ** Reference system
  351. ** =======================================================
  352. */
  353. /* number of prereserved references (for internal use) */
  354. #define FREELIST_REF (LUA_RIDX_LAST + 1) /* free list of references */
  355. LUALIB_API int luaL_ref (lua_State *L, int t) {
  356. int ref;
  357. t = abs_index(L, t);
  358. if (lua_isnil(L, -1)) {
  359. lua_pop(L, 1); /* remove from stack */
  360. return LUA_REFNIL; /* `nil' has a unique fixed reference */
  361. }
  362. lua_rawgeti(L, t, FREELIST_REF); /* get first free element */
  363. ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */
  364. lua_pop(L, 1); /* remove it from stack */
  365. if (ref != 0) { /* any free element? */
  366. lua_rawgeti(L, t, ref); /* remove it from list */
  367. lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
  368. }
  369. else { /* no free elements */
  370. ref = (int)lua_objlen(L, t) + 1; /* get a new reference */
  371. if (ref == FREELIST_REF) { /* FREELIST_REF not initialized? */
  372. lua_pushinteger(L, 0);
  373. lua_rawseti(L, t, FREELIST_REF);
  374. ref = FREELIST_REF + 1;
  375. }
  376. }
  377. lua_rawseti(L, t, ref);
  378. return ref;
  379. }
  380. LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
  381. if (ref >= 0) {
  382. t = abs_index(L, t);
  383. lua_rawgeti(L, t, FREELIST_REF);
  384. lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */
  385. lua_pushinteger(L, ref);
  386. lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
  387. }
  388. }
  389. /* }====================================================== */
  390. /*
  391. ** {======================================================
  392. ** Load functions
  393. ** =======================================================
  394. */
  395. typedef struct LoadF {
  396. int extraline;
  397. FILE *f;
  398. char buff[LUAL_BUFFERSIZE];
  399. } LoadF;
  400. static const char *getF (lua_State *L, void *ud, size_t *size) {
  401. LoadF *lf = (LoadF *)ud;
  402. (void)L;
  403. if (lf->extraline) {
  404. lf->extraline = 0;
  405. *size = 1;
  406. return "\n";
  407. }
  408. /* 'fread' can return > 0 *and* set the EOF flag. If next call to
  409. 'getF' calls 'fread', terminal may still wait for user input.
  410. The next check avoids this problem. */
  411. if (feof(lf->f)) return NULL;
  412. *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f);
  413. return (*size > 0) ? lf->buff : NULL;
  414. }
  415. static int errfile (lua_State *L, const char *what, int fnameindex) {
  416. const char *serr = strerror(errno);
  417. const char *filename = lua_tostring(L, fnameindex) + 1;
  418. lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
  419. lua_remove(L, fnameindex);
  420. return LUA_ERRFILE;
  421. }
  422. LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
  423. LoadF lf;
  424. int status, readstatus;
  425. int c;
  426. int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
  427. lf.extraline = 0;
  428. if (filename == NULL) {
  429. lua_pushliteral(L, "=stdin");
  430. lf.f = stdin;
  431. }
  432. else {
  433. lua_pushfstring(L, "@%s", filename);
  434. lf.f = fopen(filename, "r");
  435. if (lf.f == NULL) return errfile(L, "open", fnameindex);
  436. }
  437. c = getc(lf.f);
  438. if (c == '#') { /* Unix exec. file? */
  439. lf.extraline = 1;
  440. while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */
  441. if (c == '\n') c = getc(lf.f);
  442. }
  443. if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
  444. lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
  445. if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
  446. /* skip eventual `#!...' */
  447. while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ;
  448. lf.extraline = 0;
  449. }
  450. ungetc(c, lf.f);
  451. status = lua_load(L, getF, &lf, lua_tostring(L, -1));
  452. readstatus = ferror(lf.f);
  453. if (filename) fclose(lf.f); /* close file (even in case of errors) */
  454. if (readstatus) {
  455. lua_settop(L, fnameindex); /* ignore results from `lua_load' */
  456. return errfile(L, "read", fnameindex);
  457. }
  458. lua_remove(L, fnameindex);
  459. return status;
  460. }
  461. typedef struct LoadS {
  462. const char *s;
  463. size_t size;
  464. } LoadS;
  465. static const char *getS (lua_State *L, void *ud, size_t *size) {
  466. LoadS *ls = (LoadS *)ud;
  467. (void)L;
  468. if (ls->size == 0) return NULL;
  469. *size = ls->size;
  470. ls->size = 0;
  471. return ls->s;
  472. }
  473. LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
  474. const char *name) {
  475. LoadS ls;
  476. ls.s = buff;
  477. ls.size = size;
  478. return lua_load(L, getS, &ls, name);
  479. }
  480. LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
  481. return luaL_loadbuffer(L, s, strlen(s), s);
  482. }
  483. /* }====================================================== */
  484. LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
  485. if (!lua_getmetatable(L, obj)) /* no metatable? */
  486. return 0;
  487. lua_pushstring(L, event);
  488. lua_rawget(L, -2);
  489. if (lua_isnil(L, -1)) {
  490. lua_pop(L, 2); /* remove metatable and metafield */
  491. return 0;
  492. }
  493. else {
  494. lua_remove(L, -2); /* remove only metatable */
  495. return 1;
  496. }
  497. }
  498. LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
  499. obj = abs_index(L, obj);
  500. if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
  501. return 0;
  502. lua_pushvalue(L, obj);
  503. lua_call(L, 1, 1);
  504. return 1;
  505. }
  506. LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
  507. if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */
  508. switch (lua_type(L, idx)) {
  509. case LUA_TNUMBER:
  510. case LUA_TSTRING:
  511. lua_pushvalue(L, idx);
  512. break;
  513. case LUA_TBOOLEAN:
  514. lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
  515. break;
  516. case LUA_TNIL:
  517. lua_pushliteral(L, "nil");
  518. break;
  519. default:
  520. lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
  521. lua_topointer(L, idx));
  522. break;
  523. }
  524. }
  525. return lua_tolstring(L, -1, len);
  526. }
  527. static int libsize (const luaL_Reg *l) {
  528. int size = 0;
  529. for (; l->name; l++) size++;
  530. return size;
  531. }
  532. LUALIB_API void luaL_register (lua_State *L, const char *libname,
  533. const luaL_Reg *l) {
  534. luaL_checkversion(L);
  535. if (libname) {
  536. /* check whether lib already exists */
  537. luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);
  538. lua_getfield(L, -1, libname); /* get _LOADED[libname] */
  539. if (!lua_istable(L, -1)) { /* not found? */
  540. lua_pop(L, 1); /* remove previous result */
  541. /* try global variable (and create one if it does not exist) */
  542. if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, libsize(l)) != NULL)
  543. luaL_error(L, "name conflict for module " LUA_QS, libname);
  544. lua_pushvalue(L, -1);
  545. lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */
  546. }
  547. lua_remove(L, -2); /* remove _LOADED table */
  548. }
  549. if (l == NULL) return; /* nothing to register? */
  550. for (; l->name; l++) { /* else fill the table with given functions */
  551. lua_pushcfunction(L, l->func);
  552. lua_setfield(L, -2, l->name);
  553. }
  554. }
  555. LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
  556. const char *r) {
  557. const char *wild;
  558. size_t l = strlen(p);
  559. luaL_Buffer b;
  560. luaL_buffinit(L, &b);
  561. while ((wild = strstr(s, p)) != NULL) {
  562. luaL_addlstring(&b, s, wild - s); /* push prefix */
  563. luaL_addstring(&b, r); /* push replacement in place of pattern */
  564. s = wild + l; /* continue after `p' */
  565. }
  566. luaL_addstring(&b, s); /* push last suffix */
  567. luaL_pushresult(&b);
  568. return lua_tostring(L, -1);
  569. }
  570. LUALIB_API const char *luaL_findtable (lua_State *L, int idx,
  571. const char *fname, int szhint) {
  572. const char *e;
  573. lua_pushvalue(L, idx);
  574. do {
  575. e = strchr(fname, '.');
  576. if (e == NULL) e = fname + strlen(fname);
  577. lua_pushlstring(L, fname, e - fname);
  578. lua_rawget(L, -2);
  579. if (lua_isnil(L, -1)) { /* no such field? */
  580. lua_pop(L, 1); /* remove this nil */
  581. lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
  582. lua_pushlstring(L, fname, e - fname);
  583. lua_pushvalue(L, -2);
  584. lua_settable(L, -4); /* set new table into field */
  585. }
  586. else if (!lua_istable(L, -1)) { /* field has a non-table value? */
  587. lua_pop(L, 2); /* remove table and value */
  588. return fname; /* return problematic part of the name */
  589. }
  590. lua_remove(L, -2); /* remove previous table */
  591. fname = e + 1;
  592. } while (*e == '.');
  593. return NULL;
  594. }
  595. static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
  596. (void)ud;
  597. (void)osize;
  598. if (nsize == 0) {
  599. free(ptr);
  600. return NULL;
  601. }
  602. else
  603. return realloc(ptr, nsize);
  604. }
  605. static int panic (lua_State *L) {
  606. fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n",
  607. lua_tostring(L, -1));
  608. return 0; /* return to Lua to abort */
  609. }
  610. LUALIB_API lua_State *luaL_newstate (void) {
  611. lua_State *L = lua_newstate(l_alloc, NULL);
  612. if (L) lua_atpanic(L, &panic);
  613. return L;
  614. }
  615. LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver) {
  616. const lua_Number *v = lua_version(L);
  617. if (v != lua_version(NULL))
  618. luaL_error(L, "multiple Lua VMs detected");
  619. else if (*v != ver)
  620. luaL_error(L, "version mismatch: app. needs %d, Lua core provides %f",
  621. ver, *v);
  622. }