At 12:32 PM -0500 11/14/01, Carol Mahaffy <[EMAIL PROTECTED]> wrote:
>thanks bruce -- i was kind of poking around for a definitive as to when to
>use global or property and this explained it perfectly. (even tho wasn't my
>question)

There's no universal or definitive test to determine when to use a global
variable vs. a property variable. Some people avoid global variables
altogether, preferring to encapsulate all functions inside objects (and
therefore to use property variables).

I take a middle-of-the-road approach. I use global variables when there is
only "one" of something, or when it would be very hard to "transfer" the
value of a variable from one place to another. I use properties within
objects to make it easy to create multiple instances of the object and have
them function independently.

But there is more than one way to skin a cat. Let's say I want to
frequently send messages to sprite 69. I could manually use:

sendSprite (69, #message)

But it would be inelegant to repeat that code in dozens of places. And I'd
have to change it everywhere if I changed the sprite's number.

So I could send all messages through a "wrapper" function that would be the
only place I'd have to specify the sprite number:

on contactMySprite msg
  sendSprite (69, msg)
end

But I like to keep things flexible and generalized, so I might do this:

on contactMySprite msg
  global gSpecialSpriteNum
  gSpecialSpriteNum = 69
  sendSprite (gSpecialSpriteNum, msg)
end

But that is inefficient because it redeclares the global every time the
function is called. I also like to keep my sprite numbers centralized, so I
usually put them in the prepareMovie handler, like this:

on prepareMovie
  global gSpecialSpriteNum
  gSpecialSpriteNum = 69
end

on contactMySprite msg
  global gSpecialSpriteNum
  sendSprite (gSpecialSpriteNum, msg)
end


But there are *many* other ways to accomplish the same goal. You could
broadcast the message to all sprites using sendAllSprites. That way you
don't need to know the sprite's number. But that approach is slow if there
are a lot of sprites. Unless I need to broadcast a message to multiple
sprites, I use sendSprite() instead of sendAllSprites(). (FWIW, I think you
can also use a list of sprites to target just those you are interested in.)

There are many ways to accomplish any goal. In short, it depends on your
coding style and the context in which you are making the design decision.

Regards,
Bruce






[To remove yourself from this list, or to change to digest mode, go to
http://www.penworks.com/LUJ/lingo-l.cgi  To post messages to the list,
email [EMAIL PROTECTED]  (Problems, email [EMAIL PROTECTED])
Lingo-L is for learning and helping with programming Lingo.  Thanks!]

Reply via email to