lua_store.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include "lua_lsup.h"
  2. static int l_store_new (lua_State *L)
  3. {
  4. const LSUP_StoreType store_type = luaL_checkinteger (L, 1);
  5. const char *id = luaL_optstring (L, 2, NULL);
  6. const bool clear = lua_toboolean (L, 3);
  7. LSUP_Store **store_p = lua_newuserdatauv (L, sizeof (*store_p), 1);
  8. luaL_getmetatable (L, "LSUP.Store");
  9. lua_setmetatable (L, -2);
  10. const LSUP_StoreInt *sif = LSUP_store_int (store_type);
  11. LUA_NLCHECK (sif, "No interface defined for store type: %d.", store_type);
  12. *store_p = LSUP_store_new (store_type, id, 0);
  13. LUA_NLCHECK (*store_p, "Error creating back end store.");
  14. // Set up the store if a function for that is defined.
  15. if (clear) log_info ("Clearing old store.");
  16. if (sif->setup_fn) LUA_PCHECK (
  17. sif->setup_fn (id, clear), "Error initializing back end store.");
  18. return 1;
  19. }
  20. static int store_gc (lua_State *L)
  21. {
  22. LSUP_Store **sp = luaL_checkudata(L, 1, "LSUP.Store");
  23. LOG_DEBUG ("Garbage collecting store @%p.", *sp);
  24. LSUP_store_free (*sp);
  25. *sp = NULL;
  26. return 0;
  27. }
  28. static int l_store_tostring (lua_State *L)
  29. {
  30. const LSUP_Store *store = *(LSUP_Store **) luaL_checkudata (
  31. L, 1, "LSUP.Store");
  32. lua_pushfstring (
  33. L, "LSUP.Store @%p <%s>: %s",
  34. store,
  35. LSUP_store_type_label (store->type),
  36. store->id);
  37. return 1;
  38. }
  39. // TODO add transaction handling.
  40. static const luaL_Reg store_lib_fn [] = {
  41. {"new", l_store_new},
  42. {"__gc", store_gc},
  43. {NULL}
  44. };
  45. static const luaL_Reg store_lib_meth [] = {
  46. {"__gc", store_gc},
  47. {"__tostring", l_store_tostring},
  48. {NULL}
  49. };
  50. static const LEnumConst store_enums[] = {
  51. {"HTABLE", LSUP_STORE_HTABLE},
  52. {"MDB", LSUP_STORE_MDB},
  53. {NULL, 0}
  54. };
  55. int luaopen_lsup_store (lua_State *L)
  56. {
  57. LSUP_init(); // This is idempotent: no problem calling it multiple times.
  58. luaL_newmetatable (L, "LSUP.Store");
  59. lua_pushvalue (L, -1);
  60. lua_setfield (L, -2, "__index");
  61. luaL_setfuncs (L, store_lib_meth, 0);
  62. luaL_newlib (L, store_lib_fn);
  63. push_int_const (L, store_enums);
  64. return 1;
  65. }