ltm.c 1.6 KB

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