lua_triple.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. #include "lua_lsup.h"
  2. #define check_triple(L) \
  3. *(LSUP_Triple **)luaL_checkudata(L, 1, "LSUP.Triple")
  4. /*
  5. * Factory methods.
  6. */
  7. static int new (lua_State *L)
  8. {
  9. LSUP_Triple **trp_p = lua_newuserdatauv (L, sizeof (*trp_p), 1);
  10. luaL_getmetatable (L, "LSUP.Triple");
  11. LSUP_Term
  12. *s = *(LSUP_Term **)luaL_checkudata(L, 2, "LSUP.Term"),
  13. *p = *(LSUP_Term **)luaL_checkudata(L, 3, "LSUP.Term"),
  14. *o = *(LSUP_Term **)luaL_checkudata(L, 4, "LSUP.Term");
  15. lua_setmetatable (L, -4);
  16. *trp_p = LSUP_triple_new (s, p, o);
  17. if (!*trp_p) luaL_error (L, "Error while creating a triple!");
  18. return 1;
  19. }
  20. /*
  21. * Class methods.
  22. */
  23. static int gc (lua_State *L)
  24. {
  25. LSUP_Triple *trp = check_triple (L);
  26. if (trp) LSUP_triple_free (trp);
  27. return 0;
  28. }
  29. static int get_term (lua_State *L)
  30. {
  31. const LSUP_Triple *trp = check_triple (L);
  32. const int pos = luaL_checkinteger (L, 2);
  33. if (pos < TRP_POS_S || pos > TRP_POS_O)
  34. luaL_error(L, "Out of range position: %d.", pos);
  35. lua_pushlightuserdata (L, LSUP_triple_pos (trp, (LSUP_TriplePos)pos));
  36. return 1;
  37. }
  38. static int set_term (lua_State *L)
  39. {
  40. LSUP_Triple *trp = check_triple (L);
  41. const int pos = luaL_checkinteger (L, 2);
  42. const LSUP_Term *t = *(LSUP_Term **)luaL_checkudata(L, 3, "LSUP.Term");
  43. LSUP_Term *new_t = LSUP_term_copy (t);
  44. if (pos == TRP_POS_S) {
  45. LSUP_term_free (trp->s);
  46. trp->s = new_t;
  47. } else if (pos == TRP_POS_P) {
  48. LSUP_term_free (trp->p);
  49. trp->p = new_t;
  50. } else if (pos == TRP_POS_O) {
  51. LSUP_term_free (trp->o);
  52. trp->o = new_t;
  53. } else return luaL_error(L, "Out of range position: %d.", pos);
  54. return 1;
  55. }
  56. /*
  57. * Library setup.
  58. */
  59. static const struct luaL_Reg triple_lib_fn [] = {
  60. {"new", new},
  61. {NULL}
  62. };
  63. static const struct luaL_Reg triple_lib_meth [] = {
  64. {"__gc", gc},
  65. {NULL}
  66. };
  67. int luaopen_triple (lua_State *L)
  68. {
  69. luaL_newmetatable (L, "LSUP.Triple");
  70. lua_pushvalue (L, -1);
  71. lua_setfield (L, -2, "__index");
  72. luaL_setfuncs (L, triple_lib_meth, 0);
  73. // Enums
  74. lua_pushvalue (L, TRP_POS_S);
  75. lua_setfield (L, -1, "TRP_POS_S");
  76. lua_pushvalue (L, TRP_POS_P);
  77. lua_setfield (L, -1, "TRP_POS_P");
  78. lua_pushvalue (L, TRP_POS_O);
  79. lua_setfield (L, -1, "TRP_POS_O");
  80. luaL_newlib (L, triple_lib_fn);
  81. return 1;
  82. }