Types in BlitzBasic = Class in Monkey?
Monkey Forums/Monkey Beginners/Types in BlitzBasic = Class in Monkey?
| ||
Hello again, I am used to using "Types" in BlitzBasic, and I see in Monkey they are similar to Classes. Here I made a function that creates a new "fish": Function NewLevel() Local f:fish = New fish f.x = 100 f.y = Rnd(0,DeviceHeight()) f.scale = .2 f.img = LoadImage("fish.png") End Function But when I try to access it in Method OnRender() like this: DrawImage f.img,f.x,f.y,0,f.scale,f.scale It simply says identifier 'f' not found. What is happening? |
| ||
You made it local to that function. |
| ||
I tried to use Global instead of Local but it just gave me an error. |
| ||
What kind of error? |
| ||
Syntax error unexpected token 'global' |
| ||
Try something like this: Or use internal methods: |
| ||
Make sure you don't use Global inside a Method or a Function. |
| ||
You should take a look to variable scopes. A local variable exists only in the block it is defined. As instance, if you declare a local variable into a Function, it won't be accesible from outside that function. If you declare a variable inside a While block, it won't be accesible outside the while block, if you declare a local variable inside a For loop, the same... etc... Then there are global variables. Those variables, when they're defined outside a class and outside a function, they can be accessed form everywhere. They're "regular" globals. And then, there are class members, which can be fields or globals too. Fields are memebers of each instance of a class, while globals inside classes are shared in all class instances. Example: Function Main() Local myItem:= New MyClass myItem.x = 100 myItem.y = 200 local myotherItem:= New MyClass myotherItem.x = 50 myotherItem.y = 75 Print myItem.x + ", " + myItem.y Print myotherItem.x + ", " + myotherItem.y MyClass.Score = 200 Print myItem.Score Print myotherItem.Score End Class MyClass Global Score:Int = 0 Field x:Int, y:Int End |
| ||
Thank you guys! And how would I go about deleting each fish entity when I am done with it? (Like when it swims off the screen) |
| ||
Use a LIST to have control over all fishes! In New() add the new fish to the list with LIST.ADDLAST(). Call the function DrawAll() instead of calling each single fish. Use CheckAll() to control, whether a fish should be removed. Remove the fishes with LIST.REMOVE()Class Fish Field x:Float Field y:Float Field img:Image Field scale:Float Global Fishes:List<Fish>= New List<Fish> Method New(x:Float, y:Float, scale:Float, img:Image) self.x = x self.y = y self.scale = scale self.img = img Fishes.AddLast self End Function DrawAll:Void() For local locFish:Fish = Eachin Fishes locFish.Draw() Next End Method Draw:Void() DrawImage(img, x, y, 0, scale, scale) End Function CheckAll:Void() For local locFish:Fish = Eachin Fishes If locFish.y<0 Fishes.Remove locFish Next End End |