Special Support - A great place to learn to Script

Everyone wants to learn to script, but no one really knows where to start. In my honest opinion, the best place to learn is just by reading the default scripts. I learned to script with the japanese RMXP, so I didn't have English comments at my disposal, so everyone of the new generation has that upperhand. Anyways, what I think the best thing to do to learn to script is read the default scripts, and understand each line.

So what I am offering here is support for anyone trying to learn to script. If there is a line of code you don't understand, ask me here. If there is something you want to know, like where in the script editor does something happen, ask here.
  • Ask about a certain line of code : What it means, does, etc.
  • Ask where the coding is for a certain function
PLEASE DO NOT ASK SOMETHING OTHER THAN EXISTING CODE, OR WHERE IN THE DEFAULT SCRIPTS TO FIND A CERTAIN BLOCK OF CODE. Your post will be deleted.

This is a Trial and Error topic. Hopefully, it can lead to more a use full FAQ for beginners.
ok...so could we start with something easy?
Ok. Let me give you an example of what to ask here:

Example Question A Spoiler
Example Question A wrote:
In Game_Actor, under def element_set, I am confused about this block
  #--------------------------------------------------------------------------
  # * Get Normal Attack Element
  #--------------------------------------------------------------------------
  def element_set
    weapon = $data_weapons[@weapon_id]
    return weapon != nil ? weapon.element_set : []
  end
Expand to see the code.

More importantly:
    return weapon != nil ? weapon.element_set : []
Expand to see the code.


What does that mean?


Glad you asked. That is one of my favorite tools in actions. It's really not an advanced tool, but can shorten lines pretty quickly.

Lets start from the beginning:
weapon = $data_weapons[@weapon_id]
Expand to see the code.

This line of code gets the RPG::Weapon data from the $data_weapons array, depending upon the @weapon_id (the current id of the equipped weapon) instance.

The next line, is what is called a Ternary Operator. Before we look at exactly what that line is doing, let me explain Ternary Operators...

Explanation of Ternary Operators By Seph wrote:
Ternary Operators are a C form of expression, that are mostly designed for simpler, smaller expressions, usually for returning data, setting a variable, or executing a single method.

Lets follow the flow of a simple expression, to get the TO form.
# We start with a simple, basic expression.
if a > 5
  b = 'Less Than'
else
  b = 'Greater or Equal to'
end

# Now, we can remove line breaks
if a > 5 ; b = 'Less Than' ; else b = 'Greater or Equal to' ; end

# Now in Ruby, we can switch on line expressions with a few keywords...
if a > 5 then b = 'Less Than' else b = 'Greater or Equal to' end

# Now, we can change those a few of those keywords and remove a few
# Remove the starting if, and final end
# change then to ?
# change else to :
a > 5 ? b = 'Less Than' : b = 'Greater or Equal to'

# Now, just think algebra in coding...
b = (a > 5 ? 'Less Than' : 'Greater or Equal to')
Expand to see the code.


The format of a Ternary Expression is:
boolean-expression ? expr1 : expr2
Expand to see the code.


If the boolean-expression is true, expr1 is returns/executed, otherwise epxr2 is returned/executed.

You can use this to return data (like in our method from Game_Actor), set variables (as in the example), call methods (place a method call in our expr's), etc.

Have fun!


Now that we have that under our belt, things are bit clearer.

return weapon != nil ? weapon.element_set : []

# is the same as

if weapon != nil
  return weapon.element_set
else
  return []
end
Expand to see the code.


Further note on the method: If your actor has a weapon equipped, you will be attacking with your weapons element set in the database (an array). If you don't have an element set, you are sending an empty array.


Actual Help Request Thread Spoiler
Actual Help Request Thread wrote:
Also, could you please explain some of the syntaxes around the line
MapInput::Call_Common_Event.each do |input_button, common_event_id|
Expand to see the code.
what does the || and the variables withing signify. does it mean run each key in the hash and check if it is being pressed and stores the values to each key in common_event_id?

(In reference to this code)

module MapInput
  Call_Common_Event = {Input::L => 4, Input::R => 2}
end

class Scene_Map
  alias_method :sephgubid_mapinputcallcommonevent_update, :update
  def update
    sephgubid_mapinputcallcommonevent_update
    return if $game_system.map_interpreter.running?
    MapInput::Call_Common_Event.each do |input_button, common_event_id|
      if Input.trigger?(input_button)
        $game_temp.common_event_id = common_event_id
        break
      end
    end
  end
end
Expand to see the code.


Ok. This creates a loop function, passing through all the keys and values within a Hash. What you place between the | and | marks are your iterators. Now, the each function in the Hash class requires you have two of them, the first being the local variable name for you key within the loop, and the second being the local variable name for your value. You could do it with a for loop, or a million other ways.

MapInput::Call_Common_Event.each do |input_button, common_event_id|
  # code
end

# is the same as...

MapInput::Call_Common_Event.keys.each do |input_button|
  common_event_id = MapInput::Call_Common_Event[input_button]
  # code
end

# is the same as...

MapInput::Call_Common_Event.values.each do |common_event_id|
  input_button = MapInput::Call_Common_Event.index(common_event_id)
  # code
end

# is the same as...

for input_button in MapInput::Call_Common_Event.keys
  common_event_id = MapInput::Call_Common_Event[input_button]
  # cod
end

# and there's others, but I am lazy. Haha.
Expand to see the code.


It's all a matter of preference on which loop you choose to go with. You can pass through the keys, values, or both at once.


Example where question Spoiler
Example where question wrote:
Where is all the number of items, weapons, armors held in the party, and how is it used?


First off, we will start in Game_Party. Under the def initialize method, we have this:
    # Create amount in possession hash for items, weapons, and armor
    @items = {}
    @weapons = {}
    @armors = {}
Expand to see the code.


Now, with only this much information, we can't really say what they are planning on doing with this, so let's look a little further shall we... ;)

