fork download
  1. local generic_func = function(table, x)
  2. return table.pos + x
  3. end
  4.  
  5. local obj = { pos = 1}
  6. local unrelated = { pos = "42" }
  7.  
  8. function obj:func1(x)
  9. return self.pos + x
  10. end
  11.  
  12. function obj.func2(object, x)
  13. return object.pos+x
  14. end
  15.  
  16. obj.func3 = generic_func
  17.  
  18. -- identical results, no matter how you call it
  19. print(obj:func1(2))
  20. print(obj.func1(obj, 2))
  21. print(obj:func2(2))
  22. print(obj.func2(obj, 2))
  23. print(obj:func3(2))
  24. print(obj.func3(obj, 2))
  25. print(generic_func(obj, 2))
  26.  
  27. -- function from "obj" runs on unrelated table
  28. print(obj.func1(unrelated, 2))
  29.  
Success #stdin #stdout 0s 14120KB
stdin
Standard input is empty
stdout
3
3
3
3
3
3
3
44.0