lua_store.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #include "lua_volksdata.h"
  2. static int l_store_new (lua_State *L)
  3. {
  4. const VOLK_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. VOLK_Store **store_p = lua_newuserdatauv (L, sizeof (*store_p), 1);
  8. luaL_getmetatable (L, "VOLK.Store");
  9. lua_setmetatable (L, -2);
  10. // Set up the store if a function for that is defined.
  11. if (clear) log_info ("Clearing old store.");
  12. *store_p = VOLK_store_new (store_type, id, 0, clear);
  13. LUA_NLCHECK (*store_p, "Error creating back end store.");
  14. return 1;
  15. }
  16. // This can be called automatically by te garbage collector, or manually.
  17. // It is idempotent.
  18. static int l_store_gc (lua_State *L)
  19. {
  20. VOLK_Store **sp = luaL_checkudata(L, 1, "VOLK.Store");
  21. LOG_DEBUG ("Garbage collecting store @%p.", *sp);
  22. VOLK_store_free (*sp);
  23. *sp = NULL;
  24. return 0;
  25. }
  26. static int l_store_size (lua_State *L)
  27. {
  28. const VOLK_Store **store_p = luaL_checkudata (L, 1, "VOLK.Store");
  29. lua_pushinteger (L, VOLK_store_size (*store_p));
  30. return 1;
  31. }
  32. static int l_store_tostring (lua_State *L)
  33. {
  34. const VOLK_Store *store = *(VOLK_Store **) luaL_checkudata (
  35. L, 1, "VOLK.Store");
  36. lua_pushfstring (
  37. L, "VOLK.Store @%p <%s>: %s",
  38. store,
  39. VOLK_store_type_label (store->type),
  40. store->id);
  41. return 1;
  42. }
  43. // TODO add transaction handling.
  44. static const luaL_Reg store_lib_fn [] = {
  45. {"new", l_store_new},
  46. {NULL}
  47. };
  48. static const luaL_Reg store_lib_meth [] = {
  49. {"__gc", l_store_gc},
  50. {"__len", l_store_size},
  51. {"__tostring", l_store_tostring},
  52. {"close", l_store_gc},
  53. {NULL}
  54. };
  55. static const LEnumConst store_enums[] = {
  56. {"HTABLE", VOLK_STORE_HTABLE},
  57. {"MDB", VOLK_STORE_MDB},
  58. {NULL, 0}
  59. };
  60. int luaopen_volksdata_store (lua_State *L)
  61. {
  62. VOLK_init(); // This is idempotent: no problem calling it multiple times.
  63. luaL_newmetatable (L, "VOLK.Store");
  64. lua_pushvalue (L, -1);
  65. lua_setfield (L, -2, "__index");
  66. luaL_setfuncs (L, store_lib_meth, 0);
  67. luaL_newlib (L, store_lib_fn);
  68. push_int_const (L, store_enums);
  69. return 1;
  70. }