lua_store.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. if (UNLIKELY (!sif)) return luaL_error (
  12. L, "No interface defined for store type: %d.", store_type);
  13. if (clear) LOG_DEBUG("Clearing old store.");
  14. *store_p = LSUP_store_new (store_type, id, 0);
  15. if (!*store_p) return luaL_error (L, "Error creating back end store.");
  16. // Set up the store if a function for that is defined.
  17. if (sif->setup_fn && sif->setup_fn (id, clear) < LSUP_OK)
  18. return luaL_error (L, "Error initializing back end store.");
  19. return 1;
  20. }
  21. static int store_gc (lua_State *L)
  22. {
  23. LSUP_Store **sp = luaL_checkudata(L, 1, "LSUP.Store");
  24. LSUP_store_free (*sp);
  25. *sp = NULL;
  26. return 0;
  27. }
  28. // TODO add transaction handling.
  29. static const luaL_Reg store_lib_fn [] = {
  30. {"new", l_store_new},
  31. {NULL}
  32. };
  33. static const LEnumConst store_enums[] = {
  34. {"HTABLE", LSUP_STORE_HTABLE},
  35. {"MDB", LSUP_STORE_MDB},
  36. {NULL, 0}
  37. };
  38. int luaopen_lsup_store (lua_State *L)
  39. {
  40. LSUP_init(); // This is idempotent: no problem calling it multiple times.
  41. luaL_newmetatable (L, "LSUP.Store");
  42. lua_pushvalue (L, -1);
  43. lua_setfield (L, -2, "__index");
  44. lua_pushcfunction (L, store_gc);
  45. lua_setfield (L, -2, "__gc");
  46. luaL_newlib (L, store_lib_fn);
  47. push_int_const (L, store_enums);
  48. return 1;
  49. }