RGSS3 - Creating an Instance of a Class

I am interested to know how to create an instance of my own class. I noticed how $game_actors, $game_party, $game_troop and $game_map exist and I am very interested how good this feature would be if it would be applicable on my class. For example I have a class:

class RubySampler attr_accessor :access_database def sampler_get_value(ruby_value) @access_database = ruby_value endendyou'd probably tell me that I can do:

ruby_sampler = RubySampler.newruby_sampler.sampler_get_value(21)to call the method, but what if I want to do something like:

$ruby_sampler.sample_get_value(value)How can I do that?
You'd need to create a global variable to do that (all global variables begin with $), but that is not recommended. There's not much reason to make yourself a new global variable. If you want something to be globally available, it's usually recommended you put it in Game_Temp for data that does not need to be saved, and Game_System for data that does need to be saved.

What were you thinking about for making it a global variable? You may have a case where it is appropriate, but most of them aren't.
What were you thinking about for making it a global variable? You may have a case where it is appropriate, but most of them aren't.
Even the global variables used by RPG Maker by default are just evidence of lazy design, not good practices. I'm actually somewhat frustrated by the fact that many people who want to learn Ruby in order to script for RPG Maker are being fed a lot of generally messy coding habits as the norm for the program -- obviously, that's what the core scripts do, so it can't be a bad thing, right?


Well, it can be, and it often is. The only decent use I've seen of a global variable in the community has been the adoption of $imported, and that's only because it has practically become a standard at this point.


HeartFire, I understand why you want to do this, but you will learn far more by following Ruby community standards than you will by following the standards of RPG Maker itself. The program and its core scripts are practically overflowing with coding practices that were used for convenience rather than good design -- they are, generally, not the example to follow.
To attach an object onto a global variable - simply add $ before the start of the variable name. This can be cdone from anywhere at anytime. HOWEVER...

Your code has no reason / need to create a global variable. It will simply sit there eating processing power until it has been called - which I am assuming wont be very often.

Alternatively... You could do this instead....

#===============================================================================    # RubySampler.sampler_get_value(ruby_value)# RubySampler.access_database#===============================================================================    module RubySampler#===============================================================================      #-----------------------------------------------------------------------------  #  #-----------------------------------------------------------------------------  @access_database = nil  #-----------------------------------------------------------------------------  #  #-----------------------------------------------------------------------------  def self.sampler_get_value(ruby_value)    @access_database = ruby_value  end  #-----------------------------------------------------------------------------  #  #-----------------------------------------------------------------------------  def self.access_database    @access_database  endendThis changes things so that you no longer need any sort of global variable to keep track of the information.

Edit:

If you are insistant of having a global variable - I would recommend adding it to the $game_temp's existing class...
$ruby_sampler = RubySampler.new


though if you really only 1 instance of that, just make it a module as Dekita posted above


so you can just do it like RubySampler.access_database for example
I'll try this, thank you so much Dekita 🙂 It's still my first time to learn any coding so this might take for a while to understand why I am using this or that, as for now I really don't have idea why I am using global variables or instance variables, but if it is necessary to use global or instance, please enlighten me. Thank you 🙂
well according to them, design-wise it's apparently not a good idea to use global variables unless really needed
well according to them, design-wise it's apparently not a good idea to use global variables unless really needed
That's a pretty universal rule actually. Sort of like not using 'goto' [see Knuth's paper for the two 'acceptable' uses, both of which are accommodated in most languages in one form or another]. The problem with global variables is they completely override any scope considerations your program has and wreak havoc with the modularity of your code.

While the RGSS scripts are generally well written and documented, that's a design flaw they went with. I can guess why, but it doesn't make it good design - especially since you won't have the same issues they did (the scripts you see are only a portion of what there is, then you have the engine code itself).

Parameters are your friend. Learn to use them and the 'need' for global variables often goes away.
A global variable is akind to a normal variable just with different scoping.

Yup, as Dekita mentioned you can simply do this:

$ruby_sampler = RubySampler.new$ruby_sampler.sampler_get_value(21)
Feel free to run along with creating global variables. When you get burned the lesson of why using global variables typically is bad design will probably stick much better.

I don't mind people coding badly as long as it's just a phase they go through and I don't have to maintain their code.

*hugs*
I'll try this, thank you so much Dekita 🙂 It's still my first time to learn any coding so this might take for a while to understand why I am using this or that, as for now I really don't have idea why I am using global variables or instance variables, but if it is necessary to use global or instance, please enlighten me. Thank you 🙂
I was like that as well - unsure why certain methods where better than others (according to the help I gained from these forums).

After a while you realize why certain things work the way they do.

Personally, I only create a new global variable for a 'game object' similar to the default database. Really there is no need for me to do that either...

So far my global variables are...

$D13x_HUD - which is constantly shown and used during the 'HUD_Spriteset' code, it makes ALOT of huds - player / hotkeys / menu key huds etc..

and

$bank - which is used only during bank transactions - I made it global so you could use $bank.add_gold etc.. and make it easier for the user to remember the call..

And realistically - I only really made those two variables cause I could. Both could have (and probably should have) just been added to the $game_player variable / Game_Player class.

Actually - there are two global variables I made which are 'acceptable'... $deki_weaps and $deki_armrs - which are both used to completely overwrite the way the game handles equipment and allow for unique equip -(weapons have differentiations from each other).

Kind of went on a bit of a rant there...

I hope that this give you a little better information on why one would use a global variable.
Global variables allow access to the objects they point to. Having access to your object everywhere is quite useful.

Of course it does come with a cost. Lemme illustrate one potential pitfall:

$my_var = 42foo.bar$my_var += 1  # Who knows what $my_var may be at this point
Code:
my_var = 42foo.barmy_var += 1  # We can be pretty confident that my_var is 43 at this point
@dekita:

