2
0

lib22.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* implementation for lib2-v2 */
  2. #include <string.h>
  3. #include "lua.h"
  4. #include "lauxlib.h"
  5. static int id (lua_State *L) {
  6. lua_pushboolean(L, 1);
  7. lua_insert(L, 1);
  8. return lua_gettop(L);
  9. }
  10. struct STR {
  11. void *ud;
  12. lua_Alloc allocf;
  13. };
  14. static void *t_freestr (void *ud, void *ptr, size_t osize, size_t nsize) {
  15. struct STR *blk = (struct STR*)ptr - 1;
  16. blk->allocf(blk->ud, blk, sizeof(struct STR) + osize, 0);
  17. return NULL;
  18. }
  19. static int newstr (lua_State *L) {
  20. size_t len;
  21. const char *str = luaL_checklstring(L, 1, &len);
  22. void *ud;
  23. lua_Alloc allocf = lua_getallocf(L, &ud);
  24. struct STR *blk = (struct STR*)allocf(ud, NULL, 0,
  25. len + 1 + sizeof(struct STR));
  26. if (blk == NULL) { /* allocation error? */
  27. lua_pushliteral(L, "not enough memory");
  28. lua_error(L); /* raise a memory error */
  29. }
  30. blk->ud = ud; blk->allocf = allocf;
  31. memcpy(blk + 1, str, len + 1);
  32. lua_pushexternalstring(L, (char *)(blk + 1), len, t_freestr, L);
  33. return 1;
  34. }
  35. /*
  36. ** Create an external string and keep it in the registry, so that it
  37. ** will test that the library code is still available (to deallocate
  38. ** this string) when closing the state.
  39. */
  40. static void initstr (lua_State *L) {
  41. lua_pushcfunction(L, newstr);
  42. lua_pushstring(L,
  43. "012345678901234567890123456789012345678901234567890123456789");
  44. lua_call(L, 1, 1); /* call newstr("0123...") */
  45. luaL_ref(L, LUA_REGISTRYINDEX); /* keep string in the registry */
  46. }
  47. static const struct luaL_Reg funcs[] = {
  48. {"id", id},
  49. {"newstr", newstr},
  50. {NULL, NULL}
  51. };
  52. LUAMOD_API int luaopen_lib2 (lua_State *L) {
  53. lua_settop(L, 2);
  54. lua_setglobal(L, "y"); /* y gets 2nd parameter */
  55. lua_setglobal(L, "x"); /* x gets 1st parameter */
  56. initstr(L);
  57. luaL_newlib(L, funcs);
  58. return 1;
  59. }