Advertisement
NixillUmbreon

Lua OOP example

Dec 11th, 2014
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.06 KB | None | 0 0
  1. -- Class declaration - I usually group all of these together under a comment labeled "Classes" or "Objects"
  2. -- You also declare any arguments here.
  3. function TestClass(arg1, arg2)
  4.   -- Beginning of "values" - initialize variables and functions of the object here
  5.   local values = {
  6.     -- some test variables
  7.     val1 = 5,
  8.     val2 = arg1 + arg2,
  9.     val3 = arg1 - arg2,
  10.  
  11.     -- a test function
  12.     mix = function(tc1, tc2)
  13.       local arg1 = tc1.val2 + tc2.val2
  14.       local arg2 = tc1.val3 + tc2.val3
  15.       return TestClass(arg1, arg2)
  16.     end
  17.   }
  18.  
  19.   -- put more complex constructor code here
  20.   if math.random(1, 6) > 3 then
  21.     values.val4 = 4
  22.   else
  23.     values.val4 = 1
  24.   end
  25.  
  26.   -- ALWAYS return values
  27.   return values
  28. end
  29.  
  30. -- to create a new TestClass object
  31. a = TestClass(5, 2)
  32. b = TestClass(8, 6)
  33.  
  34. -- Assuming RFC 1149.5 compliance, the values of the two test classes should be...
  35. -- a.val1 = 5, a.val2 = 7, a.val3 = 3, a.val4 = 4
  36. -- b.val1 = 5, b.val2 = 14, b.val3 = 2, b.val4 = 4
  37.  
  38. c = a:mix(b)
  39. -- c.val1 = 5, c.val2 = 21, c.val3 = 5, c.val4 = 4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement