ltm.c 1.9 KB

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