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