Question over first quiz and the "callback" function

I was hoping to get an explanation on how the “callback” function as defined in the solution actually works. I understand that it is used to pull the message data from the /kobuki/laser/scan topic, but how can it write to the pub.publish object before it is “created” in the program since this is on the following line? I believe my confusion is with the callback function itself.

Is there any way to have the msg.ranges accessible outside of the callback function? I assume we could use a class to do this, but I wasn’t sure if there was a better way.

Also how is this data accessible outside of the function itself. Are things written to objects essentially “global” variables in that sense?

Thank you for the help!

Hi @battistini.jarrett,
Usually you want to be working with classes, it avoids using ugly global variables and let’s you assign shared variables for the class.

The callback function itself is just a ‘normal’ function, and can contain any code. The only special feature is, that it get’s called every time, a new topic get’s published. So you can put your control code there too. If you put the callback and your code inside a class, you can just do the following

class my_class():
    def callback(self, msg):
        self.ranges = msg.ranges