scrolls through Game_Party code...

WAIT A MINUTE!!!
  #--------------------------------------------------------------------------
  # * Get Number of Items Possessed
  #     item_id : item ID
  #--------------------------------------------------------------------------
  def item_number(item_id)
    # If quantity data is in the hash, use it. If not, return 0
    return @items.include?(item_id) ? @items[item_id] : 0
  end
Expand to see the code.


Ok. So this is the method that reads the number of items held. Lets see, we pass the item_id to this method, and...
@items.include?(item_id) ? @items[item_id] : 0
Expand to see the code.


The .include? method checks if an item_id has been added to our Hash (@items, as initialized in the initialize method). If it has the item_id, it returns the value. That means, that our key in the @items hash, is the item_id, and the value is the number owned. If no keys is found, it returns 0 (See explanation about Ternary Operators above if you don't understand the syntax behind this line).

As you can see
  #--------------------------------------------------------------------------
  # * Gain Items (or lose)
  #     item_id : item ID
  #     n       : quantity
  #--------------------------------------------------------------------------
  def gain_item(item_id, n)
    # Update quantity data in the hash.
    if item_id > 0
      @items[item_id] = [[item_number(item_id) + n, 0].max, 99].min
    end
  end
Expand to see the code.


Here, we send the item_id, and number of the object to gain. We are setting the item_id in our @items Hash, and we are setting it with that funky looking expression on the right. The expression on the right side, is just two arrays, the major array returns the min value with the array. The minor array is within that array, and it returns the max number within itself. Which means, our item number will be

the biggest number in our minor array, but the smallest number in our major array.

The two numbers in our minor array are the number of items already owned (calling our item_number method from above), plus how every many items you are gaining (the second number passed in this method call). Our second number is just 0, which means we will never have less than this, because our minor array picks the biggest number.

The two numbers in our major array are the number that is returned in the minor array, and 99. Now, the major array returns the min number here, so if we have more than 99 of an object, it will cap it back to 99.


Summary:Items, Weapons and Armors all work the same way. Keys are the objects reference id (id to the $data_object array, such as item_id to $data_items) and values are the number owned.

(If you were wondering why I changed my narrative/tone throughout this explanation, it is to show you what should be going through your head when you don't know something. I took the position as the unknowing student, and the teacher)
Question.
Do we have to start everything by:
def ....

and then end it?
The Sea King wrote:
Question.
Do we have to start everything by:
def ....

and then end it?


Ok. In Ruby, we have quite a few keywords, that all mean something. The keyword def declares a method (A function, query or attribute of an Object). Its structured in the following manner:
[php]
def your_method_name
# your code here
end[/php]

You must have an end to end your methods. Certain keywords require the end keyword. This is why tabbing is so important: So you can keep the right number of end's.
[php]
def your_method_name
if some_boolean
case something
when x
unless z > 0
do_something
else
do_something_else
end
when y
do_something_different
end
else
do_something_crazy
end
end[/php]

This is an example of how you should tab your programming.
Where are values such as an actor's level and exp stored? Basically, what I'm trying to do is create another value (skills like in D&D) which can be read in message boxes.
Sailerius wrote:
Where are values such as an actor's level and exp stored? Basically, what I'm trying to do is create another value (skills like in D&D) which can be read in message boxes.


The quick answer:
$game_actors[actor_id].level
$game_actors[actor_id].exp
Expand to see the code.


Actor data is stored in a "wrapper hash/array class", $game_actors. Now, each object in this class is a Game_Actor object. Each Game_Actor class has the two instances, @level, and @exp, both are readable.

So, here's the important parts.

Game_Actors:
#==============================================================================
# ** Game_Actors
#------------------------------------------------------------------------------
#  This class handles the actor array. Refer to "$game_actors" for each
#  instance of this class.
#==============================================================================

class Game_Actors
  #--------------------------------------------------------------------------
  # * Object Initialization
  #--------------------------------------------------------------------------
  def initialize
    @data = []
  end
  #--------------------------------------------------------------------------
  # * Get Actor
  #     actor_id : actor ID
  #--------------------------------------------------------------------------
  def [](actor_id)
    if actor_id > 999 or $data_actors[actor_id] == nil
      return nil
    end
    if @data[actor_id] == nil
      @data[actor_id] = Game_Actor.new(actor_id)
    end
    return @data[actor_id]
  end
end
Expand to see the code.


So, everytime you access $game_actors#[], it either creates an actor and adds to the @data array as a new actor (at it's initial state), or returns the Game_Actor object in the @data array.

Then in Game_Actor, you can see:
#==============================================================================
# ** Game_Actor
#------------------------------------------------------------------------------
#  This class handles the actor. It's used within the Game_Actors class
#  ($game_actors) and refers to the Game_Party class ($game_party).
#==============================================================================

class Game_Actor < Game_Battler
  #--------------------------------------------------------------------------
  # * Public Instance Variables
  #--------------------------------------------------------------------------
  attr_reader   :level                    # level
  attr_reader   :exp                      # EXP
Expand to see the code.


Here, you can see that the level and exp are readable in Game_Actor objects.

So, to get our actor data, we use:
$game_actors[actor_id]
Expand to see the code.


From there, we just need to read our level and exp.
$game_actors[actor_id].exp
# or
$game_actors[actor_id].level
Expand to see the code.





So, you are wanting to have this shown in Messages? Just use:
a = $game_actors[actor_id]
l = a.level
# or
e = a.exp
$game_variables[x] = l
# or
$game_variables[x] = e
Expand to see the code.


Then just use the \v command.
Thank you for the speedy and most informative reply. :) That answers my question.
where are the slide in windows methods stored in the sdk version 2.3?

Slide in windows = windows that aren't just shown on screen at once but are moved from beyond the borders of the screen to a specific point on the screen like x = 100, y = 0.
That's Trickster's Movable Module, in the MACL 2.1. Not really what this thread is for, but I am a nice guy. I won't get into details, but will tell you how to use it:

If you use the MACL 2.1+, for any window/sprite, call out:
your_window.move_x(x, speed)
# or
your_window.move_y(y, speed)
Expand to see the code.
Where is the opacity for an event stored? That's a question that has been bothering me for some time, but didn't think of asking :D
Quote:
Where is the opacity for an event stored? That's a question that has been bothering me for some time, but didn't think of asking


Game_Character holds all the data the events. In Game_Character, there is an instance call @opacity. Sprite_Character reads this instance, and sets the sprite's opacity according to this value.

So if you wanted to change it, add this in Game_Character 1
  attr_accessor :opacity
Expand to see the code.



Then just use:
$game_map.events[event_id].opacity = n
Expand to see the code.


Sorry for not going in-depth on this explanation. I just woke up and can barely open my eyes. XD
Great, I get the idea now. But another question arises, this time about loops.

Here is how I've set up the loop:

    loop{
    $game_map.events[event_index].opacity -= 10
    @n += 1
      if @n = 25
        break
      end
    }
Expand to see the code.


The idea was to make the loop reduce the opacity with 10 each frame, but instead it instantly reduces it to 0. That wasn't how I had planned it. event_index is the event ID that will be changed.

Could you tell me what's wrong with it, and how to fix it?

Thanks
The thing is, it never breaks.

Your main problem is: if @n = 25

In boolean-expressions, you need to have the == operator.
    loop do
      $game_map.events[event_index].opacity -= 10
      @n += 1
      break if @n == 25
    end
Expand to see the code.


That's how I would do it.
If I may, I'd like to ask a... "void-question".
It's just something the Translated RMXP Help File didn't explained very clearly for me:

What's the real function of the return?
Quote:
If I may, I'd like to ask a... "void-question".
It's just something the Translated RMXP Help File didn't explained very clearly for me:

What's the real function of the return?



Return does a few things.

In query methods in object classes, return returns a value when a method is called. Like so:
def add_three_to(x)
  return x + 3
end

add_three_to(1) # => 4
add_three_to(4) # => 7

def is_greater_than_5?(n)
  return n > 5
end

is_greater_than_5?(3) #=> false
is_greater_than_5?(8) #=> true
Expand to see the code.


We sometime use it to stop a block of code as well.
def refresh
  if $game_party.gold == @gold
    return
  end
  @gold = $game_party.gold
  # ...
end
Expand to see the code.


When they gold value in $game_party is the same as the @gold instance in that class, the method is returned, and nothing after the return is executed.
return? mmm... it seems to let you get a result. When I use it as part of a def method inside an Interpreter class, it allows me to get a result, in this case it changes an expression I selected with a script call that lets me start a specific process defined in certain script(s). Does it have any other function?

This is something that confuses me a lot.
what is the difference between alias_method and just alias? How could anyone use them properly?
class Bitmap
  #--------------------------------------------------------------------------
  # * Public Instance Variables
  #--------------------------------------------------------------------------
  attr_accessor :blur_settings
  attr_accessor :anim_sprite_settings
  #--------------------------------------------------------------------------
  # * Class Variables
  #--------------------------------------------------------------------------
  class_accessor :default_blur_settings, :default_anim_sprite_settings
  #--------------------------------------------------------------------------
  # * Alias Listings
  #--------------------------------------------------------------------------
  [color=red]alias_method[/color] :seph_macl_bitmap_init, :initialize
  #-------------------------------------------------------------------------
  # * Object Initialization
  #-------------------------------------------------------------------------
  def initialize(*args)
    # Original Bitmap Initialization
    seph_macl_bitmap_init(*args)
    # Set Bitmap Settings
    @blur_settings        = @@default_blur_settings
    @anim_sprite_settings = @@default_anim_sprite_settings
  end
...
end
Expand to see the code.
Like I said, return returns a value, or ends a block (or big block, like a method call).

Quote:
what is the difference between alias_method and just alias? How could anyone use them properly?


Nothing, sorta.

alias is embedded into Ruby library. It's a hidden method we can never really get access to. However, alias_method is a method in the Module class. It probably looks just like this:
class Module
  def alias_method(new_method_name, old_method_name)
    alias new_method_name old_method_name
  end
end
Expand to see the code.


However, I use it in all my scripts because I program with and for the SDK. The SDK has a log_alias method, that logs aliases. So we in the SDK, aliased the alias method, to call this SDK.log_alias method whenever the alias_method method was called. So instead of:
class X
  alias new old
  SDK.log_alias(X, new, old)
Expand to see the code.

We just use the alias_method like you see above. We log aliases in the SDK to check for script conflicts, in the event a script over-writes a method. It took me a while, but I got it to work if you overwrote a method that was essential to another script, an error was raised.

Another reason is stack errors. Thanks to the wonderful F12, stack errors happen a lot in aliases, so once again, in the SDK, we used the alias_method to check and prevent stack errors.
so you're trying to avoid any of those stack too deep error messages... Interesting. Thanks, Seph.
Quote:
We sometime use it to stop a block of code as well.
def refresh
  if $game_party.gold == @gold
    return
  end
  @gold = $game_party.gold
  # ...
end
Expand to see the code.


When they gold value in $game_party is the same as the @gold instance in that class, the method is returned, and nothing after the return is executed.

Eah.. That was my doubt. :D
I was concerned especially about the alone returns.

So this, basically means:
"If the variable gold is equal to the party gold, stop the things here. If it is not, make the variable gold be the same as party gold.", right?

Thanks, thing I got it. :3
def foo
  return
end
# Is the same as
def foo
  return nil
end
Expand to see the code.


Every method returns and object when called or nil.
nil can be considered as the empty return or that nothing is return.

The difference between return and return nil is on the conceptual level.
Usually you use return nil when a value is expected from the method and return when a value is not expected.

To give you an idea of every method call returns an object or nil can be illustrated by the p method:
p p p 3
Expand to see the code.


Try it out ^^

*hugs*
- Zeriab
Where do I find the exact definition of the objects created in the database and loaded in Scene_Title?
# Load database
    $data_actors        = load_data("Data/Actors.rxdata")
    $data_classes       = load_data("Data/Classes.rxdata")
    $data_skills        = load_data("Data/Skills.rxdata")
    $data_items         = load_data("Data/Items.rxdata")
    $data_weapons       = load_data("Data/Weapons.rxdata")
    $data_armors        = load_data("Data/Armors.rxdata")
    $data_enemies       = load_data("Data/Enemies.rxdata")
    $data_troops        = load_data("Data/Troops.rxdata")
    ...
Expand to see the code.


many of them I have already figured out by their use, but is there some documentation about them? $data_actors for example...
thanks
The editor itself saves the objects whenever you save your project to the rxdata files. It automatically dumps all the objects you set in the database editor into your rxdata files, as well as all the map data files from the map editor.

If you check the help file, under RPGXP-DataStructure, you can see all these classes instances. Basically, all the Data_Objects are a simple:
class DataObject
  attr_accessor :attribute
end
Expand to see the code.


To be honest, there isn't even an initialize method (well, there is, but we can't see or, or modify it).

