Advertisement
Francoo

Metatables examples

Jun 16th, 2015
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.88 KB | None | 0 0
  1. -- factorial.lua:
  2.  
  3. function fact (n)
  4.     if n == 0 then
  5.         return 1
  6.     else
  7.         return n * fact(n-1)
  8.     end
  9. end
  10.  
  11. -- print("enter a number:")
  12. -- a = io.read("*number")        -- read a number
  13. -- print(fact(a))
  14.  
  15. -- test1.lua:
  16.  
  17. dofile('factorial.lua')
  18.  
  19. local x = {1, 2, 3, 4, 5, value = 3}
  20.  
  21. local mt = {
  22.   __add =
  23.   function (lhs, rhs) -- "add" event handler
  24.     return { value = lhs.value + rhs.value }
  25.   end,
  26.   __mul =
  27.   function (lhs, rhs) -- "add" event handler
  28.     return { value = lhs.value * rhs.value }
  29.   end
  30. }
  31.  
  32. setmetatable(x, mt) -- use "mt" as the metatable for "x"
  33.  
  34. local y = x + x
  35.  
  36. print(y.value)
  37.  
  38. local z = x * x
  39.  
  40. print(fact(z.value))
  41.  
  42. -- test2.lua:
  43. -- Creates 'vector' table with a "vector space" metatable such as it assigns the vector_metatable metatable to every value set on 'vector'. The vector_metatable allows sum and dot product of vectors of same size. Only for testing purposes.
  44.  
  45. local vector = {}
  46.  
  47. local vector_metatable = {
  48.     __add =
  49.     function (lhs, rhs)
  50.         local res = {}
  51.         for i=1,table.maxn(lhs) do
  52.             res[i] = lhs[i] + rhs[i]
  53.         end
  54.         return res
  55.     end,
  56.     __mul =
  57.     function (x, y)
  58.         if type(x) == 'table' then
  59.             lhs = y
  60.             rhs = x
  61.             else if type(y) == 'table' then
  62.                 lhs = x
  63.                 rhs = y
  64.             end
  65.         end
  66.         if type(lhs) == 'table' then
  67.             local sum = 0
  68.             for i=1,table.maxn(rhs) do
  69.                 sum = sum + lhs[i] * rhs[i]
  70.             end
  71.             return sum
  72.         else
  73.             local res = {}
  74.             for i=1,table.maxn(rhs) do
  75.                 res[i] = lhs * rhs[i]
  76.             end
  77.             return res
  78.         end
  79.     end
  80. }
  81.  
  82. local vspace_metatable = {
  83.     __newindex =
  84.     function (t, key, value)
  85.         setmetatable(rawset(t, key, value)[key], vector_metatable)
  86.     end
  87. }
  88.  
  89. setmetatable(vector, vspace_metatable)
  90.  
  91. vector.x = {1, 2, 3, 4, 5}
  92.  
  93. vector.z = {3, 7, 5, 1, 0}
  94.  
  95. local y = vector.x * vector.z
  96.  
  97. if type(y) == 'table' then
  98.     for i=1,table.maxn(y) do
  99.         print(y[i])
  100.     end
  101. else
  102.     print(y)
  103. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement