metamethods.nut 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. local base_vec={
  2. function _add(n)
  3. {
  4. return {
  5. x=x+n.x,
  6. y=y+n.y,
  7. z=z+n.z,
  8. }
  9. }
  10. function _sub(n)
  11. {
  12. return {
  13. x=x-n.x,
  14. y=y-n.y,
  15. z=z-n.z,
  16. }
  17. }
  18. function _div(n)
  19. {
  20. return {
  21. x=x/n.x,
  22. y=y/n.y,
  23. z=z/n.z,
  24. }
  25. }
  26. function _mul(n)
  27. {
  28. return {
  29. x=x*n.x,
  30. y=y*n.y,
  31. z=z*n.z,
  32. }
  33. }
  34. function _modulo(n)
  35. {
  36. return {
  37. x=x%n,
  38. y=y%n,
  39. z=z%n,
  40. }
  41. }
  42. function _typeof() {return "vector";}
  43. function _get(key)
  44. {
  45. if(key==100)
  46. {
  47. return test_field;
  48. }
  49. },
  50. function _set(key,val)
  51. {
  52. ::print("key = "+key+"\n");
  53. ::print("val = "+val+"\n")
  54. if(key==100)
  55. {
  56. return test_field=val;
  57. }
  58. }
  59. test_field="nothing"
  60. }
  61. function vector(_x,_y,_z)
  62. {
  63. return {x=_x,y=_y,z=_z }.setdelegate(base_vec);
  64. }
  65. ////////////////////////////////////////////////////////////
  66. local v1=vector(1.5,2.5,3.5);
  67. local v2=vector(1.5,2.5,3.5);
  68. local r=v1+v2;
  69. foreach(i,val in r)
  70. {
  71. print(i+" = "+val+"\n");
  72. }
  73. r=v1*v2;
  74. foreach(i,val in r)
  75. {
  76. print(i+" = "+val+"\n");
  77. }
  78. r=v1/v2;
  79. foreach(i,val in r)
  80. {
  81. print(i+" = "+val+"\n");
  82. }
  83. r=v1-v2;
  84. foreach(i,val in r)
  85. {
  86. print(i+" = "+val+"\n");
  87. }
  88. r=v1%2;
  89. foreach(i,val in r)
  90. {
  91. print(i+" = "+val+"\n");
  92. }
  93. print(v1[100]+"\n");
  94. v1[100]="set SUCCEEDED";
  95. print(v1[100]+"\n");
  96. if(typeof v1=="vector")
  97. print("<SUCCEEDED>\n");
  98. else
  99. print("<FAILED>\n");