I know I had found a way to work this out but I have forgotten it. I’m basicly creating an instance of a class which has a self function I would like to pass to another class. This class returns values in the callback. Here is a very simplified version of what I am trying to do. I’m sure it’s simple but i just cant see it. I hope this example explains it better then I’m trying to!
--# Main
function setup()
t = test()
end
function draw()
background(40, 40, 50)
end
--# test
test = class()
function test:init()
self.buffer = " "
-- you can accept and set parameters here
self.cbtest = callbacktest(self:callback)
end
function test:callback(txt)
self.buffer = txt
print(self.buffer)
end
--# callbacktest
callbacktest = class()
function callbacktest:init(cb)
-- you can accept and set parameters here
self.txt = "Hello World"
self.cb = cb
self.cb(self.txt)
end
I updated the example to more accurately represent what I’m trying to do. I know I can do this with Globals but I’d really like to keep it within the class. This is to allow my ui button class to communicate with custom keyboards made up of the button class.
This does what you want i think (from initial example) 2 modifications.
--# Main
function setup()
t = test()
end
function draw()
background(40, 40, 50)
end
--# test
test = class()
function test:init()
-- you can accept and set parameters here
self.cbtest = callbacktest(self.callback) -- replace the : by .
end
function test:callback(txt)
print(txt)
end
--# callbacktest
callbacktest = class()
function callbacktest:init(cb)
-- you can accept and set parameters here
self.txt = "Hello World"
self.cb = cb
self.cb(nil,self.txt) -- cb = test.callback has 2 inputs: (self,text). self is not used so can be nil
end
I ended up just assigning the callback function to a self variable. Seemed to fix the issue. I believe its similar to what you did @Jvm38. Thank you
--# Main
function setup()
t = test()
end
function draw()
background(40, 40, 50)
end
--# test
test = class()
function test:init()
self.buffer = "Foo "
self.cb = function(txt) print(self.buffer..txt)end
-- you can accept and set parameters here
self.cbtest = callbacktest(self.cb)
end
--# callbacktest
callbacktest = class()
function callbacktest:init(cb)
-- you can accept and set parameters here
self.txt = "Bar"
self.cb = cb
self.cb(self.txt)
end
@Jvm38 your example works well, however I did not have a correct example. The callback needs to be able to access self. When the callback is called and nil is passed it is unable to access self.
It sounds like what you want is a method bound to self that can be passed around like a normal function. Read this thread (about half way down to @toadkick’s entry for a function named “bind”):