ltm.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. ** $Id: ltm.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $
  3. ** Tag methods
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define ltm_c
  7. #define LUA_CORE
  8. #define LUAC_CROSS_FILE
  9. #include "lua.h"
  10. #include <string.h>
  11. #include "lobject.h"
  12. #include "lstate.h"
  13. #include "lgc.h"
  14. #include "lstring.h"
  15. #include "ltable.h"
  16. #include "ltm.h"
  17. #include "lrotable.h"
  18. const char *const luaT_typenames[] = {
  19. "nil", "boolean", "romtable", "lightfunction", "userdata", "number",
  20. "string", "table", "function", "userdata", "thread",
  21. "proto", "upval"
  22. };
  23. void luaT_init (lua_State *L) {
  24. static const char *const luaT_eventname[] = { /* ORDER TM */
  25. "__index", "__newindex",
  26. "__gc", "__mode", "__eq",
  27. "__add", "__sub", "__mul", "__div", "__mod",
  28. "__pow", "__unm", "__len", "__lt", "__le",
  29. "__concat", "__call"
  30. };
  31. int i;
  32. for (i=0; i<TM_N; i++) {
  33. G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]);
  34. stringfix(G(L)->tmname[i]); /* never collect these names */
  35. }
  36. }
  37. /*
  38. ** function to be used with macro "fasttm": optimized for absence of
  39. ** tag methods
  40. */
  41. const TValue *luaT_gettm (Table *events, TMS event, TString *ename) {
  42. const TValue *tm;
  43. lua_assert(event <= TM_EQ);
  44. if (luaR_isrotable(events)) {
  45. tm = luaH_getstr_ro(events, ename);
  46. if (ttisnil(tm)) { /* no tag method? */
  47. return NULL;
  48. }
  49. } else {
  50. tm = luaH_getstr(events, ename);
  51. if (ttisnil(tm)) { /* no tag method? */
  52. events->flags |= cast_byte(1u<<event); /* cache this fact */
  53. return NULL;
  54. }
  55. }
  56. return tm;
  57. }
  58. const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) {
  59. Table *mt;
  60. switch (ttype(o)) {
  61. case LUA_TTABLE:
  62. mt = hvalue(o)->metatable;
  63. break;
  64. case LUA_TROTABLE:
  65. mt = (Table*)luaR_getmeta(rvalue(o));
  66. break;
  67. case LUA_TUSERDATA:
  68. mt = uvalue(o)->metatable;
  69. break;
  70. default:
  71. mt = G(L)->mt[ttype(o)];
  72. }
  73. if (!mt)
  74. return luaO_nilobject;
  75. else if (luaR_isrotable(mt))
  76. return luaH_getstr_ro(mt, G(L)->tmname[event]);
  77. else
  78. return luaH_getstr(mt, G(L)->tmname[event]);
  79. }