Protecting access to your global variables through say module functions would in all likelihood be preferable.

For the add_gold bank example you can write code such as this and slowly change your code to use that instead.

module Bank  module_function  def add_gold(*args)    $bank.add_gold(*args)  endend*hugs*
@Zeriab,

Thats really simple, yet really clever. I had'nt thought of doing anything like that at all. Think some scripts will be getting some adjustments later today to accomodate that 🙂

Only my bank and hud script though as the unique equipment script doesnt allow access to the variable (well, of course you could access it should you wish) but its only used in the code and not 'advertised' to devs for using.

Edit:

why module_function rather than self. ? personal preference or is there an advantage?
I asked a scripter from rpgmakervxace.net and he said that he uses the global variables because it can be accessed whenever he wanted to. On my own understanding, he meant something like:

$value = 10class RubySample def print_my_value value = $value puts value endendso whenever I access this as:

ruby_sample = RubySample.newruby_sample.print_my_valueit would print me 10. But whenever I do a script call and say:

$value = 90it would print me 90.

I want to ask everyone, what are the drawbacks of using these types of variables?
I asked a scripter from rpgmakervxace.net and he said that he uses the global variables because it can be accessed whenever he wanted to.

<snip>

I want to ask everyone, what are the drawbacks of using these types of variables?
The drawback of global variables is they can be accessed from anywhere (ie: whenever he wants to).

This is always true, but even moreso in OO programming (and Ruby is as OO as it gets) - you want to shield your variables and even methods from outside their classes as much as possible. For example, you should never change a variable directly - call a method to change it (where you can have bounds checking and other failsafe mechanisms). Many methods should not be called outside of the class they belong to (ie: keep them private).

Think of each class as having it's own API that the rest of the program can see and has to use to interact with it. In the beginning, it seems like a lot of extra work and limitation: and it is extra work, in the beginning. Once you start maintaining your own code, and making changes/upgrades, you realize that leaves you free to change the internal structure of a class without having to worry about it 'breaking' any other code anywhere else, so long as you leave that external API (the 'public' method calls) intact. You can even change the body of the public methods, so long as the input and output remain the same.

Global variables can be called from anywhere, which in practice means they do called from anywhere, and trying to keep track of all that for anything non-trivial becomes a major PITA, even with text searching. You've got to find all the calls, then figure out why you were changing it there (ie: WTH were you thinking...) so you can 'fix' it, or at least leave it not broken when you change something somewhere else. They are a major cause of intermittent, hard to track down bugs. Don't get me started on what they can do with concurrent programming...

There are certain rules of structure and style that have been hammered out by programmers through theory, trial and error, and experience over the past 50 years. It may not be immediately apparent to you why those rules exist, but until you understand them, it's best to follow them. I had an English teacher once who said we were allowed to break any grammatical rule we wanted in our papers: so long as we listed the rule at the end and why we broke it.

One of the best practical sources I've come across recently is in the documentation for the Unreal Engine 4 - specifically the style guidelines that must be followed for any source code to be submitted back to them for possible inclusion in the engine. They explain every style decision they made, giving their reasoning. Some things are a matter of preference (the 'religious' brace wars), but there's a lot of other things in there that are good practices no matter what language you're coding in (they use C++).

RGSS throws a few curveballs at us - not being able to see all the scripts (though we can see the 'API' for them through the help files), and the engine code being tucked away. If you try to do any scripting through events you have the logistical limitation of that damn box (who thought that was a good idea?). Even with those limitations, 95+% of the time you can get what you want without having to go too far off the reservation.
Well, for a start, it is constantly using a small amount of processing power.

When using a global variable you can never truly know what that variable holds until it has been called. There could be another script thats interfering with it in some fashion which causes it to act different compared to your expectations. This is because the variable is global, and can therefore be changed / modified at any point.

you could have slightly mistyped some kind of operator sequence which causes the variable to change to something else completely, ie, from a value to an actors data.

Yes, it is true that it can be accessed from anywhere at any time; however, there are other ways of achieving this effect, such as modules && class variables.

Edit: Mousers explanations is much better 🙂
The drawback of global variables is they can be accessed from anywhere (ie: whenever he wants to).

<explanation>
Thank you very much for explaining this. Now it has some light on me about global variables that far.

Yes, it is true that it can be accessed from anywhere at any time; however, there are other ways of achieving this effect, such as modules && class variables.
How can I change values from the module exactly? I've been doing some modules for my ruby exercise but I can't seem to change the value of the module and it says its constant.
module Example class << self attr_accessor :value end @value = 'Initial value.'endExample.value # => "Initial value."Example.value = 'Hopefully this helps.'Example.value # => "Hopefully this helps."Modules are different from classes -- they are never instanced. As such, to get proper readers, writers, and accessors for an instance variable, you have to define them on the singleton class of the module. Just defining a reader, writer, or accessor defines it on the instance, but... as said, modules do not have them. That's the reasoning for the class << self portion above -- it defines the accessor on the class rather than an instance of it.(There's actually much more to modules, classes, and instances than this, by the way.)
For more information in global variable and singleton in game programming: http://gameprogrammingpatterns.com/singleton.html

Also, I found this ebook was so good for beginners in game programming xD
I'm still a bit puzzled though... most of that can still happen even in things like instance variables... I think most of it will depend on how you use it


and even instance variables that has no accessor/reader/writer made by you can actually be accessed outside of the class/module
and even instance variables that has no accessor/reader/writer made by you can actually be accessed outside of the class/module
If a method or variable is declared private, you shouldn't be accessing it from the outside.

Original thread: https://forums.rpgmakerweb.com/threads/rgss3-creating-an-instance-of-a-class.26293/