Is it possible to assign in lua a separately defined function to an object as the object's method with access to 'self'?

Viewed 51

Is it possible to assign a separately defined function to an object as the object's method and be able to access this object's self?

SomeObject = {name = "Jack"}

function someExternalFunction ()
    print(self.name)        
end
SomeObject.someMethodName = someExternalFunction -- this is just an example
SomeObject:someMethodName() --> prints "Jack"
1 Answers

self is not magic or anything all that special. When you call a function like object:method() this is just sugar syntax for object.method(object).

When you define a function as function object:method() it implicitly has a first arg called self so the definition is equivalant to function object.method(self)

so all you need to do is, define your external function properly and it will work fine.

SomeObject = {name = "Jack"}

function someExternalFunction(self)
    print(self.name)        
end
SomeObject.someMethodName = someExternalFunction
SomeObject:someMethodName() --prints "Jack"
Related