ltm.c 2.1 KB

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