They are basically just simple instance-holding objects. Whatever you set in the database is what is held in these instances for each object.

All else fails, just use:
p $data_x[1].instance_methods
Expand to see the code.


That will show you all the instance methods, granted, some will be from the higher level classes in there as well.
There is an initialize method. If you look at the Data_Objects in the help-file you can see their initialize method. You can also change it.
It doesn't really serve much purpose unless you intend to create new Data_Object since the initialize method is by default not called on any of the data objects.
nevermind :)
Ahh.. Things are getting bad. Looks like all I try to make ends with an error. :(

Okay, let me try to ask here...
I am trying to fix a incomplete script made I asked OS. But also modifing the way it works. Whatever... Giving details of what I want to do won't help now.


I just want to know what's wrong with these lines:
Content Hidden Spoiler
def target
    if @jump_image?
    target = Sprite.new
    target.bitmap = Bitmap.new("Graphics/Pictures/target")
    target.x = @x
    target.y = @y
  else
    target = nil
    end
  end
end
Expand to see the code.

The game crashes even before it initialize, pointing an error on the line "target = sprite.new".

Oh, as my knowledge on scripts is really taaaaaad, let I explain what I think I'm doing there. :P
I'm trying to make these lines mean:
If @jump_image is true
create an image(target)
else case
  delete the image(target)


If posting the full script at the moment helps, here it is:
Content Hidden Spoiler
#==========================#
# Game_Event Edit          #
# By OS                    #
# Version 1.2                               #
#==========================#
# Use:                     #
#                          ######################################
# Call Script: $game_map.events[id].jump_event!                 #
# Conditional Branch: Script: $game_map.events[id].jump_event?  #
# <> (Inside ConBranch) Self Switch/Switch                      #
# Page 2 with Jump Event Image and Jump Code                    #
#===============================================================#
class Game_Event
  def jump_event!
    @jump = true
  end
 
  def jump_image!
    @jump_image
    end
 
  alias os_updt update
  def update
    os_updt
    if jump_event?
      if (@x - $game_player.x <= 2) || ($game_player.x - @x <= 2) || (@y - $game_player.y <= 2) || ($game_player.y - @y <= 2)
        @jump_image = true
      else
        @jump_image = false
      end
    end
    return
  end
 
  def jump_event?
    if @jump != nil
      return @jump
    end
    return
  end

  def target
    if @jump_image?
    target = Sprite.new
    target.bitmap = Bitmap.new("Graphics/Pictures/target")
    target.x = @x
    target.y = @y
    end
  end
end
Expand to see the code.
what does $ stand for?
and wat # stand for?
XDarknessBoyX wrote:
what does $ stand for?
and wat # stand for?


$ is the prefix to a Ruby global variable. Global variables can be accessed from anywhere within the program.
# is the precursor to a Ruby comment. A comment is a piece of code that is effectively skipped by the compiler. It's used to help the one reading the code better understand what the code is trying to accomplish.

# Return if the player is nil
return if $game_player.nil? # No need to do anymore work.
...
Expand to see the code.


I have a question about RGSS though. If I have a sprite and I initialize it's bitmap. Does calling sprite.dispose also dispose of the bitmap contained within the sprite. Or do I still have to call sprite.bitmap.dispose then sprite.dispose?
It is relatively simple to find out khmp. Simply do something like this:
b = Bitmap.new(23,32)
s = Sprite.new
s.bitmap = b
p s.disposed?, b.disposed?
s.dispose
p s.disposed?, b.disposed?
Expand to see the code.


That code will answer your question and the answer is that sprite.dispose does not dispose its bitmap.
This is useful if you want several sprites to have the same bitmap.
Thanks Zeriab, I tried making a test like that checking for nil status. I guess they weren't being set to nil after disposal. :)

Original thread: https://www.hbgames.org/forums/viewtopic.php?t=33070