Advertisement
FocusedWolf

Lua Callback Example

Sep 8th, 2011
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.25 KB | None | 0 0
  1. class 'B'
  2.  
  3. function B:InitCount()
  4.  
  5.     self.count = 1000
  6.  
  7. end
  8.  
  9. //this - optional paremeter (can be nil) which is a copy (i think reference) of the "self" of the class that set the callback.
  10. function B:SetCallback(func, this)
  11.  
  12.     self.callBackFunction = func
  13.     self.callBackSelf = this
  14.  
  15. end
  16.  
  17. function B:RunCallback()
  18.  
  19.     if self.callBackFunction then
  20.         self.callBackFunction(self.callBackSelf)
  21.     end
  22.  
  23. end
  24.  
  25. class 'A'
  26.  
  27. local bInstance = B()
  28.  
  29. function A:InitCount()
  30.  
  31.     self.count = 7
  32.  
  33. end
  34.  
  35. function A:Work()
  36.  
  37.     if not self.count then
  38.         self.count = 1
  39.     else
  40.         self.count = self.count + 1
  41.     end
  42.  
  43.     Print(self.count)
  44.  
  45. end
  46.  
  47. function A:SetCallback()
  48.  
  49.     bInstance:SetCallback(A.Work, self) //if A:Work() didn't rely on self then it could of been done like this: bInstance:SetCallback(A.Work)
  50.  
  51. end
  52.  
  53. local aInstance = A()
  54. A:InitCount() // sets A's self.count to 7
  55. B:InitCount() // sets B's self.count to 1000
  56. aInstance:SetCallback() //tells the bInstance how to call the A:Work() function
  57.  
  58. bInstance:RunCallback() //runs A:Work() function, prints 8 to console
  59. bInstance:RunCallback() //runs A:Work() function, prints 9 to console
  60. bInstance:RunCallback() //runs A:Work() function, prints 10 to console
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement