ltm.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. /* These must be correspond to the LUA_T* defines in lua.h */
  16. const char *const luaT_typenames[] = {
  17. "nil", "boolean", "lightfunction","number", // base type = 0, 1, 2, 3
  18. "string", "table", "function", "userdata", "thread", // base type = 4, 5, 6, 7, 8
  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. "__metatable"
  29. };
  30. int i;
  31. for (i=0; i<TM_N; i++) {
  32. G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]);
  33. stringfix(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 = luaH_getstr(events, ename);
  42. lua_assert(event <= TM_EQ);
  43. if (ttisnil(tm)) { /* no tag method? */
  44. if (isrwtable(events)) /* if this a (RW) Table */
  45. events->flags |= cast_byte(1u<<event); /* then 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. case LUA_TROTABLE:
  55. mt = hvalue(o)->metatable;
  56. break;
  57. case LUA_TUSERDATA:
  58. mt = uvalue(o)->metatable;
  59. break;
  60. default:
  61. mt = G(L)->mt[ttnov(o)];
  62. }
  63. return (mt ? luaH_getstr(mt, G(L)->tmname[event]) : luaO_nilobject);
  64. }