Class variables?

Questions about GP commands and how to do things

Moderator: MSandro

Post Reply
mguzdial
Posts: 70
Joined: Sep 15th, '15, 11:21

Class variables?

Post by mguzdial » Sep 17th, '15, 16:49

Is it possible to have class variables in GP? I was thinking about implementing the change of color function on pixels so that I only refresh every nth pixel change, or at the end of each row/column. But to do that, I'd need a count outside of any individual pixel. Could I use a class variable on class Pixel? If so, how would I initialize it -- are there class methods in GP?

Thanks!
- Mark

JohnM
Posts: 379
Joined: Sep 11th, '15, 14:42

Re: Class variables?

Post by JohnM » Sep 17th, '15, 19:09

We're trying to minimize the number of concepts in GP so, although class variables and class methods are certainly useful for experienced programmers, we've omitted them from GP.

However, GP does have "shared" variables which you might use for this task. But first, let me talk about GP variables in general.

GP has exactly three kinds of variables:

1. sprite variables (or local variables) are local to a script (i.e. a stack of blocks), are instantiated when the script is executed, and exist only for the life of that execution. The formal parameters of a function or method are just local variables whose initial values are set to the value of the parameters passed in when it is called. Thus, you can assign new values to parameter variables. Inside the GP system, we often use this feature to provide a default value when "nil" is passed in for an optional parameter, or to ensure that parameters are in range.

2. fields (or instance variables) are defined by a class. Every instance of a class has a set of fields with the same names, but each instance has its own values for those fields. When you use the "add instance variable" button you are adding a new field variable to the class. A field with that name will be added to every instance, although it will initially not have a value (i.e. its value will be "nil").

3. shared variables are global to your project. Shared variables can be used or changed by scripts in any class, and they persist until you manually delete them. Shared variables are a great place to keep track of global state, such as the score of a game.

Mark, you could use a shared variable for your pixel counter. However, you may not need to use a shared variable at all. Your pixel objects already have an "index" field. You might just add another field, call it "width", initialized when you create your pixel objects. Then the setPixel method could check to see if "index modulo width" was zero and only do a redisplay in that case to update the screen at the end of each scan line.

Post Reply