You are on page 1of 172

RGSS Reference Manual Page 1 of 172

RGSS Reference Manual


RGSS (Ruby Game Scripting System) uses the object-oriented scripting language Ruby to develop 2D games for the
Windows® platform.

Contents

z RGSS Specifications
z Ruby Syntax
{ Syntax and Expressions
{ Variables and Constants
{ Literals
{ Operator Expressions
{ Control Structures
{ Method Calls
{ Class and Method Definitions
z Standard Library
{ Built-in Functions
{ Built-in Variables
{ Built-in Classes
{ Built-in Modules
{ Built-in Exception Classes
z Game Library
{ RGSS Built-in Functions
{ RGSS Built-in Classes
{ RGSS Built-in Modules
{ RPGVX Data Structure
z Appendix
{ Regular Expressions
{ sprintf Format

About This Document

This document presents a selection of entries from the Ruby reference manual, the bare minimum needed for using
RGSS. It has been edited to include explanations of RGSS's unique specifications as well. Aimed at RGSS users, we've
greatly scaled back on those areas that aren't important for game programming and updated each entry. This means
that some portions might not be strictly accurate; as a Ruby reference, it's no more than a quick-and-dirty guide and
should be treated as such.

The original Ruby language, as well as the source for this document, can be found at the official Ruby homepage:
http://www.ruby-lang.org/. Check it out if you need more detailed Ruby information.

User Support

Enterbrain provides no user support for creating games with the script editor or any problems that may arise from the
game-creation process. Furthermore, neither Enterbrain nor Yukihiro Matsumoto assume any responsibility to provide

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 2 of 172

Ruby script support. Be sure you have a thorough understanding of RGSS's functions when attempting to edit a script.

Be a responsible programmer--make sure to check these pages, the Ruby homepage, any other Ruby information and
support sites, and similar resources before approaching a site administrator for assistance.

RGSS Specifications
z Differences from the Previous Version
z Starting a Game
z Game.ini
z RGSS-RTP
{ Installation Data
z Encrypted Archives
z Other
{ Character Set
{ Frame Rate
{ Properties

Differences from the Previous Version (RGSS2)

RGSS2, which is incorporated into RPG Maker VX, has a number of differences from RGSS1, which was included with
RPG Maker XP. The main differences are listed below.

z The default resolution has been changed from 640×480 to 544×416 and the default frame rate has been changed
from 40 to 60. Smooth Mode has been removed.
z Double buffering is now used for drawing in Full Screen mode. If your computer meets the recommended
specifications, scrolling should be very smooth.
z The function that would assume that the program had hung up if the screen had not been refreshed for a long
period of time and automatically perform a force quit has been removed. Even if the screen is not refreshed,
Windows messages will still be processed normally, so in most cases you can force quit by using Alt+F4 as usual.
z It is now possible to easily perform a fade-in or fade-out of the screen. To do this, you use the Graphics.fadeout
and Graphics.fadein methods.
z It is now possible to get a bitmap image of the current game screen. To do this, you use the
Graphics.snap_to_bitmap method.
z The tilemap (Tilemap) class has been significantly changed to match the RPGVX map specifications.
z It is now possible to use effects such as Blur or Radial Blur with bitmaps (Bitmap).
z For sprites (Sprite), a wave effect (similar to a raster scroll effect) is now supported.
z By placing font files in the Fonts folder inside the game folder, it is now possible to directly use fonts that are not
installed on the system.
z Shadow text is now supported for the Font class (Font). A number of the default values were also changed.
z It is now possible to change viewport (Viewport) associations after the fact. Sprites and other elements associated
with viewports will no longer be automatically freed.
z The timing with which the BGM restarts after ME playback has been improved (Audio.me_play).

In addition to the above, a number of other minor changes have been made.

In this manual, functions or specifications that have been changed for RGSS2 will be marked with a (RGSS2) symbol.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 3 of 172

Starting a Game

Normally, you launch RGSS by double-clicking the icon for the game file, Game.exe (or Game if the Game

Windows option "Hide extensions for known file types" has been turned on). The folder that contains
this file is called the game folder.

In-progress games can be started up by selecting [Playtest] from the menu or [Battle Test] from the Troop database.
When this is done, the global variable $TEST will be set to true. When performing a Battle Test, the $BTEST variable
will also be set to true. With RGSS1, the value of the Ruby built-in variable $DEBUG was changed but this was removed
because differences in behavior could lead to problems in rare cases. (RGSS2)

Game operation is specified in Game.ini, the configuration file.

Game.ini

The Game.ini file is automatically created and updated by RPGVX. It can also be edited manually with Notepad or
another text editor.

Example:

[Game]
RTP=RPGVX
Library=RGSS200E.dll
Scripts=Data\Scripts.rvdata
Title=RubyQuest

RTP

The title of the RGSS-RTP the game is using. Usually "RPGVX".

If the specified RTP isn't installed, an error message will be displayed.

Library

The name of the RGSS DLL. This file is usually installed in the RTP folder.

If there's a DLL specified in the game folder, it will be given precedence.

Scripts

The data file in which scripts are stored, specified with a path relative to the game folder.

Ruby's scripts usually take the form of text files with the extension .rb, but RGSS uses one proprietary packaged
file. This file cannot usually be edited without using RPGVX's script editor. The data is comprised of multiple
sections and is executed in the listed order, as displayed.

Title

The game title, displayed in the game window's title bar.

RGSS-RTP

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 4 of 172

RTP (Run-Time Package) is a mechanism that reduces game data size for distribution. RTP contains standard graphics
and audio files used across many different games. Installing these resources as a common file before playing a game
eliminates the need to download duplicate files over and over.

RTP files can use the following methods from the built-in game library to access files as though they were in the game
folder. The extensions can be left off the file names that are passed to the methods below--their file types (such as .png
or .mid) are identified automatically.

Bitmap.new, Audio.bgm_play, Audio.bgs_play, Audio.me_play, Audio.se_play, Graphics.transition

Installation Data

The standard RTP for RPG Maker VX is just "RPGVX" but it is now possible to use RTPs with different structures. If you
know how to make an installer, follow these steps to create a unique RTP at the user level. However, using common
names for RTP titles, such as "Extension", is not recommended; they might conflict with the names of new, official RTPs
in the future.

By default, RTP is installed in the following folder: (RGSS2)

[CommonFilesFolder]\Enterbrain\RGSS2\[RTPName]

Here, [CommonFilesFolder] is the location of the Windows "Common Files" folder, while [RTPName] is the name of the
RTP. Here's an example:

C:\Program Files\Common Files\Enterbrain\RGSS2\RPGVX

The RTP installer creates a string value containing the RTP name in the
"HKEY_LOCAL_MACHINE\SOFTWARE\Enterbrain\RGSS2\RTP" registry key and uses it to set the path. RGSS
recognizes the string specified in this key as the RTP. (RGSS2)

Encrypted Archives

Encrypted archives make it difficult for others to analyze and/or rebuild the game contents. Normally all data and graphic
files (not audio and font files) are stored in Game.rgss2a. You can create an encrypted archive by checking the [Create
encrypted archive] box when compressing the game data.

The files within the encrypted archive can use the following methods from the built-in game library to access files as
though they were in the game folder:

load_data, Bitmap.new, Graphics.transition

When there is an encrypted archive in the game folder, the script data (normally Data\Scripts.rvdata) defined in the
Scripts line of Game.ini will always be read from the archive. This is a limitation that prevents files within the archive
from being read by an external script.

Due to its nature, the encrypted archive's internal format has not, and will not, been released to the public. Please
refrain from analyzing it.

Other

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 5 of 172

Character Set

RGSS uses the UTF-8 character set. UTF-8 is a way of encoding Unicode, a character set that can display letters and
characters from all the world's languages.

Ruby's built-in variable $KCODE (not included in this reference) is set to "UTF8" by default. RPGVX's script data and all
other string data are also in UTF-8, so you don't have to worry about any encoding conflicts as you build your game.

Frame Rate

The standard frame rate for RGSS2 games is 60 frames per second. With RGSS1, it was possible to turn the Smooth
Mode option off and skip drawing some frames, thereby making games run at half frame rate, but this has been
eliminated with RGSS2.(RGSS2)

You can change the framerate with Graphics.frame_rate.

Properties

The term "property" is used in the game library overview. This is not a concept in Ruby's specifications, but rather a term
unique to RGSS.

For example, this is how to obtain and set a sprite's x-coordinate (Sprite#x):

x = sprite1.x # obtain
sprite2.x = x + 32 # set

For the sake of convenience, methods that are defined to both obtain (read) and set (write) via assignment operators in
this way are called "properties".

When objects such as the Color class, the Tone class, or the Rect class are defined as properties, a reference to the
object itself is returned to the caller, rather than a copy. Therefore, it is possible to change the color of a font by using
this format:

color = font1.color
color.set(255, 0, 0)

Ruby Syntax
z Syntax and Expressions
{ Identifiers
{ Comments
{ Reserved Words
{ Expressions
z Variables and Constants
{ Local Variables
{ Instance Variables
{ Class Variables
{ Global Variables
{ Constants
{ Pseudo Variables

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 6 of 172

z Literals
{ Number Literals
{ String Literals
„ Backslash Notation
„ Formula Development
{ Array Expressions
{ Hash Expressions
{ Range Expressions
{ Symbols
z Operational Forms
{ Assignment
„ Self-assignment
„ Multiple Assignment
{ and
{ or
{ not
{ Conditional Operators
z Control Structures
{ Conditional Branching
„ if
„ if Modifier
„ unless
„ unless Modifier
„ case
{ Looping
„ while
„ while Modifier
„ until
„ until Modifier
„ for
„ break
„ next
{ Exception Handling
„ raise
„ begin
„ rescue Modifiers
{ Method Ending
„ return
z Calling Methods
{ super
{ Iterators
{ yield
z Defining Classes and Methods
{ Class Definition
{ Module Definition
{ Method Definition
„ Method Evaluation

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 7 of 172

{ Unique Method Definition


{ Class Method Definition
{ Definition Controls
„ alias

Syntax and Expressions


{ Identifiers
{ Comments
{ Reserved Words
{ Expressions

Ruby is a case-sensitive language. Apart from within identifiers and some literals, blank space and comments may
be placed anywhere as needed. Line breaks are treated as blank space only when used to clearly show a line is
continuing; otherwise, they are treated as phrase delimiters.

Identifiers

Example:

foobar
ruby_is_simple

An identifier in Ruby begins with an alphabetic character or underscore (_) and consists of alphanumeric
characters or underscores (_). There is no limit on length.

Comments

Example:

# this is a comment line

Strings beginning with # are considered comments.

Reserved Words

The following are reserved words:

BEGIN class ensure nil self when


END def false not super while
alias defined? for or then yield
and do if redo true
begin else in rescue undef
break elsif module retry unless
case end next return until

Reserved words cannot be used for names of classes, variables, or the like. However, words prefixed by $ or @
are not considered reserved. Furthermore, these words can be used as method names after def, after a method-
call period, and in other cases where it is clear that the word is acting as a method name.

Expressions

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 8 of 172

Example

true
(1+2)*3
foo()
if test then ok else ng end

The term "expressions" encompasses everything from variables and literals to operational forms and control
structures.

A collection of these expressions makes up a Ruby program. Expressions are separated from one another with
semicolons (;) or line breaks. However, a line break following a backslash is not considered a new expression
boundary; instead, the expression continues on the next line.

Expressions can be grouped with parentheses.

Variables and Constants


{ Local Variables
{ Instance Variables
{ Class Variables
{ Global Variables
{ Pseudo Variables
{ Constants

The type of variable or constant in Ruby--local variables, instance variables, class variables, global variables, and
constants--can be determined from its initial character. Normally a variable has an alphanumeric name (outside of
its first character) which can include an underscore, but some built-in variables begin with '$' + one character (see
Built-In Variables).

Variables and constants point to specified objects. Assigning objects to variables and constants simply makes
them point to new objects; it does not create new copies of objects.

Local Variables

Example:

foobar

Identifiers beginning with a lowercase letter or '_' are local variables or method calls.

Within a local variable's scope (classes, modules, method definitions), the initial assignment to an identifier
beginning with lowercase letters is the declaration of that scope's local variable. Referencing undeclared identifiers
is considered a call to a method with no arguments.

Instance Variables

Example:

@foobar

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 9 of 172

Variables beginning with '@' are instance variables and belong to specific objects. Instance variables can be
referenced from any method of their class or subclass. When referenced, the value of an uninitialized instance
variable is nil.

Class Variables

Example:

class Foo
@@foo = 1
def bar
puts @@foo
end
end

Variables beginning with @@ are class variables. Class variables are defined within the class definition and can be
referenced/assigned from class-unique methods, instance methods, etc.

The differences between class variables and constants are as follows.

{ They may be reassigned (constants will give a warning if this is done).


{ They cannot be directly referenced from outside the class (they may be referenced/assigned from an
inherited class).

Global Variables

Example:

$foobar

Variables beginning with '$' are global variables and can be referenced from anywhere in the program (thus
requiring some caution when using). Global variables do not need declarations. When referenced, the value of an
uninitialized global variable is nil.

Pseudo Variables

Apart from the usual variables, there are also special variables known as pseudo variables.

self

The current method's execution constituent.

nil

The only instance of the NilClass class. Signifies NIL.

true

The only instance of the TrueClass class. Signifies TRUE.

false

The only instance of the FalseClass class. Signifies FALSE.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 10 of 172

The value of a pseudo variable cannot be changed. Assigning values to pseudo variables will result in a syntax
error.

Constants

Example:

FOOBAR

Identifiers beginning with an uppercase letter are constants. The definition of a constant (and its initialization)
depends on its assignment; constants cannot be defined with a method. Accessing an undefined constant throws
a NameError exception.

Within the class or module in which a constant is defined, the constant can be referenced by inheriting classes,
classes that include modules, and modules. To reference constants externally, use the '::' operator.

class Foo
FOO = 'FOO'
end

class Bar < Foo


p FOO # => "FOO"
end

p Foo::FOO # => "FOO"

The names of classes and modules are handled as constants.

Literals
{ Numeric Literals
{ String Literals
„ Backslash Notation
„ Expression Substitution
{ Regular Expressions
{ Array Expressions
{ Hash Expressions
{ Range Expressions
{ Symbols

Values that can be expressed directly in Ruby programs, such as the number 1 or the string "hello world", are
called literals.

Numeric Literals

123
0d123

integer

-123

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 11 of 172

integer (signed)

123.45

floating point number

Floating point numbers beginning with a decimal point, like .1, are not allowed. They must be written with a
leading zero (0.1).

1.2e-3

floating point number

0xffff

hexadecimal integer

0b1011

binary integer

0377
0o377

octal integer

Numeric literals can contain an underscore. The Ruby interpreter simply ignores these underscores and does not
interpret them in a special way. This can be useful as a thousands separator for large values. However, placing an
underscore before and after a literal or connecting literals with an underscore will result in an error.

1_000_000_000 # => 1000000000


0xffff_ffff # => 0xffffffff

String Literals

Example:

"this is a string expression\n"


'this is a string expression'

String expressions begin and end with double or single quote marks.

Double-quoted string expressions are subject to backslash notation and expression substitution. Single-quoted
strings are not (except for \' and \\).

String literals with white space on either side are treated as a single string literal.

p "foo" "bar" # => "foobar"

Backslash Notation

\t

tab (0x09)

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 12 of 172

\n

newline (0x0a)

\r

carriage return (0x0d)

\f

form feed (0x0c)

\s

whitespace (0x20)

\nnn

character at octal value nnn (n = 0-7)

\xnn

character at hexadecimal value nn (n = 0-9, a-f)

Expression Substitution

In double-quoted strings and regular expressions, the form "#{expression}" can be extended to the (string of the)
contents of that expression. If the expressions are variables beginning with either $ or @, the surrounding braces
may be omitted and the variable can be expressed as a #variable. The character # is interpreted literally if it is not
followed by the characters {, $, or @. To explicitly prevent expression substitution, place a backslash in front of the
#.

$ruby = "RUBY"
p "my name is #{$ruby}" # => "my name is RUBY"
p 'my name is #{$ruby}' # => "my name is #{$ruby}"

Regular Expressions

Example:

/^Ruby the OOPL/


/Ruby/i
/my name is #{myname}/

Strings delimited by slashes are regular expressions, which are instances of the Regexp class.

Refer to Regular Expressions for more information on which metacharacters are interpreted as regular
expressions.

The characters immediately following the final slash denotes a regular expression option:

Regular expression matching is case insensitive.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 13 of 172

Multiple run mode. Newlines are treated as normal characters (matching with the . character).

Ruby correctly handles multibyte characters (such as Chinese and Japanese) in regular expressions.

Backslash notation and expression substitution are available in regular expressions, as in strings.

If a regular expression does not include expression substitution, it will return the same regular expression object
every time it is evaluated. If expression substitution is included, the regular expression will be compiled with every
evaluation (based on the expression substitution results) and a new regular expression object will be created.

Array Expressions

Example:

[1, 2, 3]

Syntax:

'[' expr ',' ... ']'

Returns an array containing the result of each expression. Arrays are instances of the class Array.

Array expressions spawn a new array object every time they are evaluated.

Hash Expressions

Example:

{1=>2, 2=>4, 3=>6}

Syntax:

'{' expr '=>' expr ',' ... '}'


'{' expr ',' expr ',' ... '}'

Returns a new hash object that maps each resulting value to a key. Hashes are instances of the class Hash.

A hash (also called an associative array) can associate one object of an arbitrary type with another.

Hash expressions spawn a new hash object every time they are evaluated.

Range Expressions

Example:

1 .. 20

Syntax:

expr1 '..' expr2


expr1 '...' expr2

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 14 of 172

If a range expression appears anywhere but a conditional expression, returns the range object from expression 1
to expression 2. Range objects are instances of the class Range.

Range objects spawned by .. operators include the final expression, while those spawned by ... operators do not.

If both ends of a range expression are numeric literals, the expression will return the same object every time it is
evaluated. Otherwise, the expression will return a new range object every time it is evaluated.

Symbols

Example:

:class
:lvar
:method
:$gvar
:@ivar
:+

Syntax:

':' identifier
':' variable name
':' operator

Returns symbols that have a one-to-one correspondence with arbitrary strings. Symbols are an instance of the
Symbol class.

Symbols are unique objects that return the same object every time they are evaluated.

Operator Expressions
{ Assignment
„ Self-Assignment
„ Multiple Assignment
{ and
{ or
{ not
{ Conditional Operators

Example:

1+2*3/4

Some method calls and control structures take the form of operators for ease in programming. Ruby contains the
following operators:

high ::
[]
**
-(unary) +(unary) ! ~
* / %
+ -
<< >>
&
| ^
> >= < <=

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 15 of 172

<=> == === != =~ !~
&&
||
.. ...
?:(conditional operator)
=(+=, -= ... )
not
low and or

"High" and "low" signify the operators' priority level. For example, "&&" has a higher priority than "||", so it would be
interpreted in the following way:

a && b || c # => (a && b) || c


a || b && c # => a || (b && c)

Most operators are method calls in special form, but some are built into the language and cannot be redefined.

{ Redefinable operators (methods)

+@ and -@ represent the unary operators + and -. This notation is used in method definitions and the like.

| ^ & <=> == === =~ > >= < <= << >>


+ - * / % ** ~ +@ -@ [] []= `

{ Nonredefinable operators (control structures)

Combination operators (i.e., self-assignment operators, !=, and !~) cannot be redefined.

= ?: .. ... ! not && and || or ::

Assignment

Example:

foo = bar
foo[0] = bar
foo.bar = baz

Syntax:

variable '=' expr


constant '=' expr
expr '['expr..']' '=' expr
expr '.' identifier '=' expr

Assignment expressions are used to assign values to variables and the like. Assignments can also be used as
declarations for local variables or constants. The left side of an assignment expression must be one of the
following:

{ a variable

variable '=' expr

If there is a variable on the left side, the value of the expression is assigned to the variable.

{ an array reference

expr1 '[' expr2 ... ']' '=' exprN

For the object obtained by evaluating expr1, this form is converted into a []= method call with expr2 through

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 16 of 172

exprN as arguments.

class C
def initialize
@ary = [0,1,2,3,4,5,6,7]
end
def [](i)
@ary[i * 2]
end
def []=( i, v )
@ary[i * 2] = v
end
end
c = C.new
p c[3] # converted to c.[]( 3 ); result is 6
p c[3] = 1 # converted to c.[]=(3,1); result is 1

{ an attribute reference

expr1 '.' identifier '=' expr2

For the object obtained by evaluating expr1, calls the identifier= method with expr2 as an argument.

class C
def foo
@foo
end
def foo=( v )
@foo = v
end
end
c = C.new
c.foo = 5 # converted to c.foo=( 5 )
p c.foo # => 5

Attributes can be defined with attr_accessor in the same way:

class C
attr_accessor :foo
end
c = C.new
c.foo = 5 # converted to c.foo=( 5 )
p c.foo # => 5

Self-Assignment

Example:

foo += 12 # foo = foo + 12


foo *= 3 # foo = foo * 3

Syntax:

expr1 op= expr2 # expr1 is part of the right-hand assignment

op is one of the following. There can be no space between the operator and =.

+, -, *, /, %, **, &, |, ^, <<, >>, &&, ||

In this assignment format, most cases are evaluated as:

expr1 = expr1 op expr2

Multiple Assignment

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 17 of 172

Example:

foo, bar, baz = 1, 2, 3


foo, = list()
foo, *rest = list2()

Syntax:

expr [',' [ expr ',' ... ] ['*' [ expr ]]] = expr [, expr ... ]['*' expr ]
'*' [ expr ] = expr [, expr ... ]['*' expr ]

Multiple assignment performs assignments from multiple expressions or arrays. Each expression on the left must
be assignable. If there is only one expression on the right, its value will be converted into an array whose elements
will be assigned to the expressions on the left. If there are more elements in the array than on the left, the extra
elements are ignored. If there are too few elements in the array, nil will be assigned to the extra elements on the
left.

Prepend * to the final expression on the left to assign all extra lefthand elements to that expression as an array. If
there are no extra elements, an empty array will be assigned.

foo, bar = [1, 2] # foo = 1; bar = 2


foo, bar = 1, 2 # foo = 1; bar = 2
foo, bar = 1 # foo = 1; bar = nil
foo, bar = 1, 2, 3 # foo = 1; bar = 2
foo = 1, 2, 3 # foo = [1, 2, 3]
*foo = 1, 2, 3 # foo = [1, 2, 3]
foo, *bar = 1, 2, 3 # foo = 1; bar = [2, 3]

and

Example:

test && set


test and set

Syntax:

expr '&&' expr


expr and expr

First evaluates the left side; if the result is true, evaluates the right side. and does the same as &&, but is a lower
priority operator.

or

Example:

demo || die
demo or die

Syntax:

expr '||' expr


expr or expr

First evaluates the left side; if the result is false, evaluates the right side. or does the same as ||, but is a lower
priority operator.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 18 of 172

not

Example:

! me
not me
i != you

Syntax:

'!' expr
not expr

If the value of the expression is true, returns FALSE; if the value is false, returns TRUE.

The following notation is also possible:

expr '!=' expr # same as !(expr == expr)


expr '=~' expr # same as !(expr =~ expr)

Conditional Operators

Example:

obj == 1 ? foo : bar

Syntax:

expr1 ? expr2 : expr3

Returns expr2 or expr3 depending on the results of expr1. This is identical to:

if expr1 then expr2 else expr3 end

Control Structures
{ Conditional Branching
„ if
„ if Modifier
„ unless
„ unless Modifier
„ case
{ Looping
„ while
„ while Modifier
„ until
„ until Modifier
„ for
„ break
„ next
{ Exception Handling
„ raise

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 19 of 172

„ begin
„ rescue Modifier
{ Method Exit
„ return

Unlike in C, control structures in Ruby are expressions that return some value.

Ruby carries over some control structures from C and Perl, but also features a loop abstraction feature called
iterators. Iterators are user-definable looping control structures.

Conditional Branching

if

Examples:

if age >= 12 then


print "adult fee\n"
else
print "child fee\n"
end
gender = if foo.gender == "male" then "male" else "female" end

Syntax:

if expr [then]
expr ...
[elsif expr [then]
expr ... ]
...
[else
expr ... ]

end

If a conditional expression is evaluated as true, evaluates the expression beginning with then. If the if expression
is false, evaluates the elsif condition. Multiple elsif clauses can be specified; when all if or elsif conditional
expressions are false, the else clause expression, if any, is evaluated.

if returns the value of the last evaluated expression in the conditional expression clause (or else clause). If there is
no else clause and no conditional expressions in effect, returns nil.

The values false and nil are false; everything else, including zero and empty text strings, is true.

Note that Ruby uses elsif after if, not else if and not elif.

if Modifier

Example:

print "debug\n" if $DEBUG

Syntax:

expr if expr

Evaluates and returns the result of the expression on the left if the condition on the right is true. If the condition is

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 20 of 172

not in effect, returns nil.

unless

Example:

unless baby?
feed_meat
else
feed_milk
end

Syntax:

unless expr [then]


expr ...
[else
expr ... ]
end

unless is the reverse of if; if the conditional expression is false, evaluates the expression beginning with then. elsif
cannot be specified with unless.

unless Modifier

Example:

print "stop\n" unless valid(passwd)

Syntax:

expr unless expr

Evaluates and returns the result of the expression on the left if the condition on the right is false. If the condition is
not in effect, returns nil.

case

Example:

case $age
when 0 .. 2
"baby"
when 3 .. 6
"little child"
when 7 .. 12
"child"
when 13 .. 18
"youth"
else
"adult"
end

Syntax:

case expr
[when expr [, expr] ... [then]
expr ..]..
[else
expr ..]
end

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 21 of 172

case expressions execute branching for a single expression via matching. Comparisons of values specified in a
when clause to the evaluated result of the first expression are performed by the === operator. When the values
match, evaluates the contents of the when clause.

case returns the result of the last evaluated expression in a conditional when (or else) clause. If neither condition
is in effect, returns nil.

Looping

while

Example:

ary = [0,2,4,8,16,32,64,128,256,512,1024]
i = 0
while i < ary.length
print ary[i]
i += 1
end

Syntax:

while expr [do]


...
end

Executes the contents of an expression as long as the expression remains true.

while returns nil. Alternatively, the while return value can also be the value of an argument to a break.

while Modifier

Example:

sleep(60) while io_not_ready?

Syntax:

expr while expr

Repeatedly executes the expression on the left as long as the expression on the right is evaluated as true. If the
expression on the left is begin, while evaluates it first before looping.

The while modifier returns nil. Alternatively, the while modifier return value can also be the value of an argument to
a break.

until

Example:

until f.eof?
print f.gets
end

Syntax:

until expr [do]

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 22 of 172

...
end

Repeatedly executes the expression until it is evaluated as true.

until returns nil. Alternatively, the until return value can also be the value of an argument to a break.

until Modifier

Example:

print(f.gets) until f.eof?

Syntax:

expr until expr

Repeatedly executes the expression on the left until the expression on the right is evaluated as true. If the
expression on the left is begin, the until modifier evaluates it first before looping.

The until modifier returns nil. Alternatively, the until modifier return value can also be the value of an argument to a
break.

for

Example:

for i in [1, 2, 3]
print i*2, "\n"
end

Syntax:

for lhs ... in expr [do]


expr ..
end

Repeatedly executes the contents for each evaluated object element. Approximately identical to the following:

(expr).each '{' '|' lhs..'|' expr .. '}'

It is only approximately identical because while blocks defined by do ... end or by { } introduce a new block scope
for local variables, for has no effect on the scope of local variables.

for returns the return value of the each method for the objects specified in in.

break

Example:

i = 0
while i < 3
print i, "\n"
break
end

Syntax:

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 23 of 172

break [expr]

break escapes from the innermost loop. A "loop" is one of the following:

{ while
{ until
{ for
{ an iterator

Unlike in C, break can only escape from loops. It does not exit from case.

for or an iterator that has escaped from a loop via break returns nil. However, if an argument is specified, the
loop's return value will become that argument.

next

Example:

str.each_line do |line|
next if line.empty?
print line
end

Syntax:

next [expr]

next jumps to the next iteration of the innermost loop. In an iterator, next is an escape for a yield call.

A yield that has escaped via next returns nil. However, if an argument is specified, yield's return value will become
that argument.

Exception Handling

raise

Examples:

raise
raise "you lose"
raise SyntaxError.new("invalid syntax")
raise SyntaxError, "invalid syntax"

Syntax:

raise
raise message
raise exception
raise error_type, message

Throws an exception. In the first format, throws the last exception again. In the second format, given a string
argument, throws a RuntimeError exception with the given string as a message. In the third format, throws the
exception if the argument is an exception object. In the last format, throws the exception specified in the first
argument with the message given in the second argument.

Thrown exceptions can be trapped with a rescue clause in begin.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 24 of 172

raise is not a reserved word in Ruby, but rather an built-in function.

begin

Example:

begin
do_something
rescue
recover
ensure
must_do
end

Syntax::

begin
expr ..
[rescue [error_type,..] [then]
expr ..]..
[ensure
expr ..]
end

If an exception is thrown while begin is being executed, a rescue clause can trap the exception; multiple clauses
can be specified. If a rescue clause with a matching exception type exists, it is executed. The thrown exception
can be referenced with the built-in variable $!.

When error_type is omitted, it traps all exceptions in the StandardError subclasses, of which most built-in
exceptions in Ruby are members. See Built-in Exception Classes.

In rescue clauses, error_type is evaluated in the same way as an argument. If any value matches, the clause will
be executed. If the value of error_type is not a class or a module, rescue throws a TypeError exception.

If there is an ensure clause, its contents are always evaluated immediately before a begin expression exits.

begin returns the result of the final argument evaluated in either its contents or in the rescue clause.

rescue Modifier

Example:

File.open("file") rescue print "can't open\n"

Syntax:

expr1 rescue expr2

When an exception is thrown in the first expression, evaluates the second expression. You cannot specify the
exception class(es) to be trapped; in other words, you can only trap the subclasses of the StandardError exception
class.

Expressions associated with the rescue modifier return expr1 if no exception is thrown and expr2 if an exception is
thrown.

Method Exit

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 25 of 172

return

Example:

return
return 12
return 1,2,3

Syntax:

return [expr[',' expr ... ]]

Exits from a method with the return value. If two or more expressions are provided, the method's return value will
consist of an array containing these values. If the expression is omitted, the return value will be nil.

Method Calls
{ super
{ Iterators
{ yield

Example:

foo.bar()
foo.bar
bar()
print "hello world\n"
print

Syntax:

[expr '.'] identifier ['(' expr ... ['*' [expr]] ')']

Method calls invoke the method of the receiver (the value of the expression to the left of the dot). If no receiver is
specified, calls the method of self.

Method names can be normal identifiers or identifiers followed by the character ? or !. Customarily, ? is used for
predicates (methods returning true/false values), while ! is used for methods that are more destructive than their !-
less counterparts (tr versus tr!).

If the last argument is preceded by *, the value of that expression is expanded to its arguments:

foo(*[1,2,3]) # same as foo(1,2,3)

super

Example:

super
super(1,2,3)

Syntax:

super
super(expr , ... )

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 26 of 172

super calls the method that is being overridden by the current method. If the parentheses and arguments are
omitted, the current method's arguments are passed to super as is. To call the overridden method without passing
any arguments, indicate the parentheses as in super().

class Foo
def foo(arg=nil)
p arg
end
end

class Bar < Foo


def foo(arg)
super(5) # called with 5 as an argument
super(arg) # called with 5 as an argument
super # called with 5 as an argument; abbreviation of super(arg)
arg = 1
super # called with 1 as an argument; abbreviation of super(arg)
super() # called with no argument
end
end
Bar.new.foo 5

Iterators

Example:

[1,2,3].each do |i| print i*2, "\n" end


[1,2,3].each {|i| print i*2, "\n" }

Syntax:

method(arg1, arg2, ...) do ['|' expr ... '|'] expr ... end
method(arg1, arg2, ...) '{' ['|' expr ... '|'] expr ... '}'

Iterators are methods used for abstracting control structures (especially loops). If you call a method that is followed
by a code segment enclosed by do ... end or by { ... } (called a block), the method can evaluate the block from
within. Methods that call these kinds of blocks are called iterators. Block calls from iterators use yield. The value
passed to yield is assigned to the variable between the two pipes ( | ).

{ ... } binds more strongly than a do ... end block.

foobar a, b do .. end # foobar is called as an iterator


foobar a, b { .. } # b is called as an iterator

Local variables that are first assigned (declared) in a block are only valid within that block.

foobar {
i = 20 # local variable 'i' is declared
...
}
# 'i' is undefined here
foobar a, b do
i = 11 # declaration of a totally different variable 'i'
...
end

Like most methods, an iterator's return value is nil if it is interrupted by break from within a block. When break has
an argument, that value will become the iterator's return value.

yield

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 27 of 172

Example:

yield data

Syntax:

yield '(' [ expr [',' expr ... ]] ')'


yield [ expr [',' expr ... ]]

Passes the argument(s) as the block's argument(s) and evaluates the block. yield is used within MethodDefinition
to define iterators.

def foo
yield(1,2)
end

foo {|a,b| p [a,b]}

Assignment of the block argument(s) is carried out according to the rules of multiple assignment. If no block is
supplied to the method that executed yield (i.e., it is not an iterator), throws a LocalJumpError exception.

yield returns the result of the block's last evaluated expression. If block execution has been interrupted by next,
returns nil. When next has an argument, that value will become yield's return value.

Class and Method Definitions


{ Class Definitions
{ Module Definitions
{ Method Definitions
„ Method Evaluation
{ Singleton-Method Definitions
{ Class Method Definitions
{ Definition Operations
„ alias

Class Definitions

Example:

class Foo < Super


def test
:
end
:
end

Syntax:

class identifier ['<' superclass ]


expr ..
end

Defines a class. Class names are identifiers beginning with an uppercase letter.

Class definitions assign a class to a constant specified by an identifier (in Ruby, classes and objects together are
one instance of the Class class.)

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 28 of 172

When a class is already defined, writing a class definition with the same class name will add to the existing class
definition.

class Foo < Array


def foo
end
end

class Foo
def bar
end
end

In a class definition, self is that class itself; otherwise, it is no different than a top-level definition. Class definitions
can contain arbitrary expressions that will be executed when the class is defined.

Class definitions can operate as nests. In the following example, there is absolutely no functional relationship
(such as inheritance) between the outer class Foo and the inner class Bar, other than the fact that the constant
Bar is Foo's inner constant Foo::Bar. Class nests group together semantically related classes into the outer class
or module, and can be used to express an inclusion relationship.

class Foo
class Bar
end
end

Class definitions return the result of the last evaluated expression. If that expression does not return a value, the
class definition returns nil.

Module Definitions

Example:

module Foo
def test
:
end
:
end

Syntax:

module identifier
expr ..
end

Defines a module. Module names are identifiers beginning with an uppercase letter.

Module definitions assign a module to a constant specified by an identifier. In Ruby, classes and objects together
are one instance of the Class class.)

When a module is already defined, writing a module definition with the same module name will add to the existing
module definition.

Module definitions return the result of the last evaluated expression. If that expression does not return a value, the
module definition returns nil.

Method Definitions

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 29 of 172

Example:

def fact(n)
if n == 1 then
1
else
n * fact(n-1)
end
end

Syntax:

def methodname ['(' [arg ['=' default]] ... [',' '*' arg] ')']
expr ..
[rescue [error_type,..] [then]
expr ..]..
[ensure
expr ..]
end

Defines a method. In other words, defines the method of a class or module if within the definition of that class or
module. If top-level, defines methods that can be called from anywhere. This kind of method can be used like
functions are in other scripting languages.

Method names can be normal identifiers or redefinable operators (==, +, -, and so on; see Operator Expressions.

When a default expression has been provided to a dummy argument, it becomes the default value when the actual
argument is omitted through a method call. The default expression is evaluated at the time of the call and in the
context of the method definition.

When the last dummy argument has a * immediately before it, the remaining actual arguments are all stored in this
argument as an array.

Example:

# method with no argument. end omitted below


def foo
end

# method with arguments


def foo(arg, arg2)

# method with default argument


def foo(arg = nil)

# with everything
def foo(arg, arg2, arg3 = nil, *rest)

# operator format
def ==(other)
def +(other)
def *(other)

For method definition, each type of dummy argument can only be specified according to the following sequence.
Any of these types of arguments can be omitted.

{ arguments without default expressions (can specify multiple arguments)


{ arguments with default expressions (can specify multiple arguments)
{ arguments with * (can specify only one)

These method definitions have special formats:

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 30 of 172

# unary plus/minus
def +@
def -@

# element substitution
def foo=(value) # obj.foo = value

# [] and []=
def [](key) # obj[key]
def []=(key, value) # obj[key] = value
def []=(key, key2, value) # obj[key, key2] = value

Furthermore, a begin expression as well as rescue and/or ensure clauses can be specified to trap exceptions
when executing a method.

Method definition returns nil.

Method Evaluation

When a method is called, its expressions are evaluated in the following order:

{ Default expressions in arguments (when specified)


{ The method itself
{ The method's rescue or else clauses (when specified), depending on whether an exception has been thrown
{ The ensure clause (when specified)

Everything is evaluated in the method's context, including the argument's default expression.

The method's return value is the value passed to return. When return is not called, returns the value of the last
evaluated expression in the method, before any ensure clause is executed.

Methods cannot be called before they are defined. For example:

foo
def foo
print "foo\n"
end

Calling an undefined method throws a NameError exception.

Singleton-Method Definitions

Example:

def foo.test
print "this is foo\n"
end

Syntax:

def expr '.' identifier ['(' [ argument ['=' default]] ... [',' '*' argument ]')']
expr ..
[rescue [error_type,..] [then]
expr ..]..
[else
expr ..]
[ensure
expr ..]
end

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 31 of 172

A singleton method belongs to a certain object and not to a class. Singleton-method definitions can be nested.

The singleton methods of a class carry over to its subclasses. In other words, they act like the class methods in
other object-oriented languages.

Singleton-method definitions return nil.

Class Method Definitions

In Ruby, class methods are the methods specific to a class. Classes are also objects, so these specific methods
can be defined like regular objects.

Therefore, when a method in a class object is defined in some way, that object becomes a class method.
Specifically, these methods can be defined in the following way (as can modules):

# singleton method
class Hoge
def Hoge.foo
end
end

# can use outside class definition, too


def Hoge.bar
end

# even if the class name changes, you don't have to change the method
class Hoge
def self.baz
end
end

Definition Operations

alias

Example:

alias foo bar


alias :foo :bar

Syntax:

alias newmethod oldmethod

Assigns an alias to a method or global variable. Specifies an identifier or a Symbol as the method name
(expressions like obj.method are not permitted). alias's argument performs no evaluation of method calls or the
like.

An aliased method carries over that method definition, retaining it even if the original method is redefined. This can
be used when you want to change the actions of a given method, then use the result of the original method in the
redefined method.

# defining method "foo"


def foo
"foo"
end

# setting alias (retracting method definition)


alias :_orig_foo :foo

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 32 of 172

# "foo" redefined (using the old definition)


def foo
_orig_foo * 2
end

p foo # => "foofoo"

alias returns nil.

Standard Library
{ Built-in Functions
{ Built-in Variables
{ Built-in Classes
„ Object
„ Array
„ Exception
„ FalseClass
„ Hash
„ IO
„ File
„ MatchData
„ Module
„ Class
„ NilClass
„ Numeric
„ Integer
„ Bignum
„ Fixnum
„ Float
„ Proc
„ Range
„ Regexp
„ String
„ Symbol
„ Time
„ TrueClass
{ Built-in Modules
„ Comparable
„ Enumerable
„ Errno
„ FileTest
„ GC
„ Kernel
„ Marshal
„ Math
{ Built-in Exception Classes

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 33 of 172

Built-in Functions
Strictly speaking, they aren't functions in Ruby, but since methods defined in the Kernel module can be called from
anywhere, they can be used like functions are in other languages. Carefully consider the repercussions of
redefining the methods here.

block_given?

Returns true when the method has been supplied with a block; otherwise, returns false. See Iterator for
details.

catch(tag) {|tag| .... }

Executes the block and returns its value. If a throw with the same name as tag takes place while the block is
running, the return value will be that throw's second argument.

break cannot break out all nested loops at once. Use catch in these circumstances.

catch(:loop1) {
for i in 1..2
for j in 1..2
throw :loop1, j
end
end
}

eval(expr)

Evaluate the string expr as a Ruby program and returns the result.

exit

Exits a running Ruby program.

exit throws a SystemExit exception to terminate the program, so it can be trapped by a rescue clause where
necessary.

loop { ... }

Evaluates a block in an infinite loop (until explicitly terminated).

open(file[, mode])
open(file[, mode]) {|io| ... }

Opens file and returns a File object. mode specifies one of the following strings. When mode is omitted, the
default is "r".

z "r": Opens file in read mode.


z "w": Opens file in write mode. If a file already exists when file is opened, the previous file's contents will
be deleted.
z "a": Opens file in write mode. Output will always be appended to the end of the file.

Using "+" opens the file in read-write mode (RDWR):

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 34 of 172

z "r+": Sets the read-write position to the beginning of the file.


z "w+": The same as "r+", but if a file already exists when file is opened, the previous file's contents will
be deleted.
z "a+": The same as "r+", but if a file already exists when file is opened, the read-write position will be set
to the end of the file.

The "b" flag can also be added to any of these (in the format "r+b") to open the file in binary mode.

When open is called along with a block, it opens the file, executes the block, then closes the file when
execution is complete. In this case, returns the result of the block evaluation. That is:

open(path, mode) do |f|


...
end

# almost identical to the above


f = open(path, mode)
begin
...
ensure
f.close
end

p(obj, [obj2, ...])

Outputs obj in a human-readable format. Identical to the following code (see Object#inspect):

print obj.inspect, "\n", obj2.inspect, "\n", ...

In Ruby, the usual output destination would be standard output. This method is redefined in RGSS to output
to a Windows message box.

Returns nil.

print(arg[, ...])

Prints the arguments in order. If a non-string object has been supplied as an argument, it will be converted
into a string with to_s and printed. However, if the argument is nil, it will print the string "nil".

In Ruby, the usual output destination would be standard output. This method is redefined in RGSS to output
to a Windows message box.

Returns nil.

raise
raise(message)
raise(exception)
raise(error_type, message)

Throws an exception. See raise for details.

rand(max)

Creates a random integer in the range 0 ≤ integer < max. Automatically calls srand if it hasn't already been
called.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 35 of 172

If max is nil or 0, uses Float to return a random number in the range 0 ≤ real number < 1.

sprintf(format[, arg[, ...]])

Interprets the string format as does C's sprintf, returning a string of formatted arguments.

See sprintf Format for details.

srand([seed])

Sets the rand random number seed and returns the old initial value. If seed is omitted, uses the current time
(or a similar value) as the seed.

throw(tag[, value])

Escapes (across methods) to the end of a catch block with the same tag. If there is no catch with the same
tag, the thread terminates with NameError. value will be the return value of the catch.

Built-in Variables
Built-in variables are a type of global variable, but their values are not only used globally.

The following are examples of built-in variables divided up by their scope.

Local Scope

$~

The information about the last match in the current scope (MatchData object). Setting this variable changes
the values of $&, $1 ... $9, etc.

Identical to Regexp.last_match.

$&

The string matched by the last successful pattern match in this scope, or nil if the last pattern match failed.

Identical to Regexp.last_match[0]

$1
$2
$3 ...

Contains the subpattern from the corresponding set of parentheses in the last successful pattern matched, or
nil if the last pattern match failed.

Identical to Regexp.last_match[1], Regexp.last_match[2], ...

Global Scope

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 36 of 172

$!

Information on the latest exception. Set with raise.

$DEBUG

The debug mode flag. RGSS sets this flag during playtesting.

There are some differences in exception behavior, etc., while in Ruby's debug mode, but you need not be
concerned about them in RGSS.

Built-in Classes
{ Object
„ Array
„ Exception
„ FalseClass
„ Hash
„ IO
„ File
„ MatchData
„ Module
„ Class
„ NilClass
„ Numeric
„ Integer
„ Bignum
„ Fixnum
„ Float
„ Proc
„ Range
„ Regexp
„ String
„ Symbol
„ Time
„ TrueClass

Object
The superclass of all classes. Defines the general behavior of objects.

Included Modules

{ Kernel

Methods

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 37 of 172

self == other

Checks if self and other are equal. By default, has the same effect as equal?.

This method must be redefined with respect to each class's properties.

self === other

This method is mostly used for comparison within case statements. By default, acts like Object#==, but this
behavior can be redefined in the subclass to implement an ownership check.

class

Returns the receiver class.

clone
dup

Creates a copy of the object. clone returns a complete clone of the original object, including freeze status
and singleton methods, while dup duplicates the object contents only.

Note that clone and dup perform only a shallow copy. They duplicate the object itself, but nothing it points to
(such as array elements).

For duplicated objects,

obj.equal?(obj.clone)

generally does not hold, while

obj == obj.clone

is correct in most cases.

Attempting to duplicate true, false, nil, Numeric objects, Symbol objects, and the like result in TypeError
exceptions.

equal?(other)

When other is self, returns true. This method must not be redefined.

freeze

Prohibits an object's contents from being modified. Modifying a frozen object throws a TypeError exception.

frozen?

Returns true when the object's contents are prohibited from being modified.

inspect

Returns the object in a human-readable string format.

instance_of?(klass)

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 38 of 172

Returns true when self is a direct instance of the class klass. When obj.instance_of?(c) is true, obj.kind_of?
(c) is always true as well.

is_a?(mod)
kind_of?(mod)

Returns true when self is the class mod (or its subclass). or a class (or its subclass) that includes the module
mod.

module M
end
class C < Object
include M
end
class S < C
end

obj = S.new
p obj.is_a? S # true
p obj.is_a? M # true
p obj.is_a? C # true
p obj.is_a? Object # true
p obj.is_a? Hash # false

nil?

Checks if the receiver is nil.

object_id

Returns a unique integer for each object. The integers are assigned to objects arbitrarily.

to_ary

Called internally when an object's implicit conversion to an array is required.

to_hash

Called internally when an object's implicit conversion to a hash is required.

to_int

Called internally when an object's implicit conversion to an integer is required.

to_s

Returns the string representation of the object. This method is used internally by print and sprintf.

When non-string objects are passed to arguments in print and sprintf, use this method to convert the objects
to strings.

to_str

Called when an object's implicit conversion to a string is required.

Private Method

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 39 of 172

initialize

The initialization method for user-defined classes. This method is called from Class#new to initialize a newly
created object. The default behavior is to do nothing; it is assumed that this method will be redefined in the
subclass as needed. The argument given to Class#new will be passed to initialize as is.

Array
The array class. The elements of an array are arbitrary Ruby objects. See Array Expressions for more information.

Superclass

{ Object

Included Modules

{ Enumerable

Methods

self[nth]

Retrieves the nth item from an array. The index starts from zero. If the nth value is negative, counts
backward from the end of the array (the index of the last element is -1). If the nth element does not exist in
the array, returns nil.

self[start, length]

Returns an array containing length items from start. If the start value is negative, counts backward from the
end of the array (the index of the last element is -1).If length is longer than the length of the array from start,
the length of the overlong portion is ignored. Returns nil if length is negative.

self[nth]=val

Changes the nth element of the array into val. If nth is outside the array range, the array will automatically be
extended. The extended region will be initialized by nil.

Returns val.

self[start, length]=val

Replace the length items from index start with the contents of val. If val is not an array, the items will be
replaced by the contents of val.to_ary or [val]. Returns val .

ary = [0, 1, 2, 3]
ary[1, 2] = ["a", "b", "c"]
p ary # => [0, "a", "b", "c", 3]
ary[2, 1] = 99
p ary # => [0, "a", 99, "c", 3]
ary[1, 0] = ["inserted"]
p ary # => [0, "inserted", "a", 99, "c", 3]

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 40 of 172

self + other

Returns a new array with the concatenated contents of self and other. If other is not an array, uses the return
value of other.to_ary. If that return value is not an array, throws a TypeError exception.

a = [1, 2]
b = [8, 9]
p a + b # => [1, 2, 8, 9]
p a # => [1, 2] (no change)
p b # => [8, 9] (no change here, either)

self - other

The set subtraction operation. Returns a new array containing self without the elements of other.

self & other

The set intersection operation. Returns a new array containing elements belonging to both arrays. Duplicate
elements will be removed.

self | other

The set union operation. Returns a new array containing all elements belonging to either array. Duplicate
elements will be removed.

self <=> other

Compares each element with <=> and returns 1 if self is greater than, 0 if equal to, or -1 if less than other. If
the end of one array is reached with each element being equal, the shorter array will be treated as being the
lesser of the two.

self == other

Compares each element with == and returns TRUE if all elements are equal.

clear

Deletes all elements of an array, making it empty. Returns self.

ary = [1, 2]
ary.clear
p ary # => []

clone
dup

Returns a new array with the same contents as the receiver. clone returns a complete clone of the original
array, including freeze status and singleton methods, while dup duplicates the object contents only. Neither
method copies the methods or elements themselves.

compact
compact!

compact returns a new array consisting of self without any nil elements. compact! performs a destructive
update; if modified, returns self, if not modified, returns nil.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 41 of 172

ary = [1, nil, 2, nil, 3, nil]


p ary.compact # => [1, 2, 3]
p ary # => [1, nil, 2, nil, 3, nil]
ary.compact!
p ary # => [1, 2, 3]
p ary.compact! # => nil

concat(other)

Appends (destructively) the other array to the end of self. Returns self.

array = [1, 2]
a = [3, 4]
array.concat a
p array # => [1, 2, 3, 4]
p a # => [3, 4] # this doesn't change

delete(val)
delete(val) { ... }

Delete all elements equal to val (via ==). When elements equal to val are found, returns val.

If there are no elements equal to val, returns nil. However, if a block has been specified, it will be evaluated
and the result returned.

array = [1, 2, 3, 2, 1]
p array.delete(2) # => 2
p array # => [1, 3, 1]

# if the argument is nil and there's no block, there's no way


# to determine from the return value whether it was deleted
ary = [nil,nil,nil]
p ary.delete(nil) # => nil
p ary # => []
p ary.delete(nil) # => nil

delete_at(pos)

Removes the element at the position specified by pos and returns the removed element. If pos is out of
range, returns nil.

array = [0, 1, 2, 3, 4]
array.delete_at 2
p array # => [0, 1, 3, 4]

each {|item| .... }

Evaluates a block against each element. Returns self.

# 1, 2, 3 are displayed in order


[1, 2, 3].each do |i|
puts i
end

each_index {|index| .... }

Evaluates a block against each element's index. Identical to the following:

(0 ... ary.size).each {|index| .... }

Returns self.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 42 of 172

empty?

Returns TRUE if the number of elements in the array is zero.

include?(val)

Returns TRUE if the array contains an element equal to val (using ==).

index(val)

Returns the position of the first element equal to val (using ==). If no such element is found, returns nil.

insert(nth, [val[, val2 ...]])

Inserts the value of the second or more arguments immediately before the nth element. Returns self. Defined
as below:

class Array
def insert( n, *vals )
self[n, 0] = vals
self
end
end

ary = ["foo", "bar", "baz"]


ary.insert 2, 'a', 'b'
p ary # => ["foo", "bar", "a", "b", "baz"]

If no argument val is specified, does nothing.

length
size

Returns the length of the array. If the array is empty, returns zero.

nitems

Returns the number of non-nil elements.

pop

Removes the last element and returns it. If the array is empty, returns nil.

array = [1, [2, 3], 4]


p array.pop # => 4
p array.pop # => [2, 3]
p array # => [1]

p array.pop # => 1
p array.pop # => nil
p array # => []

push(obj1[, obj2 ...])

Appends obj1, obj2 ... to the end of the array, in order.

Returns self.

array = [1, 2, 3]

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 43 of 172

array.push 4
array.push [5, 6]
array.push 7, 8
p array # => [1, 2, 3, 4, [5, 6], 7, 8]

reverse
reverse!

reverse returns a new array of all elements in reverse order. reverse! destructively updates the elements in
the array.

reverse always returns a new array, while reverse! returns self.

shift

Removes the first element of the array and returns it. The remaining elements are moved up to fill the gap. If
the array is empty, returns nil.

sort
sort!
sort {|a, b| ... }
sort! {|a, b| ... }

Sorts the contents of the array. If called with a block, it passes two arguments to the block, then uses the
result to compare. Without a block, it compares elements with the operator <=>. sort! destructively updates
the elements in the array.

sort returns a new, sorted array, while sort! always returns self.

uniq
uniq!

uniq returns a new array by removing duplicate elements. The remaining elements will then be shifted
forward to fill the gaps. uniq! performs destructive deletion and returns self if deletion was performed and nil
if it was not.

unshift(obj1[, obj2 ...])

Inserts obj1, obj2 ... to the start of the array, in order.

Returns self.

Exception
The ancestor class of all exceptions.

Refer to Built-in Exception Classes for information on its subclasses.

Superclass

{ Object

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 44 of 172

Class Method

Exception.new([error_message])

Creates and returns a new exception object. A string indicating an error message can be supplied as an
argument. This message will become the value of the message attribute (below) and will be displayed by the
default exception handler.

Methods

exception([error_message])

Returns self when no argument is specified. Otherwise, creates a copy of itself with the message attribute as
error_message and returns it.

raise actually calls the Exception object's exception method.

backtrace

Returns backtrace information as a String array in the follow formats:

z "#{sourcefile}:#{sourceline}:in '#{method}'"

(within methods)

z "#{sourcefile}:#{sourceline}"

(at the top level)

message

Returns the error message string.

FalseClass
The false class. false is the only instance of the FalseClass class. false, like nil, denotes a FALSE condition, while
all other objects are TRUE.

Superclass

{ Object

Methods

self & other

Normally returns FALSE.

self | other

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 45 of 172

self ^ other

If other is TRUE, returns TRUE. If FALSE, returns FALSE.

Hash
The hash class. See Hash Expressions for more information.

Superclass

{ Object

Included Modules

{ Enumerable

Methods

self[key]

Returns the value mapped to key. If the corresponding key is not registered, returns the default value (or nil if
not specified).

self[key]=value

Maps value to key. Returns value.

clear

Clears the hash contents. Returns self.

clone
dup

Returns a new hash with the same contents as the receiver. Using clone on a frozen hash will return a
similarly frozen hash, but dup returns an unfrozen hash with identical contents.

Returns value.

delete(key)
delete(key) {|key| ... }

Deletes the mapping from key. Returns the removed value, or nil if there is no value corresponding to key.

When the method has been supplied with a block, it will be evaluated and the results returned if there is no
match for key.

each {|key, value| ... }


each_pair {|key, value| ... }

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 46 of 172

Evaluates a block with key and value as arguments. Returns self.

each_key {|key| ... }

Evaluates a block with key as the argument. Returns self.

each_value {|value| ... }

Evaluates a block with value as the argument. Returns self.

empty?

Returns true when the hash is empty.

has_key?(key)
include?(key)

Returns true when the hash includes key as a key.

has_value?(value)

Returns true when the hash includes value as a value as determined by ==.

index(val)

Returns the key corresponding to val. If there is no corresponding element, returns nil.

If there are multiple corresponding keys, arbitrarily returns one of them.

keys

Returns an array of all keys.

length
size

Returns the number of elements in the hash.

values

Returns an array of all values in the hash.

IO
The IO class provides basic IO functions.

Superclass

{ Object

Included Modules

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 47 of 172

{ Enumerable

Methods

binmode

Converts the stream into binary mode. The only way to revert to normal mode is to reopen the stream.

Returns self.

close

Closes the IO port. An Errno::EXXX exception is thrown if close fails.

Returns nil.

each_line {|line| ... }

Reads from the IO port line by line.

Returns self.

each_byte {|ch| ... }

Reads from the IO port byte by byte.

Returns self.

eof?

Returns true when the stream reaches the end of the file.

pos

Returns the current position of the file pointer.

pos=n

Moves the file pointer to the indicated position.

read([length])

Reads length bytes and returns the string. If length is omitted, reads all data until the end of the file.

If the IO has already reached the end of the file, returns nil.

Throws an Errno::EXXX exception if the data read fails and an ArgumentError exception if length is negative.

readlines([rs])

Reads all the data and returns an array whose elements consist of the lines read. If the IO has already
reached the end of the file, returns the empty array [].

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 48 of 172

Lines are separated by the string indicated in the argument rs, whose default value is "\n".

Specify nil for rs and the lines will not be separated. Specify the empty string "" and consecutive linefeeds will
be treated as line separators (paragraph mode).

write(str)

Outputs str to the IO port. If str is not a string, tries converting it to a string with to_s.

Returns the actual number of bytes written. Throws an Errno::EXXX exception if the output action fails.

File
The file access class, normally created by open or File.open.

Open file objects that cannot be referenced will be closed and discarded by the next garbage collection.

Superclass

{ IO

Class Methods

File.mtime(filename)

Returns the file's last modified time (Time object).

If time retrieval fails, throws an Errno::EXXX exception.

File.basename(filename[, suffix])

Returns the final slash-delimited component of filename. If suffix is supplied and is identical to the end of
filename, filename is returned without the suffix.

p File.basename("ruby/ruby.c") # => "ruby.c"


p File.basename("ruby/ruby.c", ".c") # => "ruby"
p File.basename("ruby/ruby.c", ".*") # => "ruby"
p File.basename("ruby/ruby.exe", ".*") # => "ruby"

See also File.dirname and File.extname.

File.delete(filename ... )

Deletes a file or files and returns the number of files deleted. If deletion fails, throws an Errno::EXXX
exception.

This method is for file deletion and cannot delete directories.

File.dirname(filename)

Returns all but the final slash-delimited component of filename. Returns "." (the current directory) for a
filename that does not include a slash.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 49 of 172

p File.dirname("dir/file.ext") # => "dir"


p File.dirname("file.ext") # => "."
p File.dirname("foo/bar/") # => "foo"
p File.dirname("foo//bar") # => "foo"

See also File.basename and File.extname.

File.expand_path(path[, default_dir])

Returns a string containing path's expanded absolute path. If path is relative, sets default_dir as the base
directory. If default_dir is nil or missing, uses the current directory.

p File.expand_path("..") # => "/home/matz/work"


p File.expand_path("..", "/tmp") # => "/"

File.extname(filename)

Returns filename's extension (the string after the final dot). Dots in directory names or at the start of
filenames are not considered to be denoting extensions. If filename contains no extension, returns an empty
string.

p File.extname("foo/foo.txt") # => ".txt"


p File.extname("foo/foo.tar.gz") # => ".gz"
p File.extname("foo/bar") # => ""
p File.extname("foo/.bar") # => ""
p File.extname("foo.txt/bar") # => ""
p File.extname(".foo") # => ""

See also File.basename and File.dirname.

File.open(path[, mode])
File.open(path[, mode]) {|file| ... }

Opens the file specified by path and returns the file object. If file opening fails, throws an Errno::EXXX
exception.

The mode argument is identical to the built-in function open.

Blocks can be specified for open(). When called with a block, executes the block with the given file object.
The file will be closed automatically after executing the block.

When a block is specified, the return value of this method is the result of the block's evaluation.
File.rename(from, to)

Renames file, moving it to a different directory as required. If a file already exists at the destination, it is
overwritten.

Returns 0 when file movement is successful; when it fails, throws an Errno::EXXX exception.

Methods

mtime

Returns the file's last modified time (Time object).

If time retrieval fails, throws an Errno::EXXX exception.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 50 of 172

path

Returns the path of the opened file.

MatchData
The class handling regular expression match data. Instances of this class can be obtained via

{ Regexp.last_match,
{ Regexp#match, and
{ $~.

Superclass

{ Object

Methods

self[n]

Returns the nth substring. 0 signifies the entire matching string. When the value of n is negative, it is treated
as a backwards index (the final element being in the position -1). When the nth element does not exist,
returns nil.

/(foo)(bar)(BAZ)?/ =~ "foobarbaz"
p $~.to_a # => ["foobar", "foo", "bar", nil]
p $~[0] # => "foobar"
p $~[1] # => "foo"
p $~[2] # => "bar"
p $~[3] # => nil (doesn't match)
p $~[4] # => nil (out of range)
p $~[-2] # => "bar"

post_match

Returns the string after the matching portion.

pre_match

Returns the string before the matching portion.

to_a

Returns an array containing $&, $1, $2, ...

to_s

Returns the entire matching string.

Module

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 51 of 172

The module class.

Superclass

{ Object

Method

self === obj

This method is mostly used for comparison within case statements. Returns true if obj has an
Object#kind_of? relationship with self. In other words, case can be used to check the owner relationship of
classes and modules.

str = String.new
case str
when String # evaluates String === str
p true # => true
end

Private Methods

attr_accessor(name ... )

Defines both the read and write methods for the attribute name, where name is specified by Symbol or a
string.

The definition of the method defined by attr_accessor is as follows:

def name
@name
end
def name=(val)
@name = val
end

attr_reader(name ... )

Defines the read method for the attribute name, where name is specified by Symbol or a string.

The definition of the method defined by attr_reader is as follows:

def name
@name
end

attr_writer(name ... )

Defines the writer method for the specified attribute(s).

Defines the write method for the attribute name (name=), where name is specified by Symbol or a string.

The definition of the method defined by attr_writer is as follows:

def name=(val)
@name = val

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 52 of 172

end

include(module ... )

Includes the specified modules' properties (methods and constants). Returns self. include is used to
implement a mix-in in place of a multiple inheritance.

class C
include FileTest
include Math
end

Module capabilities are included by inserting modules into a class inheritance. Therefore, when searching for
methods, included modules will be given priority over superclasses.

If the same module is included two or more times, the second and later instances will be ignored.
Furthermore, executing an include that results in a recursive module inheritance will throw an ArgumentError
exception.

Class
The class of classes. More accurately speaking, each class has its own unnamed "metaclass", and Class is the
class of these metaclasses. This relationship is a little complicated, but it is not especially important to keep in
mind while using Ruby.

Compared to modules, classes

{ can create instances and


{ cannot perform mix-in using include

Otherwise, nearly all of its capabilities are inherited from Module.

Superclass

{ Module

Method

new( ... )

Creates a class instance and returns it. This method's arguments, including block arguments, are passed to
initialize.

NilClass
The nil class of nil. nil is the sole instance of this class, signifying FALSE along with the false object. All other
objects are true.

Superclass

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 53 of 172

{ Object

Methods

self & other

Always returns false.

self | other
self ^ other

If other is true, returns true; if false, returns false.

nil?

Always returns true.

to_a

Returns the empty array [].

to_f

Returns 0.0.

to_i

Returns 0.

to_s

Returns the empty string "".

Numeric
Numeric is the abstract class for numbers. In Ruby, operations are possible among different numerical classes.

Operations and comparison methods (+, -, *, /, <=>), etc. are defined in a subclass. For increased efficiency,
methods identical to the Numeric method may also be redefined in a subclass.

Superclass

{ Object

Included Modules

{ Comparable

Methods

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 54 of 172

+ self

Returns self.

- self

Returns self, negated.

This method is defined by the binary operator - in 0 - self.

abs

Returns the absolute value of self.

ceil

Returns the smallest integer equal to or greater than self (i.e., the ceiling).

floor

Returns the largest integer that does not exceed self (i.e., the floor).

integer?

Returs true when self is an integer.

round

Returns the integer closest to self.

truncate

Discards the decimal point and all digits after it.

Integer
The abstract class for integers. Its subclasses are Fixnum and Bignum. These two types of integers are
automatically converted into one another according to their values. Integers can be treated as infinite bit strings for
bit operations.

Superclass

{ Numeric

Methods

self[nth]

Returns 1 if the nth bit of the integer is set (with the LSB, or least significant bit, at position 0), otherwise
returns 0.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 55 of 172

self[nth]=bit is not an Integer method because the associated Numeric class is immutable.

self + other
self - other
self * other
self / other
self % other
self ** other

Arithmetic operators. Compute the sum, difference, product, quotient, remainder, and exponent respectively.

self <=> other

Compares self with other; returns a positive integer if self is larger, 0 if the two are equal, and a negative
integer if self is smaller.

self == other
self < other
self <= other
self > other
self >= other

Relational operators.

~ self
self | other
self & other
self ^ other

Bit operators. Compute bitwise negation, logical OR, logical AND, and logical XOR respectively.

self << bits


self >> bits

Shift operators. Shift only bits to the right or left.

The signed bit (MSB or most significant bit) is retained in a right shift.

chr

Returns a 1-byte string corresponding to the numeric position in the character set. For example, 65.chr
returns "A".

The integer must be within the range of 0 to 255. Calling this method with an out-of-range integer will throw a
RangeError exception.

downto(min) {|n| ... }

Iterates from self to min, decrementing by 1. If self < min, does nothing.

See also upto, step, and times.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 56 of 172

next
succ

Returns the "next" value of an integer.

step(limit, step) {|n| ... }

Iteratively evaluates a block from self, incrementing by step, until limit is about to be surpassed. step can
also be a negative number.

When step is set to 0, throws an ArgumentError exception.

Returns self.

See also upto, downto, and times.

times {|n| ... }

Iterates self number of times, from 0 to self-1. If self is negative, does nothing.

Returns self.

See also upto, downto, and step.

to_f

Converts a value to a floating point integer (Float).

to_s([base])

Converts an integer to a base-10 string expression.

If an argument is specified, it will be used as the base number for conversion. If a base outside the range of
2-36 is specified, an ArgumentError exception will be thrown.

p 10.to_s(2) # => "1010"


p 10.to_s(8) # => "12"
p 10.to_s(16) # => "a"
p 35.to_s(36) # => "z"

upto(max) {|n| ... }

Iterates from self to max, incrementing by 1. If self > max, does nothing.

Returns self.

See also downto, step, and times.

Bignum
The class for long integers, limited only by memory size. The result of an operation is automatically converted into
a Fixnum if its value is within range; conversely, if the value is out of Fixnum range, it is extended into a Bignum.
For bit operations, Bignum can be considered to be an infinite 2's complement bit string. Negative numbers in

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 57 of 172

particular can operate as a string of 1 bits extending indefinitely to the left. Mixing Bignum with Float can result in
digit cancellation errors upon conversion.

Superclass

{ Integer

Fixnum
The class for fixed-length integers that fit into the machine's pointer, which is usually 31 bits long. If the result of an
operation is out of Fixnum range, it is automatically extended into a Bignum.

Superclass

{ Integer

Methods

id2name

Returns the string corresponding to a Symbol integer (obtained with Symbol#to_i). If there is no symbol that
corresponds to the integer, returns nil.

to_sym

Returns the Symbol object corresponding to the integer value of the object's self. If there is no symbol that
corresponds to the integer, returns nil.

Float
The floating point value class. The implementation of Float is the same as in C.

Superclass

{ Numeric

Methods

self + other
self - other
self * other
self / other
self % other
self ** other

Arithmetic operator. Computes the sum, difference, product, quotient, remainder, and exponent.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 58 of 172

self <=> other

Compares other with self; returns a positive integer if self is larger, 0 if the two are equal, and a negative
integer if self is smaller.

self == other
self < other
self <= other
self > other
self >= other

Relational operator.

finite?

Returns TRUE even if the value is infinite, unless it is also NaN.

infinite?

Returns 1 when a value is positive and infinite; returns -1 when a value is negative and infinite. Otherwise,
returns nil. The floating point zero ensures infinite division.

inf = 1.0/0
p inf
p inf.infinite?

=> Infinity
1

inf = -1.0/0
p inf
p inf.infinite?

=> -Infinity
-1

nan?

Returns TRUE when a value is NaN (not a number). The floating point zero ensures the result of division by
0 is NaN.

nan = 0.0/0.0
p nan
p nan.nan?

=> NaN
true

Range
The range object class. See Range Expressions for more information.

Superclass

{ Object

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 59 of 172

Included Module

{ Enumerable

Methods

self === other

This method is mostly used for comparison within case statements. Returns true if other is within range.

begin
first

Returns the initial element.

each {|item| ... }

Iterates over each element within the range.

end
last

Returns the end point, regardless of whether the range object is inclusive of the end point.

p (1..5).end # => 5
p (1...5).end # => 5

exclude_end?

Returns true if the range object is exclusive of the end point.

Proc
Proc is a procedure object in which both a block and its context (local variable scope and stack frame) have been
encapsulated as an object. Proc can be used like an unnamed function, except that it does not have its own local
variable scope.

We can see that Proc retains a local variable scope, however, by observing that the variable var can be
referenced, as in the example below:

var = 1
$foo = Proc.new { var }
var = 2

def foo
$foo.call
end

p foo # => 2

Superclass

{ Object

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 60 of 172

Class Method

Proc.new
Proc.new { ... }

Encapsulates a block, along with its context, into an object and returns it.

If no block is specified, but the method that called Proc.new contains a block, that block will be created as a
Proc object and returned.

Method

call(arg ... )

Executes a procedure object and returns the result. Arguments are assigned to block parameters as is
(according to the rules of multiple assignation).

Regexp
The regular expression class. See Regular Expressions for details.

Superclass

{ Object

Class Methods

Regexp.last_match

Returns the MatchData object for the last regular expression match performed in the current scope. This
method call is identical to a $~ reference.

/(.)(.)/ =~ "ab"
p Regexp.last_match # => #<MatchData:0x4599e58>
p Regexp.last_match[0] # => "ab"
p Regexp.last_match[1] # => "a"
p Regexp.last_match[2] # => "b"
p Regexp.last_match[3] # => nil

Regexp.last_match([nth])

If the integer nth is 0, returns the matching string ($&). Otherwise, returns the substring matching the nth set
of parentheses ($1, $2, ...). When there are no corresponding parentheses or no matches, returns nil.

/(.)(.)/ =~ "ab"
p Regexp.last_match # => #<MatchData:0x4599e58>
p Regexp.last_match(0) # => "ab"
p Regexp.last_match(1) # => "a"
p Regexp.last_match(2) # => "b"
p Regexp.last_match(3) # => nil

Because Regexp.last_match, with no arguments, returns nil when the entire regular expression does not

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 61 of 172

match, the format last_match[1] will throw a NameError exception. On the other hand, last_match(1) returns
nil.

Methods

self =~ string
self === string

Matches the string string to a regular expression. If the argument is not a string or does not match, returns
false; if it matches, returns true.

Matching information can be configured in the built-in variable $~.

If string is neither nil nor a String object, throws a TypeError exception.

match(str)

Identical to self=~str, except that it does not return a MatchData object. If there is no match, returns nil.

When only the substring matching the regular expression is needed, use match(str) like this:

bar = /foo(.*)baz/.match("foobarbaz").to_a[1]

_, foo, bar, baz = */(foo)(bar)(baz)/.match("foobarbaz")

to_a takes failed matches into account.

to_s

Creates and returns a string expression for a regular expression. Preserves the meaning of the returned
string even if the string is embedded in another regular expression.

re = /foo|bar|baz/i
p re.to_s # => "(?i-mx:foo|bar|baz)"
p /#{re}+/o # => /(?i-mx:foo|bar|baz)+/

However, some regular expressions with backreferences may not work as expected. This is because
backreferences can only be specified by number at present.

re = /(foo|bar)\1/ # \1 is foo or bar


p /(baz)#{re}/ # \1 is baz

# => /(baz)(?-mix:(foo|bar)\1)/

String
The string class. Can handle byte sequences of arbitrary lengths. See String Literals for details.

The String class itself behaves like a byte sequence. Use scan(/./), etc. to extract characters from a multibyte
string one at a time.

Superclass

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 62 of 172

{ Object

Included Modules

{ Comparable
{ Enumerable

Methods

self + other

Returns a new concatenated string.

self * times

Creates and returns a new string consisting of the string contents repeated times times.

self <=> other

Compares self with other by ASCII order; returns a positive integer if self is larger, 0 if the two are equal, and
a negative integer if self is smaller.

self == other

Determines whether the strings are equal.

self[nth, len]

Returns a len-byte-long substring found at the nth byte. When nth is negative, counts from the end of the
string.

If nth is out of range, returns nil.

self[regexp]

Returns the first substring matching regexp. Matching information can be configured in the built-in variable
$~.

If there is no match to regexp, returns nil.

p "foobar"[/bar/] # => "bar"

self[nth, len]=val

Replaces the len-byte-long substring found at the nth byte with the string val. When nth is negative, counts
from the end of the string.

Returns val .

self[regexp]=val

Replaces the first substring matching the regular expression regexp with the string val.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 63 of 172

If there is no match to the regular expression, throws an IndexError exception.

Returns val.

clone
dup

Returns a new string with the same contents as the original string. Using clone on a frozen string will return a
similarly frozen string, but dup returns an unfrozen string with identical contents.

concat(other)

Appends the contents of the string other to self. Returns self.

downcase
downcase!

Replaces all uppercase characters with lowercase characters.

downcase creates and returns the modified string. downcase! modifies and returns self, but if no characters
were replaced, returns nil.

See also upcase.

each {|line| ... }


each_line {|line| ... }

Iterates over each line in the string.

Returns self.

each_byte {|byte| ... }

Iterates over each byte of the string. Returns self.

empty?

Returns true if the string is empty (i.e., a zero-length string).

gsub(pattern) {|matched| .... }


gsub!(pattern) {|matched| .... }

Replaces all substrings matching pattern with the results of the block evaluation. The matching substring is
passed to the block as an argument. The built-in variable $<digits> can be referenced within the block.

p 'abcabc'.gsub(/b/) {|s| s.upcase } # => "aBcaBc"


p 'abcabc'.gsub(/b/) { $&.upcase } # => "aBcaBc"
p 'abbbcd'.gsub(/a(b+)/) { $1 } # => "bbbcd"

gsub creates and returns the post-replacement string. gsub! modifies and returns self, but if no characters
were replaced, returns nil.

See also sub.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 64 of 172

include?(substr)

Returns true if the substring substr is included in the text string.

If substr is a Fixnum from 0 to 255, it is determined to be a character code and if that character is included, it
returns true.

index(pattern[, pos])

Performs a search for the substring from left to right. Returns the left-hand position of the found substring. If
nothing is found, nil is returned.

The pattern argument is used to specify the substring to search for, using a text string, an integer from 0 to
255, or a regular expression.

If pos is provided, the search starts from that position. The value of pos when it is omitted is 0.

insert(nth, other)

Inserts the string other immediately before the character in the nth position. Returns self.

p "foobaz".insert(3, "bar") # => "foobarbaz"

to_sym

Returns the symbol value (Symbol) corresponding to the string.

Use Symbol#id2name to obtain the string corresponding to a symbol.

p "foo".to_sym # => :foo


p "foo".to_sym.to_s == "foo" # => true

length
size

Returns the length of the string in bytes.

scan(re)
scan(re) {|s| ... }

Repeatedly matches against self with the regular expression re and returns an array of matching substrings.

p "foobarbazfoobarbaz".scan(/ba./)
# => ["bar", "baz", "bar", "baz"]

p "abcde".scan(/./)
# => ["a", "b", "c", "d", "e"]

When called with a block specified, the matching substrings become the block's parameters. (If parentheses
are included, an array of strings that match the patterns in parentheses becomes the block's parameter.) If a
block is specified, returns self.

"foobarbazfoobarbaz".scan(/ba./) {|s| p s}
# => "bar"
"baz"
"bar"
"baz"

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 65 of 172

slice(nth, len)
slice(regexp)

Identical to self[].

slice!(nth, len)
slice!(regexp)

Removes a specified range (see self[]) from a string and returns the removed substring.

If the argument is out of range, returns nil.

sub(pattern) {|matched| ... }


sub!(pattern) {|matched| ... }

Replaces the first substring matching pattern with the results of the block evaluation.

sub creates and returns the post-replacement string. sub! modifies and returns self, but if no characters were
replaced, returns nil.

Identical to gsub, except that sub only matches once.

to_f

Interprets the string as a base-10 expression and converts it into a floating point integer (Float).

to_i([base])

Interprets the string as a numeric expression and converts it into an integer.

The default is base-10. By specifing base, you can perform base 2-36 conversions as well.

upcase
upcase!

Replaces all lowercase characters with uppercase characters.

downcase creates and returns the modified string. downcase! modifies and returns self, but if no characters
were replaced, returns nil.

See also downcase.

Symbol
The class that expresses symbols. See Symbol for more information.

Superclass

{ Object

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 66 of 172

Methods

id2name

Returns the string corresponding to a symbol.

Use String#to_sym to obtain the symbol corresponding to a string.

p :foo.id2name.to_sym == :foo # => true

to_i

Returns the integer corresponding to a symbol.

Use Fixnum#to_sym to obtain the symbol corresponding to this integer.

p :foo.to_i # => 8881


p :foo.to_i.to_sym # => :foo

In Ruby, reserved words, variable names, method names, and the like are controlled by these integers.
Integers corresponding to objects (obtained via Object#object_id) and those corresponding to symbols are
separate items.

Time
The time class.

Superclass

{ Object

Included Module

{ Comparable

Class Method

Time.now

Returns the current Time object.

Methods

self + other

Returns a time that is later than self by other seconds.

self - other

When other is a Time object, returns the difference between the two times with Float. If other is a numeric

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 67 of 172

value, returns a time that is earlier than self by other.

self <=> other

Compares times. other must be a Time object or a numeric value; if a numeric value, the times are
compared in terms of seconds since the epoch began.

strftime(format)

Returns the time, having been converted into a string via a format string. The format string may be specified
with the following:

z %A

Day of the week (Sunday, Monday ... )

z %a

Day of the week, abbreviated (Sun, Mon ... )

z %B

Month (January, February ... )

z %b

Month, abbreviated (Jan, Feb ... )

z %c

Date and time

z %d

Day of the month (01-31)

z %H

Time of day, 24-hour format (00-23)

z %I

Time of day, 12-hour format (01-12)

z %j

Day of the year (001-366)

z %M

Minutes (00-59)

z %m

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 68 of 172

Month of the year (01-12)

z %p

AM or PM

z %S

Seconds (00-60, 60 being a leap second)

z %U

Week of the year, the first week starting with the first Sunday (00-53)

z %W

Week of the year, the first week starting with the first Monday (00-53)

z %w

Day of the week (0-6, 0 denoting Sunday)

z %X

Time

z %x

Date

z %Y

Year, 4-digit

z %y

Year, 2-digit (00-99)

z %Z

Time zone

z %%

The character %

sec

Returns the seconds.

min

Returns the minutes.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 69 of 172

hour

Returns the hour.

mday

Returns the day.

mon

Returns the month.

year

Returns the year.

wday

Returns the number representing the day of the week.

TrueClass
The true class. true is the only instance of the TrueClass class. true is a representative object that denotes a
TRUE condition.

Superclass

{ Object

Methods

self & other

If other is TRUE, returns TRUE. If FALSE, returns FALSE.

self | other

Normally returns TRUE.

self ^ other

If other is TRUE, returns FALSE. If FALSE, returns TRUE.

Built-in Modules
{ Comparable
{ Enumerable
{ Errno
{ FileTest

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 70 of 172

{ GC
{ Kernel
{ Marshal
{ Math

Comparable
A mix-in allowing for relational operations. Classes including this module must define the basic relational operators
<, =, and >. All other relational operators can be derived through use of those definitions.

Methods

self == other

Returns TRUE when self and other are equal.

When <=> returns nil, returns nil.

self > other

Returns TRUE when self is greater than other.

When <=> returns nil, throws an ArgumentError exception.

self >= other

Returns TRUE when self is greater than or equal to other.

When <=> returns nil, throws an ArgumentError exception.

self < other

Returns TRUE when self is less than other.

When <=> returns nil, throws an ArgumentError exception.

self <= other

Returns TRUE when self is less than or equal to other.

When <=> returns nil, throws an ArgumentError exception.

between?(min, max)

Returns TRUE when self falls within a range from min to max, inclusive.

When self <=> min or self <=> max returns nil, throws an ArgumentError exception.

Enumerable

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 71 of 172

A mix-in for repeating classes. This module's methods are all defined via each, so each must be defined in any
class which includes this module.

Method

all?
all? {|item| ... }

Returns TRUE when all items are true. If any item is false, immediately returns FALSE.

When using a block, evaluates the block against each item and returns TRUE if all outcomes are true. If the
block returns FALSE at any time, immediately returns FALSE.

p [1,2,3].all? {|v| v > 0} # => true


p [1,2,3].all? {|v| v > 1} # => false

any?
any? {|item| ... }

Returns FALSE when all items are false. If any item is true, immediately returns TRUE.

When using a block, evaluates the block against each item and returns FALSE if all outcomes are false. If
the block returns TRUE at any time, immediately returns TRUE.

p [1,2,3].any? {|v| v > 3} # => false


p [1,2,3].any? {|v| v > 1} # => true

find {|item| ... }

Returns the first item that tested as true during the block evaluation. If no item was true, returns nil.

find_all {|item| ... }

Returns an array of all items that tested as true during the block evaluation. If no item was true, returns an
empty array.

include?(val)

Returns TRUE when the list includes an item that satisfies the relationship val ==.

max

Returns the largest item. Assumes all items are comparable via the <=> method.

max {|a, b| ... }

Compares each item based on the block's evaluated value and returns the largest item.

Anticipates a block value that will be a positive integer when a>b, 0 when a==b, and a negative integer when
a<b. When the block returns a non-integer, throws a TypeError exception.

min

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 72 of 172

Returns the smallest item. Assumes all items are comparable via the <=> method.

min {|a, b| ... }

Compares each item based on the block's evaluated value and returns the smallest item.

Anticipates a block value that will be a positive integer when a>b, 0 when a==b, and a negative integer when
a<b. When the block returns a non-integer, throws a TypeError exception.

sort
sort {|a, b| ... }

Creates and returns an array of all items sorted in ascending order.

When not using a block, calls the <=> against each item and sorts based upon those results.

To sort using other methods besides <=>, select a block; the items will be sorted based on the evaluation of
this block. Anticipates a block value that will be a positive integer when a>b, 0 when a==b, and a negative
integer when a<b. When the block returns a non-integer, throws a TypeError exception.

to_a
entries

Returns an array of all items.

Errno
A module containing exceptions corresponding to system call errors.

Inner Classes

These are representative exception classes. Many others are defined as well, but you need not be concerned
about them.

E2BIG
The argument list is too long.
EACCES
Access permission was denied.
EAGAIN
Cannot create any more processes.
EBADF
Invalid file number.
ECHILD
No child process exists.
EDEADLOCK
Possibility of a resource deadlock.
EDOM
The value of the numerical data function's argument is outside the function's domain.
EEXIST

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 73 of 172

File already exists.


EINVAL
Invalid argument.
EMFILE
Too many open files.
ENOENT
No file or directory.
ENOEXEC
Executable file error.
ENOMEM
Not enough memory.
ENOSPC
Not enough free space on device.
ERANGE
Results are too large.
EXDEV
Device interlink.

FileTest
A module containing file test functions.

Module Functions

FileTest.exist?(filename)

Returns TRUE when filename exists.

FileTest.directory?(filename)

Returns TRUE when filename is a directory.

FileTest.file?(filename)

Returns TRUE when filename is an ordinary file.

FileTest.size(filename)

Returns the size of filename. If filename does not exist, throws an Errno::EXXX exception (most likely
Errno::ENOENT).

GC
A module that controls garbage collection in the Ruby interpreter.

Module Method

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 74 of 172

GC.disable

Halts garbage collection.

Returns the previous halt state (if halted, returns TRUE; if garbage collection was enabled, returns FALSE).

GC.enable

Permits garbage collection.

Returns the previous halt state (if halted, returns TRUE; if garbage collection was enabled, returns FALSE).

GC.start

Initializes garbage collection.

Returns nil.

Kernel
A module defining the methods that can be referred to by all classes. Object classes are included in this module.
The methods explained on the Built-in Functions page are defined in this module.

Object class methods are defined in this module. This ensures compatibility with top-level method redefinition.

Marshal
A module providing the capability to write a Ruby object to and read it from a file (or string array).

Module Functions

Marshal.dump(obj[, port][, limit])

Writes obj to a file recursively.

Some objects may not be writeable to file, such as in instances of File or MatchData, or with objects that
define unusual methods. When attempting to write such objects to file, a TypeError will occur.

port specifies an instance of IO (or a subclass). In this case, returns port. When omitted, dump returns the
object's dump as a string.

When limit is specified, no objects linked at or deeper than limit can be dumped (100 levels is the default.
When limit is negative, no depth checking is performed.

Marshal.load(port)

Reads marshal data from port (i.e., the string output from Marshal.dump) and creates an object with the
same state as the original object. port specifies an instance of IO (or a subclass).

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 75 of 172

Math
A module that supports floating point calculations.

Module Functions

Math.acos(x)
Math.asin(x)
Math.atan(x)

Returns the value of the inverse trigonometric functions of x in radians.

Values that can be returned have ranges of [0, +π], [-π/2, +π/2], and (-π/2, +π/2) respectively.

In acos(x), and asin(x), x must be in the range -1.0 <= x <= 1 (normally returns NaN).

acos() and asin() will throw an Errno::EDOM exception for arguments out of range.

Math.atan2(y, x)

Returns the arctangent of y/x in the range [-π, π].

Math.acosh(x)
Math.asinh(x)
Math.atanh(x)

Returns the value of the inverse hyperbolic functions of x.

asinh(x) = log(x + sqrt(x * x + 1))


acosh(x) = log(x + sqrt(x * x - 1)) [x >= 1]
atanh(x) = log((1+x)/(1-x)) / 2 [-1 < x < 1]

In acosh(x), x must be >= 1 (normally throws an Errno::EDOM exception).

In atanh(x), x must be in the range -1.0 < x < 1 (normally throws an Errno::EDOM exception).

Math.cos(x)
Math.sin(x)
Math.tan(x)

Returns the value of the trigonometric functions of x in radians, in the range [-1, 1].

Math.cosh(x)
Math.sinh(x)
Math.tanh(x)

Returns the value of the hyperbolic functions of x.

cosh(x) = (exp(x) + exp(-x)) / 2


sinh(x) = (exp(x) - exp(-x)) / 2
tanh(x) = sinh(x) / cosh(x)

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 76 of 172

Math.erf(x)
Math.erfc(x)

Returns the values of the error function (erf) and complementary error function (erfc) of x.

Math.exp(x)

Returns the value of the exponential function of x.

Math.frexp(x)

Returns the exponent and mantissa of the real number x.

Math.hypot(x, y)

Returns sqrt(x*x + y*y).

Math.ldexp(x, exp)

Returns the real number x multiplied by 2 to the power of exp.

Math.log(x)

Returns the natural logarithm of x.

x must be a positive value (normally returns NaN for negative values and -Infinity for 0).

Negative arguments out of range throw Errno::EDOM exceptions, while a 0 argument throws an
Errno::ERANGE exception.

Math.log10(x)

Returns the common logarithm of x.

x must be a positive value (normally returns NaN for negative values and -Infinity for 0).

Negative arguments out of range throw Errno::EDOM exceptions, while a 0 argument throws an
Errno::ERANGE exception.

Math.sqrt(x)

Returns the square root of x. When x is a negative value, throws an ArgumentError exception.

Normally, when x is negative, throws an Errno::EDOM exception.

Definitions

The natural logarithmic base.

p Math::E
# => 2.718281828

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 77 of 172

PI

The circle ratio.

p Math::PI
# => 3.141592654

Built-in Exception Classes


Exception
The superclass of all exceptions.
NoMemoryError
Thrown when attempting to reserve too much memory at once.
ScriptError
Indicates a script error.
NotImplementedError
Thrown when an unimplemented feature is invoked.
SyntaxError
Thrown by a syntax error.
StandardError
Without a class specified, the rescue class will catch the subclasses of this exception class.
ArgumentError
Thrown when argument numbers do not match or when the values are incorrect.
IndexError
Thrown when the index is out of range.
IOError
Thrown when an I/O error occurs.
EOFError
Thrown when EOF (End Of File) has been reached.
LocalJumpError
Thrown when no jump destination is found for a control structure.
NameError
Thrown when accessing an undefined local variable or constant.
NoMethodError
Thrown when calling an undefined method.
RangeError
A range exception. Thrown when an out-of-range integer conversion (from Bignum to Fixnum) ,
etc., occurs.
FloatDomainError
Thrown when trying to convert a positive or negative infinite number or NaN (Not a Number)
into Bignum , or when comparing a number to a NaN.
RegexpError
Thrown when compiling a regular expression fails.
RuntimeError
A runtime exception. Thrown when calling raise without specifying an exception.
SystemCallError
Thrown when a system call fails.
Errno::EXXX

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 78 of 172

Exception class for each errno. See the Errno module for more on each class name.
SystemStackError
Thrown when a stack level becomes too deep.
TypeError
Thrown when an illegal type is invoked.
ZeroDivisionError
Thrown when dividing by zero.
SystemExit
Terminates the program. See exit for more information.
fatal
A fatal (internal) error. This object is not visible with normal methods.

Game Library
{ RGSS Built-in Functions
{ RGSS Built-in Classes
„ Bitmap
„ Color
„ Font
„ Plane
„ Rect
„ Sprite
„ Table
„ Tilemap
„ Tone
„ Viewport
„ Window
„ RGSSError
{ RGSS Built-in Modules
„ Audio
„ Graphics
„ Input
„ RPG
{ RPGVX Data Structures
„ RPG::Map
„ RPG::MapInfo
„ RPG::Area
„ RPG::Event
„ RPG::Event::Page
„ RPG::Event::Page::Condition
„ RPG::Event::Page::Graphic
„ RPG::EventCommand
„ RPG::MoveRoute
„ RPG::MoveCommand
„ RPG::Actor
„ RPG::Class
„ RPG::Class::Learning

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 79 of 172

„ RPG::BaseItem
„ RPG::UsableItem
„ RPG::Skill
„ RPG::Item
„ RPG::Weapon
„ RPG::Armor
„ RPG::Enemy
„ RPG::Enemy::DropItem
„ RPG::Enemy::Action
„ RPG::Troop
„ RPG::Troop::Member
„ RPG::Troop::Page
„ RPG::Troop::Page::Condition
„ RPG::State
„ RPG::Animation
„ RPG::Animation::Frame
„ RPG::Animation::Timing
„ RPG::CommonEvent
„ RPG::System
„ RPG::System::Vechile
„ RPG::System::Terms
„ RPG::System::TestBattler
„ RPG::AudioFile
„ RPG::BGM
„ RPG::BGS
„ RPG::ME
„ RPG::SE

RGSS Built-in Functions


The following built-in functions are defined in RGSS.

load_data(filename)

Loads the data file indicated by filename and restores the object.

$data_actors = load_data("Data/Actors.rvdata")

This function is essentially the same as:

File.open(filename, "rb") { |f|


obj = Marshal.load(f)
}

However, it differs in that it can load files from within encrypted archives.

save_data(obj, filename)

Saves the object obj to the data file indicated by filename.

save_data($data_actors, "Data/Actors.rvdata")

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 80 of 172

This function is the same as:

File.open(filename, "wb") { |f|


Marshal.dump(obj, f)
}

It is unlikely you will ever use this function during a game, but it is defined as a counterpart to load_data.

Also, the built-in functions p and print are redefined for use in message box output.

RGSS Built-in Classes


{ Bitmap
{ Color
{ Font
{ Plane
{ Rect
{ Sprite
{ Table
{ Tilemap
{ Tone
{ Viewport
{ Window
{ RGSSError

Bitmap
The bitmap class. Bitmaps are expressions of so-called graphics.

Sprites (Sprite) and other objects must be used to display bitmaps on the screen.

Superclass

{ Object

Class Methods

Bitmap.new(filename)

Loads the graphic file specified in filename and creates a bitmap object.

Also automatically searches files included in RGSS-RTP and encrypted archives. File extensions may be
omitted.

Bitmap.new(width, height)

Creates a bitmap object with the specified size.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 81 of 172

Methods

dispose

Frees the bitmap. If the bitmap has already been freed, does nothing.

disposed?

Returns TRUE if the bitmap has been freed.

width

Gets the bitmap width.

height

Gets the bitmap height.

rect

Gets the bitmap rectangle (Rect).

blt(x, y, src_bitmap, src_rect[, opacity])

Performs a block transfer from the src_bitmap box src_rect (Rect) to the specified bitmap coordinates (x, y).

opacity can be set from 0 to 255.

stretch_blt(dest_rect, src_bitmap, src_rect[, opacity])

Performs a block transfer from the src_bitmap box src_rect (Rect) to the specified bitmap box dest_rect
(Rect).

opacity can be set from 0 to 255.

fill_rect(x, y, width, height, color)


fill_rect(rect, color)

Fills the bitmap box (x, y, width, height) or rect (Rect) with color (Color).

gradient_fill_rect(x, y, width, height, color1, color2[, vertical]) (RGSS2)


gradient_fill_rect(rect, color1, color2[, vertical]) (RGSS2)

Fills in this bitmap box (x, y, width, height) or rect (Rect) with a gradient from color1 (Color) to color2 (Color).

Set vertical to true to create a vertical gradient. Horizontal gradient is the default.

clear

Clears the entire bitmap.

clear_rect(x, y, width, height) (RGSS2)

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 82 of 172

clear_rect(rect) (RGSS2)

Clears this bitmap box or (x, y, width, height) or rect (Rect).

get_pixel(x, y)

Gets the color (Color) at the specified pixel (x, y).

set_pixel(x, y, color)

Sets the specified pixel (x, y) to color (Color).

hue_change(hue)

Changes the bitmap's hue within 360 degrees of displacement.

This process is time-consuming. Furthermore, due to conversion errors, repeated hue changes may result in
color loss.

blur (RGSS2)

Applies a blur effect to the bitmap. This process is time consuming.

radial_blur(angle, division) (RGSS2)

Applies a radial blur to the bitmap. angle is used to specify an angle from 0 to 360. The larger the number,
the rounder the effect.

division is the division number (from 2 to 100). The larger the number, the smoother it will be. This process
can be very time consuming.

draw_text(x, y, width, height, str[, align])


draw_text(rect, str[, align])

Draws a string str in the bitmap box (x, y, width, height) or rect (Rect).

If str is not a character string object, it will be converted to a character string using the to_s method before
processing is performed. (RGSS2)

If the text length exceeds the box's width, the text width will automatically be reduced by up to 60 percent.

Horizontal text is left-aligned by default; set align to 1 to center the text and to 2 to right-align it. Vertical text
is always centered.

As this process is time-consuming, redrawing the text with every frame is not recommended.

text_size(str)

Gets the box (Rect) used when drawing a string str with the draw_text method. Does not include the angled
portions of italicized text.

If str is not a character string object, it will be converted to a character string using the to_s method before

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 83 of 172

processing is performed.(RGSS2)

Property

font

The font (Font) used to draw a string with the draw_text method.

Color
The RGBA color class. Each component is handled with a floating point value (Float).

Superclass

{ Object

Class Method

Color.new(red, green, blue[, alpha])

Creates a Color object. If alpha is omitted, it is assumed at 255.

Method

set(red, green, blue[, alpha])

Sets all components at once.

Properties

red

The red value (0-255). Values out of range are automatically corrected.

green

The green value (0-255). Values out of range are automatically corrected.

blue

The blue value (0-255). Values out of range are automatically corrected.

alpha

The alpha value (0-255). Values out of range are automatically corrected.

Font

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 84 of 172

The font class. Font is a property of the Bitmap class.

Superclass

{ Object

Class Methods

Font.new([name[, size]])

Creates a Font object.

Font.exist?(name)

Returns TRUE when the specified font exists within the system.

Properties

name

The font name. Include an array of strings to specify multiple fonts to be used in a desired order.

font.name = ["Myriad", "Verdana"]

In this example, if the higher priority font Myriad does not exist within the system, the second choice Verdana
will be used instead.

The default is ["Verdana", "Arial", "Courier New"]. (RGSS2)

size

The font size. The default is 20. (RGSS2)

bold

The bold flag. The default is FALSE.

italic

The italic flag. The default is FALSE.

shadow (RGSS2)

The flag for shadow text. The default is TRUE. When enabled, a black shadow will be drawn to the bottom
right of the character.

color

The font color (Color). Alpha values may also be used. The default is (255,255,255,255).

Alpha values are also used when drawing shadow text. (RGSS2)

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 85 of 172

Class Properties

default_name
default_size
default_bold
default_italic
default_shadow (RGSS2)
default_color

Change the default values for each component, to be applied to each new Font object.

Font.default_name = ["Myriad", "Verdana"]


Font.default_bold = true

Plane
The Plane class. Planes are special sprites that tile bitmap patterns across the entire screen, and are used to
display parallax backgrounds, etc.

Superclass

{ Object

Class Method

Plane.new([viewport])

Creates a Plane object. Specifies a Viewport (Viewport) when necessary.

Methods

dispose

Frees the plane. If the plane has already been freed, does nothing.

disposed?

Returns TRUE if the plane has been freed.

Properties

bitmap

Refers to the bitmap (Bitmap) used in the plane.

viewport (RGSS2)

Refers to the viewport (Viewport) associated with the plane.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 86 of 172

visible

Whether the plane can be seen. If TRUE, the plane is visible.

The plane's Z-coordinate. The larger this value, the closer to the player the plane will be displayed. If multiple
objects share the same Z-coordinate, the more recently created object will be displayed closest to the player.

ox

The X-coordinate of the plane's starting point. Change this value to scroll the plane.

oy

The Y-coordinate of the plane's starting point. Change this value to scroll the plane.

zoom_x

The plane's X-axis zoom level. 1.0 denotes actual pixel size.

zoom_y

The plane's Y-axis zoom level. 1.0 denotes actual pixel size.

opacity

The plane's opacity (0-255). Values out of range are automatically corrected.

blend_type

The plane's blending mode (0: normal, 1: addition, 2: subtraction).

color

The color (Color) to be blended with the plane. Alpha values are used in the blending ratio.

tone

The plane's color tone (Tone).

Rect
The rectangle class.

Superclass

{ Object

Class Method

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 87 of 172

Rect.new(x, y, width, height)

Creates a new Rect object.

Method

set(x, y, width, height)

Sets all parameters at once.

Properties

The X-coordinate of the rectangle's upper left corner.

The Y-coordinate of the rectange's upper left corner.

width

The rectangle's width.

height

The rectangle's height.

Sprite
The sprite class. Sprites are the basic concept used to display characters, etc. on the game screen.

Superclass

{ Object

Class Method

Sprite.new([viewport])

Creates a new Sprite object. Specifies a Viewport (Viewport) when necessary.

Methods

dispose

Frees the sprite. If the sprite has already been freed, does nothing.

disposed?

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 88 of 172

Returns TRUE if the sprite has been freed.

flash(color, duration)

Begins flashing the sprite. duration specifies the number of frames the flash will last.

If color is set to nil, the sprite will disappear while flashing.

update

Advances the sprite flash or wave phase (RGSS2). As a general rule, this method is called once per frame.

If a flash or wave is not needed, it is not necessary to call this.

width (RGSS2)

Gets the width of the sprite. Equivalent to src_rect.width.

height (RGSS2)

Gets the height of the sprite. Equivalent to src_rect.height.

Properties

bitmap

Refers to the bitmap (Bitmap) used for the sprite's starting point.

src_rect

The box (Rect) taken from a bitmap.

viewport (RGSS2)

Refers to the viewport (Viewport) associated with the sprite.

visible

The sprite's visibility. If TRUE, the sprite is visible.

The sprite's X-coordinate.

The sprite's Y-coordinate.

The sprite's Z-coordinate. The larger this value, the closer to the player the sprite will be displayed.

If two sprites have the same Z coordinates, the one with the larger Y coordinate will be displayed closer to

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 89 of 172

the player (RGSS2), and if the Y coordinates are the same, the one that was generated later will be
displayed closer to the player.

ox

The X-coordinate of the sprite's starting point.

oy

The Y-coordinate of the sprite's starting point.

zoom_x

The sprite's X-axis zoom level. 1.0 denotes actual pixel size.

zoom_y

The sprite's Y-axis zoom level. 1.0 denotes actual pixel size.

angle

The sprite's angle of rotation. Specifies up to 360 degrees of counterclockwise rotation. However, drawing a
rotated sprite is time-consuming, so avoid overuse.

wave_amp (RGSS2)
wave_length (RGSS2)
wave_speed (RGSS2)
wave_phase (RGSS2)

Defines the amplitude, frequency, speed, and phase of the wave effect. A raster scroll effect is achieved by
using a sinusoidal function to draw the sprite with each line's horizontal position a bit different from the last.

wave_amp is the wave amplitude and wave_length is the wave frequency, and each is specified by number
of pixels.

wave_speed specifies the speed of the wave animation. The default is 360, and the larger the value, the
faster the effect.

wave_phase specifies the phase of the top line of the sprite using an angle of up to 360 degrees. This is
updated each time the update method is called. It is not necessary to use this property unless it is required
for two sprites to have their wave effects synchronized.

mirror

Flag denoting the sprite has been flipped horizontally. If TRUE, the sprite will be drawn flipped.

bush_depth
bush_opacity (RGSS2)

The bush depth and opacity of a sprite. This can be used to represent something like characters' legs being
hidden by bushes.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 90 of 172

For bush_depth, the number of pixels for the bush section is specified. The default value is 0.

For bush_opacity, the opacity of the bush section from 0 to 255 is specified. Values that are out of range will
automatically be corrected. The default value is 128.

The bush_opacity value will be multiplied by opacity. For example, if both opacity and bush_opacity are set
to 128, it will be handled as transparency on top of transparency, for an actual opacity of 64.

opacity

The sprite's opacity (0-255). Values out of range are automatically corrected.

blend_type

The sprite's blending mode (0: normal, 1: addition, 2: subtraction).

color

The color (Color) to be blended with the sprite. Alpha values are used in the blending ratio.

Handled separately from the color blended into a flash effect. However, the color with the higher alpha value
when displayed will have the higher priority when blended.

tone

The sprite's color tone (Tone).

Table
The multidimensional array class. Each element takes up 2 signed bytes, ranging from -32,768 to 32,767.

Ruby's Array class does not run efficiently when handling large amounts of data, hence the inclusion of this class.

Superclass

{ Object

Class Method

Table.new(xsize[, ysize[, zsize]])

Creates a Table object. Specifies the size of each dimension in the multidimensional array. 1-, 2-, and 3-
dimensional arrays are possible. Arrays with no parameters are also permitted.

Methods

resize(xsize[, ysize[, zsize]])

Change the size of the array. All data from before the size change is retained.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 91 of 172

xsize
ysize
zsize

Gets the sizes of each of the array's dimensions.

Properties

self[x]
self[x, y]
self[x, y, z]

Accesses the array's elements. Pulls the same number of arguments as there are dimensions in the created
array. Returns nil if the specified element does not exist.

Tilemap
The class governing tilemaps. Tilemaps are a specialized concept used in 2D game map displays, created
internally from multiple sprites.

This class has been greatly changed with RGSS2. (RGSS2)

Superclass

{ Object

Class Method

Tilemap.new([viewport])

Creates a Tilemap object. Specifies a Viewport (Viewport) when necessary.

Methods

dispose

Frees the tilemap. If the tilemap has already been freed, does nothing.

disposed?

Returns TRUE if the tilemap has been freed.

update

Updates the autotile animation, etc. As a rule, this method is called once per frame.

Properties

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 92 of 172

bitmaps[index] (RGSS2)

Refers to the bitmap (Bitmap) indicated by the index number (0 - 8) that is used as a tile set.

The correspondence between numbers and sets is illustrated in the table below.。

0 TileA1 1 TileA2 2 TileA3

3 TileA4 4 TileA5 5 TileB

6 TileC 7 TileD 8 TileE

map_data

Refers to map data (Table). Defines a 3-dimensional array measuring [ horizontal size * vertical size * 3 ].

flash_data

Refers to the flash data (Table) used when showing range of possible movement in simulation games, etc.
Defines a 2-dimensional array measuring [ horizontal size * vertical size ]. This array must be the same size
as the map data. Each element uses 4 bits to represent a tile's flash color in RGB; for example, 0xf84 flashes
in RGB(15,8,4).

passages (RGSS2)

Reference to the passage table (Table). Defines a 1-dimensional array containing elements corresponding to
tile IDs.

viewport (RGSS2)

Refers to the viewport (Viewport) associated with the tilemap.

visible

The tilemap's visibility. If TRUE, the tilemap is visible.

ox

The X-coordinate of the tilemap's starting point. Change this value to scroll the tilemap.

oy

The Y-coordinate of the tilemap's starting point. Change this value to scroll the tilemap.

Notes

The Z-coordinate of each sprite used to create a tilemap is fixed at a specific value.

1. A tile that should be displayed under the character has a Z coordinate of 0.


2. A tile that should be displayed over the character has a Z coordinate of 200. (RGSS2)

Keep these rules in mind when setting the Z-coordinates of any map characters.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 93 of 172

Tone
The color tone class. Each component is handled with a floating point value (Float).

Superclass

{ Object

Class Method

Tone.new(red, green, blue[, gray])

Creates a Tone object. If gray is omitted, it is assumed at 0.

Method

set(red, green, blue[, gray])

Sets all components at once.

Properties

red

The red balance adjustment value (-255 to 255). Values out of range are automatically corrected.

green

The green balance adjustment value (-255 to 255). Values out of range are automatically corrected.

blue

The blue balance adjustment value (-255 to 255). Values out of range are automatically corrected.

gray

The grayscale filter strength (0 to 255). Values out of range are automatically corrected.

When this value is not 0, processing time is significantly longer than when using tone balance adjustment
values alone.

Viewport
The viewport class. Used when displaying sprites in one portion of the screen, with no overflow into other regions.

Superclass

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 94 of 172

{ Object

Class Methods

Viewport.new(x, y, width, height)


Viewport.new(rect)

Creates a viewport object.

Methods

dispose

Frees the viewport. If the viewport has already been freed, does nothing.

This operation will not result in a separate associated object being automatically freed. (RGSS2)

disposed?

Returns TRUE if the viewport has been freed.

flash(color, duration)

Begins flashing the viewport. duration specifies the number of frames the flash will last.

If color is set to nil, the viewport will disappear while flashing.

update

Refreshes the viewport flash. As a rule, this method is called once per frame.

It is not necessary to call this method if no flash effect is needed.

Properties

rect

The box (Rect) defining the viewport.

visible

The viewport's visibility. If TRUE, the viewport is visible.

The viewport's Z-coordinate. The larger this value, the closer to the player the plane will be displayed. If
multiple objects share the same Z-coordinate, the more recently created object will be displayed closest to
the player.

ox

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 95 of 172

The X-coordinate of the viewport's starting point. Change this value to shake the screen, etc.

oy

The Y-coordinate of the viewport's starting point. Change this value to shake the screen, etc.

color

The color (Color) to be blended with the viewport. Alpha values are used in the blending ratio.

Handled separately from the color blended into a flash effect.

tone

The viewport's color tone (Tone).

Window
The game window class. Created internally from multiple sprites.

Superclass

{ Object

Class Method

Window.new([viewport])

Creates a Window object. Specifies a Viewport (Viewport) when necessary.

Methods

dispose

Frees the window. If the window has already been freed, does nothing.

disposed?

Returns TRUE if the window has been freed.

update

Refreshes the cursor blink and the pause graphic animation. As a rule, this method is called once per frame.

Properties

windowskin

Refers to the bitmap (Bitmap) used as a windowskin.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 96 of 172

Only RPGVX skins may be used. (RGSS2)

contents

Refers to the bitmap (Bitmap) used for the window's contents.

viewport (RGSS2)

Refers to the (Viewport) associated with the window.

cursor_rect

The cursor box (Rect). Sets the window's upper left corner using relative coordinates (-16, -16).

active

Cursor blink status. If TRUE, the cursor is blinking.

visible

The window's visibility. If TRUE, the window is visible.

pause

The pause graphic's visibility. This is a symbol that appears in the message window when waiting for the
player to press a button. If TRUE, the graphic is visible.

The window's X-coordinate.

The window's Y-coordinate.

width

The window's width.

height

The window's height.

The window's Z-coordinate. The larger this value, the closer to the player the plane will be displayed. If
multiple objects share the same Z-coordinate, the more recently created object will be displayed closest to
the player.

It is no longer possible to use different Z coordinates for the window's background and its contents. (RGSS2)

ox

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 97 of 172

The X-coordinate of the starting point of the window's contents. Change this value to scroll the window's
contents.

oy

The Y-coordinate of the starting point of the window's contents. Change this value to scroll the window's
contents.

opacity

The window's opacity (0-255). Values out of range are automatically corrected.

back_opacity

The window background's opacity (0-255). Values out of range are automatically corrected.

contents_opacity

The opacity of the window's contents (0-255). Values out of range are automatically corrected.

openness (RGSS2)

The openness of the window (from 0 to 255). Values out of range are automatically corrected.

By changing this value from 0 (completely closed) to 255 (completely open), it is possible to create an
animation of the window opening and closing. If the openness is less than 255, the contents of the window
will not be displayed. The default value is 255.

RGSSError
Exception class providing notifications of RGSS internal errors.

Generated when, for instance, trying to access Bitmap or Sprite class objects that have already been freed.

Superclass

{ StandardError

RGSS Built-in Modules


{ Audio
{ Graphics
{ Input
{ RPG

Audio
The module that carries out music and sound processing.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 98 of 172

Module Methods

Audio.bgm_play(filename[, volume[, pitch]])

Starts BGM playback. Sets the file name, volume, and pitch in turn.

Also automatically searches files included in RGSS-RTP. File extensions may be omitted.

Audio.bgm_stop

Stops BGM playback.

Audio.bgm_fade(time)

Starts BGM fadeout. time is the length of the fadeout in milliseconds.

Audio.bgs_play(filename[, volume[, pitch]])

Starts BGS playback. Sets the file name, volume, and pitch in turn.

Also automatically searches files included in RGSS-RTP. File extensions may be omitted.

Audio.bgs_stop

Stops BGS playback.

Audio.bgs_fade(time)

Starts BGS fadeout. time is the length of the fadeout in milliseconds.

Audio.me_play(filename[, volume[, pitch]])

Starts ME playback. Sets the file name, volume, and pitch in turn.

Also automatically searches files included in RGSS-RTP. File extensions may be omitted.

When ME is playing, the BGM will temporarily stop. The timing of when the BGM restarts is slightly different
from RGSS1. (RGSS2)

Audio.me_stop

Stops ME playback.

Audio.me_fade(time)

Starts ME fadeout. time is the length of the fadeout in milliseconds.

Audio.se_play(filename[, volume[, pitch]])

Starts SE playback. Sets the file name, volume, and pitch in turn.

Also automatically searches files included in RGSS-RTP. File extensions may be omitted.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 99 of 172

When attempting to play the same SE more than once in a very short period, they will automatically be
filtered to prevent choppy playback.

Audio.se_stop

Stops SE playback.

Graphics
The module that carries out graphics processing.

Module Methods

Graphics.update

Refreshes the game screen and advances time by 1 frame. This method must be called at set intervals.

loop do
Graphics.update
Input.update
do_something
end

With RGSS1, if this method was not called for more than 10 seconds, the script was judged to be out of
control and was automatically shut down, but this has been done away with. Even if this method is not called
for a long period of time, Windows messages will still be processed normally, and it is possible to force quit
using Alt + F4 as usual.(RGSS2)

Graphics.wait(duration) (RGSS2)

Waits for the specified number of frames. Equivalent to the following.

duration.times do
Graphics.update
end

Graphics.fadeout(duration) (RGSS2)

Performs a fade-out of the screen.

duration is the number of frames to spend on the fade-out.

Graphics.fadein(duration) (RGSS2)

Performs a fade-in of the screen.

duration is the number of frames to spend on the fade-in.

Graphics.freeze

Fixes the current screen in preparation for transitions.

Screen rewrites are prohibited until the transition method is called.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 100 of 172

Graphics.transition([duration[, filename[, vague]]])

Carries out a transition from the screen fixed in Graphics.freeze to the current screen.

duration is the number of frames the transition will last. When omitted, this value is set to 8.

filename specifies the transition graphic file name. When not specified, a standard fade will be used. Also
automatically searches files included in RGSS-RTP and encrypted archives. File extensions may be omitted.

vague sets the ambiguity of the borderline between the graphic's starting and ending points. The larger the
value, the greater the ambiguity. When omitted, this value is set to 40.

Graphics.snap_to_bitmap (RGSS2)

Gets the current game screen image as a bitmap object.

This reflects the graphics that should be displayed, without relation to use of the freeze method.

The created bitmap must be freed when it is no longer needed.

Graphics.frame_reset

Resets the screen refresh timing. After a time-consuming process, call this method to prevent extreme frame
skips.

Graphics.width (RGSS2)
Graphics.height (RGSS2)

Gets the width and height of the game screen.

These are normally 544 and 416.

Graphics.resize_screen(width, height) (RGSS2)

Changes the size of the game screen.

Specify a value up to 640×480 for width and height.

Module Properties

Graphics.frame_rate

The number of times the screen is refreshed per second. The larger the value, the more CPU power is
required. Normally set at 60. (RGSS2)

Changing this property is not recommended; however, it can be set anywhere from 10 to 120. Values out of
range are automatically corrected.

Graphics.frame_count

The screen's refresh rate count. Set this property to 0 at game start and the game play time (in seconds) can
be calculated by dividing this value by the frame_rate property value.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 101 of 172

Graphics.brightness (RGSS2)

The brightness of the screen. Takes a value from 0 to 255. The fadeout, fadein, and transition methods
change this value internally, as required.

Input
A module that handles input data from a gamepad or keyboard.

Module Methods

Input.update

Updates input data. As a rule, this method is called once per frame.

Input.press?(num)

Determines whether the button num is currently being pressed.

If the button is being pressed, returns TRUE. If not, returns FALSE.

if Input.press?(Input::C)
do_something
end

Input.trigger?(num)

Determines whether the button num is being pressed again.

"Pressed again" is seen as time having passed between the button being not pressed and being pressed.

If the button is being pressed, returns TRUE. If not, returns FALSE.

Input.repeat?(num)

Determines whether the button num is being pressed again.

Unlike trigger?, takes into account the repeat input of a button being held down continuously.

If the button is being pressed, returns TRUE. If not, returns FALSE.

Input.dir4

Checks the status of the directional buttons, translates the data into a specialized 4-direction input format,
and returns the number pad equivalent (2, 4, 6, 8).

If no directional buttons are being pressed (or the equivalent), returns 0.

Input.dir8

Checks the status of the directional buttons, translates the data into a specialized 8-direction input format,
and returns the number pad equivalent (1, 2, 3, 4, 6, 7, 8, 9).

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 102 of 172

If no directional buttons are being pressed (or the equivalent), returns 0.

Constants

DOWN LEFT RIGHT UP

Numbers corresponding to the directions down, left, right, and up.

ABCXYZLR

Numbers corresponding to the various controller buttons.

SHIFT CTRL ALT

Numbers directly corresponding to the keyboard's SHIFT, CTRL, and ALT keys.

F5 F6 F7 F8 F9

Numbers corresponding to the keyboard's function keys. The other function keys are reserved by the system
and cannot be obtained.

RPG
A module containing RPGVX Data Structures.

RPGVX Data Structures


{ RPG::Map
{ RPG::MapInfo
{ RPG::Area
{ RPG::Event
{ RPG::Event::Page
{ RPG::Event::Page::Condition
{ RPG::Event::Page::Graphic
{ RPG::EventCommand
{ RPG::MoveRoute
{ RPG::MoveCommand
{ RPG::Actor
{ RPG::Class
{ RPG::Class::Learning
{ RPG::BaseItem
„ RPG::UsableItem
„ RPG::Skill
„ RPG::Item
„ RPG::EquippableItem
„ RPG::Weapon
„ RPG::Armor
{ RPG::Enemy

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 103 of 172

{ RPG::Enemy::DropItem
{ RPG::Enemy::Action
{ RPG::Troop
{ RPG::Troop::Member
{ RPG::Troop::Page
{ RPG::Troop::Page::Condition
{ RPG::State
{ RPG::Animation
{ RPG::Animation::Frame
{ RPG::Animation::Timing
{ RPG::CommonEvent
{ RPG::System
{ RPG::System::Vehicle
{ RPG::System::Terms
{ RPG::System::TestBattler
{ RPG::AudioFile
„ RPG::BGM
„ RPG::BGS
„ RPG::ME
„ RPG::SE

RPG::Map
Data class for maps.

Superclass

{ Object

Attributes

width

The map width.

height

The map height.

scroll_type

Scroll type (0: No Loop, 1: Vertical Loop, 2: Horizontal Loop, 3: Both Loop).

autoplay_bgm

Truth-value of whether BGM autoswitching is enabled.

bgm

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 104 of 172

If BGM autoswitching is enabled, the name of that BGM (RPG::AudioFile).

autoplay_bgs

Truth-value of whether BGS autoswitching is enabled.

bgs

If BGS autoswitching is enabled, the name of that BGS (RPG::AudioFile).

disable_dashing

Truth-value of the [Disable Dashing] option.

encounter_list

Encounter list. A troop ID array.

encounter_step

Number of steps between encounters.

parallax_name

The parallax background's graphic file name.

parallax_loop_x

Truth-value of the [Loop Horizontal] option.

parallax_loop_y

Truth-value of the [Loop Vertical] option.

parallax_sx

The automatic X-axis scrolling speed.

parallax_sy

The automatic Y-axis scrolling speed.

parallax_show

Truth-value of the [Show in the Editor] option.

data

The map data. A 3-dimensional tile ID array (Table).

events

Map events. A hash that represents RPG::Event instances as values, using event IDs as the keys.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 105 of 172

Definition
module RPG
class Map
def initialize(width, height)
@width = width
@height = height
@scroll_type = 0
@autoplay_bgm = false
@bgm = RPG::AudioFile.new
@autoplay_bgs = false
@bgs = RPG::AudioFile.new("", 80)
@disable_dashing = false
@encounter_list = []
@encounter_step = 30
@parallax_name = ""
@parallax_loop_x = false
@parallax_loop_y = false
@parallax_sx = 0
@parallax_sy = 0
@parallax_show = false
@data = Table.new(width, height, 3)
@events = {}
end
attr_accessor :width
attr_accessor :height
attr_accessor :scroll_type
attr_accessor :autoplay_bgm
attr_accessor :bgm
attr_accessor :autoplay_bgs
attr_accessor :bgs
attr_accessor :disable_dashing
attr_accessor :encounter_list
attr_accessor :encounter_step
attr_accessor :parallax_name
attr_accessor :parallax_loop_x
attr_accessor :parallax_loop_y
attr_accessor :parallax_sx
attr_accessor :parallax_sy
attr_accessor :parallax_show
attr_accessor :data
attr_accessor :events
end
end

RPG::MapInfo
Data class for map information.

Superclass

{ Object

Attributes

name

The map name.

parent_id

The parent map ID.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 106 of 172

order

The map tree display order, used internally.

expanded

The map tree expansion flag, used internally.

scroll_x

The X-axis scroll position, used internally.

scroll_y

The Y-axis scroll position, used internally.

Definition
module RPG
class MapInfo
def initialize
@name = ""
@parent_id = 0
@order = 0
@expanded = false
@scroll_x = 0
@scroll_y = 0
end
attr_accessor :name
attr_accessor :parent_id
attr_accessor :order
attr_accessor :expanded
attr_accessor :scroll_x
attr_accessor :scroll_y
end
end

RPG::Area
Data class for areas.

Superclass

{ Object

Attributes

id

The area ID.

name

The area name.

map_id

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 107 of 172

The parent map ID.

rect

The area position (Rect) .

encounter_list

Encounter list. A troop ID array.

order

The map tree display order, used internally.

Definition
module RPG
class Area

def initialize
@id = 0
@name = ""
@map_id = 0
@rect = Rect.new(0,0,0,0)
@encounter_list = []
@order = 0
end
attr_accessor :id
attr_accessor :name
attr_accessor :map_id
attr_accessor :rect
attr_accessor :encounter_list
attr_accessor :order
end
end

RPG::Event
Data class for map events.

Superclass

{ Object

Referrer

{ RPG::Map

Attributes

id

The event ID.

name

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 108 of 172

The event name.

The event's X-coordinate on the map.

The event's Y-coordinate on the map.

pages

The Events pages. An RPG::Event::Page array.

Inner Class

{ RPG::Event::Page

Definition
module RPG
class Event
def initialize(x, y)
@id = 0
@name = ""
@x = x
@y = y
@pages = [RPG::Event::Page.new]
end
attr_accessor :id
attr_accessor :name
attr_accessor :x
attr_accessor :y
attr_accessor :pages
end
end

RPG::Event::Page
Data class for the event page.

Superclass

{ Object

Referrer

{ RPG::Event

Attributes

condition

The event condition (RPG::Event::Page::Condition).

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 109 of 172

graphic

The event graphic (RPG::Event::Page::Graphic).

move_type

Type of movement (0: fixed, 1: random, 2: approach, 3: custom).

move_speed

Movement speed (1: x8 slower, 2: x4 slower, 3: x2 slower, 4: normal, 5: x2 faster, 6: x4 faster).

move_frequency

Movement frequency (1: lowest, 2: lower, 3: normal, 4: higher, 5: highest).

move_route

Movement route (RPG::MoveRoute). Referenced only when the movement type is set to Custom.

walk_anime

Truth value of the [Walking Anim.] option.

step_anime

Truth value of the [Stepping Anim.] option.

direction_fix

Truth value of the [Direction Fix] option.

through

Truth value of the [Through] option.

priority_type

Priority type (0: below characters, 1: same as characters, 2: above characters).

trigger

Event trigger (0: action button, 1: player touch, 2: event touch, 3: autorun, 4: parallel process).

list

List of event commands. An RPG::EventCommand array.

Inner Classes

{ RPG::Event::Page::Condition
{ RPG::Event::Page::Graphic

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 110 of 172

Definition
module RPG
class Event
class Page
def initialize
@condition = RPG::Event::Page::Condition.new
@graphic = RPG::Event::Page::Graphic.new
@move_type = 0
@move_speed = 3
@move_frequency = 3
@move_route = RPG::MoveRoute.new
@walk_anime = true
@step_anime = false
@direction_fix = false
@through = false
@priority_type = 0
@trigger = 0
@list = [RPG::EventCommand.new]
end
attr_accessor :condition
attr_accessor :graphic
attr_accessor :move_type
attr_accessor :move_speed
attr_accessor :move_frequency
attr_accessor :move_route
attr_accessor :walk_anime
attr_accessor :step_anime
attr_accessor :direction_fix
attr_accessor :through
attr_accessor :priority_type
attr_accessor :trigger
attr_accessor :list
end
end
end

RPG::Event::Page::Condition
Data class for the event page conditions.

Superclass

{ Object

Referrer

{ RPG::Event::Page

Attributes

switch1_valid

Truth value for whether the first [Switch] condition is valid.

switch2_valid

Truth value for whether the second [Switch] condition is valid.

variable_valid

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 111 of 172

Truth value for whether the [Variable] condition is valid.

self_switch_valid

Truth value for whether the [Self Switch] condition is valid.

item_valid

Truth value for whether the [Item] condition is valid.

actor_valid

Truth value for whether the [Actor] condition is valid.

switch1_id

If the first [Switch] condition is valid, the ID of that switch.

switch2_id

If the second [Switch] condition is valid, the ID of that switch.

variable_id

If the [Variable] condition is valid, the ID of that variable.

variable_value

If the [Variable] condition is valid, the standard value of that variable (x and greater).

self_switch_ch

If the [Self Switch] condition is valid, the letter of that self switch ("A".."D").

item_id

If the [Item] condition is valid, the ID of that item.

actor_id

If the [Actor] condition is valid, the ID of that actor.

Definition
module RPG
class Event
class Page
class Condition
def initialize
@switch1_valid = false
@switch2_valid = false
@variable_valid = false
@self_switch_valid = false
@item_valid = false
@actor_valid = false
@switch1_id = 1
@switch2_id = 1

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 112 of 172

@variable_id = 1
@variable_value = 0
@self_switch_ch = "A"
@item_id = 1
@actor_id = 1
end
attr_accessor :switch1_valid
attr_accessor :switch2_valid
attr_accessor :variable_valid
attr_accessor :self_switch_valid
attr_accessor :item_valid
attr_accessor :actor_valid
attr_accessor :switch1_id
attr_accessor :switch2_id
attr_accessor :variable_id
attr_accessor :variable_value
attr_accessor :self_switch_ch
attr_accessor :item_id
attr_accessor :actor_id
end
end
end
end

RPG::Event::Page::Graphic
Data class for the Event page [Graphics].

Superclass

{ Object

Referrer

{ RPG::Event::Page

Attributes

tile_id

The tile ID. If the specified graphic is not a tile, this value is 0.

character_name

The character's graphic file name.

character_index

The character's index of the graphic file (0..7).

direction

The direction in which the character is facing (2: down, 4: left, 6: right, 8: up).

pattern

The character's pattern (0..2).

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 113 of 172

Definition
module RPG
class Event
class Page
class Graphic
def initialize
@tile_id = 0
@character_name = ""
@character_index = 0
@direction = 2
@pattern = 0
end
attr_accessor :tile_id
attr_accessor :character_name
attr_accessor :character_index
attr_accessor :direction
attr_accessor :pattern
end
end
end
end

RPG::EventCommand
Data class for the Event command.

Superclass

{ Object

Referrers

{ RPG::Event::Page
{ RPG::Troop::Page
{ RPG::CommonEvent

Attributes

code

The event code.

indent

The indent depth. Usually 0; the [Conditional Branch] command, among others, adds 1 with every step
deeper.

parameters

Array containing the Move command arguments. The contents vary for each command.

Definition
module RPG

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 114 of 172

class EventCommand
def initialize(code = 0, indent = 0, parameters = [])
@code = code
@indent = indent
@parameters = parameters
end
attr_accessor :code
attr_accessor :indent
attr_accessor :parameters
end
end

RPG::MoveRoute
Data class for the Move route.

Superclass

{ Object

Referrer

{ RPG::EventPage

Attributes

repeat

Truth value of the [Repeat Action] option.

skippable

Truth value of the [Skip If Cannot Move] option.

wait

Truth value of the [Wait for Completion] option.

list

Program contents. An RPG::MoveCommand array.

Definition
module RPG
class MoveRoute
def initialize
@repeat = true
@skippable = false
@wait = false
@list = [RPG::MoveCommand.new]
end
attr_accessor :repeat
attr_accessor :skippable
attr_accessor :wait
attr_accessor :list
end

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 115 of 172

end

RPG::MoveCommand
Data class for the Move command.

Superclass

{ Object

Referrer

{ RPG::MoveRoute

Attributes

code

Move command code.

parameters

Array containing the Move command arguments. The contents vary for each command.

Definition
module RPG
class MoveCommand(code = 0, parameters = [])
def initialize
@code = code
@parameters = parameters
end
attr_accessor :code
attr_accessor :parameters
end
end

RPG::Actor
Data class for actors.

Superclass

{ Object

Attributes

id

The actor ID.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 116 of 172

name

The actor name.

class_id

The actor class ID.

initial_level

The actor's initial level.

exp_basis

The value on which the experience curve is based (10..40).

exp_inflation

The amount of experience curve inflation (20..50).

character_name

The actor's character graphic file name.

character_index

The actor's character index of the graphic file (0..7).

face_name

The actor's face graphic file name.

face_index

The actor's face index of the graphic file (0..7).

parameters

2-dimensional array containing base parameters for each level (Table).

Generally takes the form parameters[kind, level].

kind indicates the parameter type (0: MaxHP, 1: MaxMP, 2: Attack, 3: Defense, 4: Spirit, 5: Agility).

weapon_id

ID of the actor's initially equipped weapon.

armor1_id

ID of the actor's initially equipped shield.

armor2_id

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 117 of 172

ID of the actor's initially equipped helmet.

armor3_id

ID of the actor's initially equipped body armor.

armor4_id

ID of the actor's initially equipped accessory.

two_swords_style

Truth value of the [Two Swords Style] option.

fix_equipment

Truth value of the [Fix Equipment] option.

auto_battle

Truth value of the [Auto Battle] option.

super_guard

Truth value of the [Super Guard] option.

pharmacology

Truth value of the [Pharmacology] option.

critical_bonus

Truth value of the [Critical Bonus] option.

Definition
module RPG
class Actor
def initialize
@id = 0
@name = ""
@class_id = 1
@initial_level = 1
@exp_basis = 25
@exp_inflation = 35
@character_name = ""
@character_index = 0
@face_name = ""
@face_index = 0
@parameters = Table.new(6,100)
for i in 1..99
@parameters[0,i] = 400+i*50
@parameters[1,i] = 80+i*10
@parameters[2,i] = 15+i*5/4
@parameters[3,i] = 15+i*5/4
@parameters[4,i] = 20+i*5/2
@parameters[5,i] = 20+i*5/2
end
@weapon_id = 0
@armor1_id = 0

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 118 of 172

@armor2_id = 0
@armor3_id = 0
@armor4_id = 0
@two_swords_style = false
@fix_equipment = false
@auto_battle = false
@super_guard = false
@pharmacology = false
@critical_bonus = false
end
attr_accessor :id
attr_accessor :name
attr_accessor :class_id
attr_accessor :initial_level
attr_accessor :exp_basis
attr_accessor :exp_inflation
attr_accessor :character_name
attr_accessor :character_index
attr_accessor :face_name
attr_accessor :face_index
attr_accessor :parameters
attr_accessor :weapon_id
attr_accessor :armor1_id
attr_accessor :armor2_id
attr_accessor :armor3_id
attr_accessor :armor4_id
attr_accessor :two_swords_style
attr_accessor :fix_equipment
attr_accessor :auto_battle
attr_accessor :super_guard
attr_accessor :pharmacology
attr_accessor :critical_bonus
end
end

RPG::Class
Data class for class.

Superclass

{ Object

Attributes

id

The class's ID.

name

The class name.

position

The class position (0: front, 1: middle, 2: rear).

weapon_set

Array containing IDs for equippable weapons.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 119 of 172

armor_set

Array containing IDs for equippable armor.

element_ranks

Level of elements efficiency. 1-dimensional array using element IDs as subscripts (Table), with 6 levels (0: A,
1: B, 2: C, 3: D, 4: E, 5: F).

state_ranks

Level of states efficiency. 1-dimensional array using status IDs as subscripts (Table), with 6 levels (0: A, 1:
B, 2: C, 3: D, 4: E, 5: F).

learnings

Skills to learn. An RPG::Class::Learning array.

skill_name_valid

Truth value for whether the skill name is valid.

skill_name

Name of the skill command.

Inner Class

{ RPG::Class::Learning

Definition
module RPG
class Class
def initialize
@id = 0
@name = ""
@position = 0
@weapon_set = []
@armor_set = []
@element_ranks = Table.new(1)
@state_ranks = Table.new(1)
@learnings = []
@skill_name_valid = false
@skill_name = ""
end
attr_accessor :id
attr_accessor :name
attr_accessor :position
attr_accessor :weapon_set
attr_accessor :armor_set
attr_accessor :element_ranks
attr_accessor :state_ranks
attr_accessor :learnings
attr_accessor :skill_name_valid
attr_accessor :skill_name
end
end

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 120 of 172

RPG::Class::Learning
Data class for a [Class's Learned] skills.

Superclass

{ Object

Referrer

{ RPG::Class

Attributes

level

Skill level.

skill_id

The learned skill's ID.

Definition
module RPG
class Class
class Learning
def initialize
@level = 1
@skill_id = 1
end
attr_accessor :level
attr_accessor :skill_id
end
end
end

RPG::BaseItem
Superclass of Skill, Item, Weapon, and Armor.

Superclass

{ Object

Attributes

id

The item ID.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 121 of 172

name

The item name.

icon_index

The icon number.

description

The description text.

note

The text of the note.

Definition
module RPG
class Item
def initialize
@id = 0
@name = ""
@icon_index = 0
@description = ""
@note = ""
end
attr_accessor :id
attr_accessor :name
attr_accessor :icon_index
attr_accessor :description
attr_accessor :note
end
end

RPG::UsableItem
Superclass of Skill and Item.

Superclass

{ RPG::BaseItem

Attributes

scope

Scope of the effects.

0: None
1: One Enemy
2: All Enemies
3: One Enemy Dual
4: One Random Enemy

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 122 of 172

5: 2 Random Enemies
6: 3 Random Enemies
7: One Ally
8: All Allies
9: One Ally (Dead)
10: All Allies (Dead)
11: The User
occasion

When the item/skill may be used.

0: Always
1: Only in Battle
2: Only from the Menu
3: Never
speed

The speed correction.

animation_id

The animation ID.

common_event_id

The Common Event ID.

base_damage

The base damage.

variance

The degree of variance.

atk_f

The factor of attack power.

spi_f

The factor of spirit.

physical_attack

Truth value of the [Physical Attack] option.

damage_to_mp

Truth value of the [Damage to MP] option.

absorb_damage

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 123 of 172

Truth value of the [Absorb Damage] option.

ignore_defense

Truth value of the [Ignore Defense] option.

element_set

Elements of the item. An Element ID array.

plus_state_set

States to add. A State ID array.

minus_state_set

States to cancel. A Stae ID array.

Methods

for_opponent?

Determines whether or not the area of effect is enemies. Returns true if the value of scope is 1, 2, 3, 4, 5, or
6.

for_friend?

Determines whether or not the area of effect is allies. Returns true if the value of scope is 7, 8, 9, 10, or 11.

for_dead_friend?

Determines whether or not the area of effect is downed allies. Returns true if the value of scope is 9 or 10.

for_user?

Determines whether or not the area of effect is the user. Returns true if the value of scope is 11.

for_one?

Determines whether or not the area of effect is one character. Returns true if the value of scope is 1, 3, 4, 7,
9, or 11.

for_two?

Determines whether or not the area of effect is two characters. Returns true if the value of scope is 5.

for_three?

Determines whether or not the area of effect is three characters. Returns true if the value of scope is 6.

for_random?

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 124 of 172

Determines whether or not the area of effect is random. Returns true if the value of scope is 4, 5, or 6.

for_all?

Determines whether or not the area of effect is everyone. Returns true if the value of scope is 2, 8, or 10.

dual?

Determines whether or not the area of effect is "One Enemy Dual." Returns true if the value of scope is 3.

need_selection?

Determines whether or not selection of the target is required. Returns true if the value of scope is 1, 3, 7, or
9.

battle_ok?

Determines if it may be used on the battle screen. Returns true if the value of occasion is 0 or 1.

menu_ok?

Determines if it may be used on the menu screen. Returns true if the value of occasion is 0 or 2.

Definition
module RPG
class UsableItem < BaseItem
def initialize
super
@scope = 0
@occasion = 0
@speed = 0
@animation_id = 0
@common_event_id = 0
@base_damage = 0
@variance = 20
@atk_f = 0
@spi_f = 0
@physical_attack = false
@damage_to_mp = false
@absorb_damage = false
@ignore_defense = false
@element_set = []
@plus_state_set = []
@minus_state_set = []
end
def for_opponent?
return [1, 2, 3, 4, 5, 6].include?(@scope)
end
def for_friend?
return [7, 8, 9, 10, 11].include?(@scope)
end
def for_dead_friend?
return [9, 10].include?(@scope)
end
def for_user?
return [11].include?(@scope)
end
def for_one?
return [1, 3, 4, 7, 9, 11].include?(@scope)
end
def for_two?
return [5].include?(@scope)
end

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 125 of 172

def for_three?
return [6].include?(@scope)
end
def for_random?
return [4, 5, 6].include?(@scope)
end
def for_all?
return [2, 8, 10].include?(@scope)
end
def dual?
return [3].include?(@scope)
end
def need_selection?
return [1, 3, 7, 9].include?(@scope)
end
def battle_ok?
return [0, 1].include?(@occasion)
end
def menu_ok?
return [0, 2].include?(@occasion)
end
attr_accessor :scope
attr_accessor :occasion
attr_accessor :speed
attr_accessor :animation_id
attr_accessor :common_event_id
attr_accessor :base_damage
attr_accessor :variance
attr_accessor :atk_f
attr_accessor :spi_f
attr_accessor :physical_attack
attr_accessor :damage_to_mp
attr_accessor :absorb_damage
attr_accessor :ignore_defense
attr_accessor :element_set
attr_accessor :plus_state_set
attr_accessor :minus_state_set
end
end

RPG::Skill
Data class for skills.

Superclass

{ RPG::UsableItem

Attributes

mp_cost

Number of MP consumed.

hit

The skill's hit ratio.

message1
message2

The use message.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 126 of 172

Definition
module RPG
class Skill < UsableItem
def initialize
super
@scope = 1
@mp_cost = 0
@hit = 100
@message1 = ""
@message2 = ""
end
attr_accessor :mp_cost
attr_accessor :hit
attr_accessor :message1
attr_accessor :message2
end
end

RPG::Item
Data class for items.

Superclass

{ RPG::UsableItem

Attributes

price

The item price.

consumable

Truth value of whether the item disappears when used.

hp_recovery_rate

HP recovery rate.

hp_recovery

HP recovery amount.

mp_recovery_rate

MP recovery rate.

mp_recovery

MP recovery amount.

parameter_type

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 127 of 172

Parameter affected (0: None, 1: MaxHP, 2: MaxMP, 3: Attack, 4: Defense, 5: Spirit, 6: Agility).

parameter_points

Amount by which parameter increases.

Definition
module RPG
class Item < UsableItem
def initialize
super
@scope = 7
@price = 0
@consumable = true
@hp_recovery_rate = 0
@hp_recovery = 0
@mp_recovery_rate = 0
@mp_recovery = 0
@parameter_type = 0
@parameter_points = 0
end
attr_accessor :price
attr_accessor :consumable
attr_accessor :hp_recovery_rate
attr_accessor :hp_recovery
attr_accessor :mp_recovery_rate
attr_accessor :mp_recovery
attr_accessor :parameter_type
attr_accessor :parameter_points
end
end

RPG::Weapon
Data class for weapons.

Superclass

{ RPG::BaseItem

Attributes

animation_id

The animation ID when using the weapon.

price

The weapon's price.

hit

The weapon's hit ratio.

atk

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 128 of 172

The weapon's attack power.

def

The weapon's defense power.

spi

The weapon's spirit power.

agi

The weapon's agility power.

two_handed

Truth value of the [Two Handed] option.

fast_attack

Truth value of the [Fast Attack] option.

dual_attack

Truth value of the [Dual Attack] option.

critical_bonus

Truth value of the [Critical Bonus] option.

element_set

Elements of the weapon. An element ID array.

state_set

States to add. A state ID array.

Definition
module RPG
class Weapon < BaseItem
def initialize
super
@animation_id = 0
@price = 0
@hit = 95
@atk = 0
@def = 0
@spi = 0
@agi = 0
@two_handed = false
@fast_attack = false
@dual_attack = false
@critical_bonus = false
@element_set = []
@state_set = []
end

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 129 of 172

attr_accessor :animation_id
attr_accessor :price
attr_accessor :hit
attr_accessor :atk
attr_accessor :def
attr_accessor :spi
attr_accessor :agi
attr_accessor :two_handed
attr_accessor :fast_attack
attr_accessor :dual_attack
attr_accessor :critical_bonus
attr_accessor :element_set
attr_accessor :state_set
end
end

RPG::Armor
Data class for armor.

Superclass

{ RPG::BaseItem

Attributes

kind

Type of armor (0: shield, 1: helmet, 2: body armor, 3: accessory).

price

The armor's price.

eva

The armor's evasion rate.

atk

The armor's attack power.

def

The armor's defense power.

spi

The armor's spirit power.

agi

The armor's agility power.

prevent_critical

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 130 of 172

Truth value of the [Prevent Critical] option.

half_mp_cost

Truth value of the [Half MP Cost] option.

double_exp_gain

Truth value of the [Double EXP Gain] option.

auto_hp_recover

Truth value of the [Auto HP Recover] option.

element_set

Elements to guard. An element ID array.

state_set

States to resist. A state ID array.

Definition
module RPG
class Armor < BaseItem
def initialize
super
@kind = 0
@price = 0
@eva = 0
@atk = 0
@def = 0
@spi = 0
@agi = 0
@prevent_critical = false
@half_mp_cost = false
@double_exp_gain = false
@auto_hp_recover = false
@element_set = []
@state_set = []
end
attr_accessor :kind
attr_accessor :price
attr_accessor :eva
attr_accessor :atk
attr_accessor :def
attr_accessor :spi
attr_accessor :agi
attr_accessor :prevent_critical
attr_accessor :half_mp_cost
attr_accessor :double_exp_gain
attr_accessor :auto_hp_recover
attr_accessor :element_set
attr_accessor :state_set
end
end

RPG::Enemy
Data class for enemies.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 131 of 172

Superclass

{ Object

Attributes

id

The enemy ID.

name

The enemy name.

battler_name

The enemy's battler graphic file name.

battler_hue

The adjustment value for the battler graphic's hue (0..360).

maxhp

The enemy's MaxHP.

maxmp

The enemy's MaxMP.

atk

The enemy's attack power.

def

The enemy's defense power.

spi

The enemy's spirit.

agi

The enemy's agility.

hit

The enemy's hit ratio.

eva

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 132 of 172

The enemy's evasion rate.

exp

The enemy's experience.

gold

The enemy's gold.

drop_item1

The drop item 1 (RPG::Enemy::DropItem) 。

drop_item2

The drop item 2 (RPG::Enemy::DropItem) 。

levitate

Truth value of the [Levitate] option.

has_critical

Truth value of the [Has Critical] option.

element_ranks

Level of elements efficiency. 1-dimensional array using element IDs as subscripts (Table), with 6 levels (0: A,
1: B, 2: C, 3: D, 4: E, 5: F).

state_ranks

Level of states efficiency. 1-dimensional array using status IDs as subscripts (Table), with 6 levels (0: A, 1:
B, 2: C, 3: D, 4: E, 5: F).

actions

Actions petterns. An RPG::Enemy::Action array.

note

The text of the note.

Inner Class

{ RPG::Enemy::DropItem
{ RPG::Enemy::Action

Definition
module RPG

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 133 of 172

class Enemy
def initialize
@id = 0
@name = ""
@battler_name = ""
@battler_hue = 0
@maxhp = 10
@maxmp = 10
@atk = 10
@def = 10
@spi = 10
@agi = 10
@hit = 95
@eva = 5
@exp = 0
@gold = 0
@drop_item1 = RPG::Enemy::DropItem.new
@drop_item2 = RPG::Enemy::DropItem.new
@levitate = false
@has_critical = false
@element_ranks = Table.new(1)
@state_ranks = Table.new(1)
@actions = [RPG::Enemy::Action.new]
@note = ""
end
attr_accessor :id
attr_accessor :name
attr_accessor :battler_name
attr_accessor :battler_hue
attr_accessor :maxhp
attr_accessor :maxmp
attr_accessor :atk
attr_accessor :def
attr_accessor :spi
attr_accessor :agi
attr_accessor :hit
attr_accessor :eva
attr_accessor :exp
attr_accessor :gold
attr_accessor :drop_item1
attr_accessor :drop_item2
attr_accessor :levitate
attr_accessor :has_critical
attr_accessor :element_ranks
attr_accessor :state_ranks
attr_accessor :actions
attr_accessor :note
end
end

RPG::Enemy::DropItem
Data class for enemy [Drop Item].

Superclass

{ Object

Referrer

{ RPG::Enemy

Attributes

kind

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 134 of 172

Type of the drop item (0: none, 1: item, 2: weapon, 3: armor).

item_id

The item ID, when kind == 1.

weapon_id

The weapon ID, when kind == 2.

armor_id

The armor ID, when kind == 3.

denominator

N of the probability 1/N.

Definition
module RPG
class Enemy
class DropItem
def initialize
@kind = 0
@item_id = 1
@weapon_id = 1
@armor_id = 1
@denominator = 1
end
attr_accessor :kind
attr_accessor :item_id
attr_accessor :weapon_id
attr_accessor :armor_id
attr_accessor :denominator
end
end
end

RPG::Enemy::Action
Data class for enemy [Actions].

Superclass

{ Object

Referrer

{ RPG::Enemy

Attributes

kind

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 135 of 172

Type of action.

0: Basic
1: Skill
basic

When set to a [Basic] action, defines it further.

0: Attack
1: Guard
2: Escape
3: Do Nothing
skill_id

When set to a [Skill], the ID of that skill.

condition_type

The type of condition.

0: Always
1: Turn No.
2: HP
3: MP
4: State
5: Party Level
6: Switch
condition_param1
condition_param2

A condition parameter. Shared by all types.

For example, if the condition is [HP], then condition_param1 will be the minimum value and
condition_param2 will be the maximum value.

rating

The action's rating (1..10).

Methods

skill?

Determines if kind is skill or not. Returns true if kind is 1.

Definition
module RPG
class Enemy
class Action
def initialize
@kind = 0

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 136 of 172

@basic = 0
@skill_id = 1
@condition_type = 0
@condition_param1 = 0
@condition_param2 = 0
@rating = 5
end
def skill?
return @kind == 1
end
attr_accessor :kind
attr_accessor :basic
attr_accessor :skill_id
attr_accessor :condition_type
attr_accessor :condition_param1
attr_accessor :condition_param2
attr_accessor :rating
end
end
end

RPG::Troop
Data class for troops.

Superclass

{ Object

Attributes

id

Troop ID.

name

Troop name.

members

Troop members. An RPG::Troop::Member array.

pages

Battle events. An RPG::Troop::Page array.

Inner Classes

{ RPG::Troop::Member
{ RPG::Troop::Page

Definition
module RPG
class Troop

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 137 of 172

def initialize
@id = 0
@name = ""
@members = []
@pages = [RPG::BattleEventPage.new]
end
attr_accessor :id
attr_accessor :name
attr_accessor :members
attr_accessor :pages
end
end

RPG::Troop::Member
Data class for troop members.

Superclass

{ Object

Referrer

{ RPG::Troop

Attributes

enemy_id

The enemy ID.

The troop member's X-coordinate.

The troop member's Y-coordinate.

hidden

Truth value of the [Appear Midway] option.

immortal

Truth value of the [Immortal] option.

Definition
module RPG
class Troop
class Member
def initialize
@enemy_id = 1
@x = 0

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 138 of 172

@y = 0
@hidden = false
@immortal = false
end
attr_accessor :enemy_id
attr_accessor :x
attr_accessor :y
attr_accessor :hidden
attr_accessor :immortal
end
end
end

RPG::Troop::Page
Data class for battle events (pages).

Superclass

{ Object

Referrer

{ RPG::Troop

Attributes

condition

Condition (RPG::Troop::Page::Condition).

span

Span (0: battle, 1: turn, 2: moment).

list

Program contents. An RPG::EventCommand array.

Inner Class

{ RPG::Troop::Page::Condition

Definition
module RPG
class Troop
class Page
def initialize
@condition = RPG::Troop::Page::Condition.new
@span = 0
@list = [RPG::EventCommand.new]
end
attr_accessor :condition
attr_accessor :span
attr_accessor :list

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 139 of 172

end
end
end

RPG::Troop::Page::Condition
A database of battle event [Conditions].

Superclass

{ Object

Referrer

{ RPG::Troop::Page

Attributes

turn_ending

Truth value for whether the [When the end of the turn] condition is valid.

turn_valid

Truth value for whether the [Turn No.] condition is valid.

enemy_valid

Truth value for whether the [Enemy] condition is valid.

actor_valid

Truth value for whether the [Actor] condition is valid.

switch_valid

Truth value for whether the [Switch] condition is valid.

turn_a
turn_b

a and b values specified in the [Turn No.] condition. To be input in the form A + B * X.

enemy_index

Troop member index specified in the [Enemy] condition (0..7).

enemy_hp

HP percentage specified in the [Enemy] condition.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 140 of 172

actor_id

Actor ID specified in the [Actor] condition.

actor_hp

HP percentage specified in the [Actor] condition.

switch_id

Switch ID specified in the [Switch] condition.

Definition
module RPG
class Troop
class Page
class Condition
def initialize
@turn_ending = false
@turn_valid = false
@enemy_valid = false
@actor_valid = false
@switch_valid = false
@turn_a = 0
@turn_b = 0
@enemy_index = 0
@enemy_hp = 50
@actor_id = 1
@actor_hp = 50
@switch_id = 1
end
attr_accessor :turn_ending
attr_accessor :turn_valid
attr_accessor :enemy_valid
attr_accessor :actor_valid
attr_accessor :switch_valid
attr_accessor :turn_a
attr_accessor :turn_b
attr_accessor :enemy_index
attr_accessor :enemy_hp
attr_accessor :actor_id
attr_accessor :actor_hp
attr_accessor :switch_id
end
end
end
end

RPG::State
Data class for state.

Superclass

{ Object

Attributes

id

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 141 of 172

State ID.

name

State name.

icon_index

The state's icon number.

restriction

Sets restrictions (0: none, 1: can't use magic, 2: always attack enemies, 3: always attack allies, 4: can't
move, 5: can't move or evade).

priority

State priority (0..10).

atk_rate

Attack percentage.

def_rate

Defense percentage.

spi_rate

Spirit percentage.

agi_rate

Agility percentage.

nonresistance

Truth value of the [Nonresistance] option.

offset_by_opposite

Truth value of the [Offset By Opp.] option.

slip_damage

Truth value of the [Slip Damage] option.

reduce_hit_ratio

Truth value of the [Reduce Hit Ratio] option.

battle_only

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 142 of 172

Truth value of whether the state wears off at battle end.

release_by_damage

Truth value of whether the state wears after receiving damage.

hold_turn
auto_release_prob

Probability of wearing off is auto_release_prob % after hold_turn turns have passed.

message1
message2
message3
message4

Messages. For an actor, for an enemy, remaining, releasing.

element_set

Elements to guard. An Element ID array.

state_set

States to cancel. A State ID array.

note

The text of the note.

Definition
module RPG
class State
def initialize
@id = 0
@name = ""
@icon_index = 0
@restriction = 0
@priority = 5
@atk_rate = 100
@def_rate = 100
@spi_rate = 100
@agi_rate = 100
@nonresistance = false
@offset_by_opposite = false
@slip_damage = false
@reduce_hit_ratio = false
@battle_only = true
@release_by_damage = false
@hold_turn = 0
@auto_release_prob = 0
@message1 = ""
@message2 = ""
@message3 = ""
@message4 = ""
@element_set = []
@state_set = []
@note = ""
end
attr_accessor :id

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 143 of 172

attr_accessor :name
attr_accessor :icon_index
attr_accessor :restriction
attr_accessor :priority
attr_accessor :atk_rate
attr_accessor :def_rate
attr_accessor :spi_rate
attr_accessor :agi_rate
attr_accessor :nonresistance
attr_accessor :offset_by_opposite
attr_accessor :slip_damage
attr_accessor :reduce_hit_ratio
attr_accessor :battle_only
attr_accessor :release_by_damage
attr_accessor :hold_turn
attr_accessor :auto_release_prob
attr_accessor :message1
attr_accessor :message2
attr_accessor :message3
attr_accessor :message4
attr_accessor :element_set
attr_accessor :state_set
attr_accessor :note
end
end

RPG::Animation
Data class for animation.

Superclass

{ Object

Attributes

id

The animation ID.

name

The animation name.

animation1_name

The first animation's graphic file name.

animation1_hue

The adjustment value for the first animation graphic's hue (0..360).

animation2_name

The second animation's graphic file name.

animation2_hue

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 144 of 172

The adjustment value for the second animation graphic's hue (0..360).

position

The base position (0: head, 1: center, 2: feet, 3: screen).

frame_max

Number of frames.

frames

Frame contents. An RPG::Animation::Frame array.

timings

Timing for SE and flash effects. An RPG::Animation::Timing array.

Inner Classes

{ RPG::Animation::Frame
{ RPG::Animation::Timing

Definition
module RPG
class Animation
def initialize
@id = 0
@name = ""
@animation1_name = ""
@animation1_hue = 0
@animation2_name = ""
@animation2_hue = 0
@position = 1
@frame_max = 1
@frames = [RPG::Animation::Frame.new]
@timings = []
end
attr_accessor :id
attr_accessor :name
attr_accessor :animation1_name
attr_accessor :animation1_hue
attr_accessor :animation2_name
attr_accessor :animation2_hue
attr_accessor :position
attr_accessor :frame_max
attr_accessor :frames
attr_accessor :timings
end
end

RPG::Animation::Frame
Data class for animation frames.

Superclass

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 145 of 172

{ Object

Referrer

{ RPG::Animation

Attributes

cell_max

Number of cells. Equivalent to the largest cell number in the frame set.

cell_data

2-dimensional array containing cell contents (Table).

Generally takes the form cell_data[cell_index, data_index].

data_index ranges from 0 to 7 and denotes various information about a cell (0: pattern, 1: X-coordinate, 2: Y-
coordinate, 3: zoom level, 4: angle of rotation, 5: horizontal flip, 6: opacity, 7: blending mode). Patterns are 1
less than the number displayed in RPGVX; -1 indicates that that cell is not in use.

Definition
module RPG
class Animation
class Frame
def initialize
@cell_max = 0
@cell_data = Table.new(0, 0)
end
attr_accessor :cell_max
attr_accessor :cell_data
end
end
end

RPG::Animation::Timing
Data class for the timing of an animation's SE and flash effects.

Superclass

{ Object

Referrer

{ RPG::Animation

Attributes

frame

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 146 of 172

Frame number. 1 less than the number displayed in RPGVX.

se

SE, or sound effect (RPG::AudioFile).

flash_scope

Flash area (0: none, 1: target, 2: screen; 3: hide target).

flash_color

Flash color (Color).

flash_duration

Flash duration.

Definition
module RPG
class Animation
class Timing
def initialize
@frame = 0
@se = RPG::AudioFile.new("", 80)
@flash_scope = 0
@flash_color = Color.new(255,255,255,255)
@flash_duration = 5
end
attr_accessor :frame
attr_accessor :se
attr_accessor :flash_scope
attr_accessor :flash_color
attr_accessor :flash_duration
end
end
end

RPG::CommonEvent
Data class for common events.

Superclass

{ Object

Attributes

id

The event ID.

name

The event name.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 147 of 172

trigger

The event trigger (0: none, 1: autorun; 2: parallel).

switch_id

The condition switch ID.

list

List of event commands. An RPG::EventCommand array.

Definition
module RPG
class CommonEvent
def initialize
@id = 0
@name = ""
@trigger = 0
@switch_id = 1
@list = [RPG::EventCommand.new]
end
attr_accessor :id
attr_accessor :name
attr_accessor :trigger
attr_accessor :switch_id
attr_accessor :list
end
end

RPG::System
Data class for the system.

Superclass

{ Object

Attributes

game_title

The game title.

version_id

Random number used for update checks. Updates changed values every time data is saved in RPGVX.

party_members

The initial party. An array of actor IDs.

elements

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 148 of 172

Element list. Text array using element IDs as subscripts, with the element in the 0 position being nil.

switches

Switch list. Text array using switch IDs as subscripts, with the element in the 0 position being nil.

variables

Variable list. Text array using variable IDs as subscripts, with the element in the 0 position being nil.

passages

Passage table. A 1-dimensional array (Table) containing various flags.

The tile ID is used as a subscript. Each bit is handled as follows:

z 0x01: Characters cannot move.


z 0x02: The boat cannot move.
z 0x04: The ship cannot move.
z 0x08: The airship cannot land.
z 0x10: Display above characters.
z 0x40: Bush.
z 0x80: Counter.
boat

The boat settings (RPG::System::Vehicle).

ship

The ship settings (RPG::System::Vehicle).

airship

The airship settings (RPG::System::Vehicle).

title_bgm

The title BGM (RPG::AudioFile).

battle_bgm

The battle BGM (RPG::AudioFile).

battle_end_me

The battle end ME (RPG::AudioFile).

gameover_me

The gameover ME (RPG::AudioFile).

sounds

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 149 of 172

Sound Effects. An RPG::AudioFile array.

start_map_id

The map ID of the player's initial position.

start_x

The map X-coordinate of the player's initial position.

start_y

The map Y-coordinate of the player's initial position.

terms

Terms (RPG::System::Terms).

test_battlers

Party settings for battle tests. An RPG::System::TestBattler array.

test_troop_id

The troop ID for battle tests.

battler_name

The battler graphic file name, for internal use.

battler_hue

The adjustment value for the battler graphic's hue (0..360), for internal use.

edit_map_id

The ID of the map currently being edited, for internal use.

Inner Classes

{ RPG::System::Vechile
{ RPG::System::Terms
{ RPG::System::TestBattler

Definition
module RPG
class System
def initialize
@game_title = ""
@version_id = 0
@party_members = [1]
@elements = [nil, ""]
@switches = [nil, ""]
@variables = [nil, ""]

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 150 of 172

@passages = Table.new(8192)
@boat = RPG::System::Vehicle.new
@ship = RPG::System::Vehicle.new
@airship = RPG::System::Vehicle.new
@title_bgm = RPG::BGM.new
@battle_bgm = RPG::BGM.new
@battle_end_me = RPG::ME.new
@gameover_me = RPG::ME.new
@sounds = []
20.times { @sounds.push(RPG::AudioFile.new) }
@test_battlers = []
@test_troop_id = 1
@start_map_id = 1
@start_x = 0
@start_y = 0
@terms = RPG::System::Terms.new
@battler_name = ""
@battler_hue = 0
@edit_map_id = 1
end
attr_accessor :game_title
attr_accessor :version_id
attr_accessor :party_members
attr_accessor :elements
attr_accessor :switches
attr_accessor :variables
attr_accessor :passages
attr_accessor :boat
attr_accessor :ship
attr_accessor :airship
attr_accessor :title_bgm
attr_accessor :battle_bgm
attr_accessor :battle_end_me
attr_accessor :gameover_me
attr_accessor :sounds
attr_accessor :test_battlers
attr_accessor :test_troop_id
attr_accessor :start_map_id
attr_accessor :start_x
attr_accessor :start_y
attr_accessor :terms
attr_accessor :battler_name
attr_accessor :battler_hue
attr_accessor :edit_map_id
end
end

RPG::System::Vehicle
Data class for vehicles.

Superclass

{ Object

Referrer

{ RPG::System

Attributes

character_name

The vehicle's character graphic file name.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 151 of 172

character_index

The vehicle's character index of the graphic file (0..7).

bgm

The vehicle BGM (RPG::AudioFile).

start_map_id

The map ID of the vehicle's initial position.

start_x

The map X-coordinate of the vehicle's initial position.

start_y

The map Y-coordinate of the vehicle's initial position.

Definition
module RPG
class System
class Vehicle
def initialize
@character_name = ""
@character_index = 0
@bgm = RPG::AudioFile.new
@start_map_id = 0
@start_x = 0
@start_y = 0
end
attr_accessor :character_name
attr_accessor :character_index
attr_accessor :bgm
attr_accessor :start_map_id
attr_accessor :start_x
attr_accessor :start_y
end
end
end

RPG::System::Terms
Data class for terminology.

Superclass

{ Object

Referrer

{ RPG::System

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 152 of 172

Attributes

level

The term "Level".

level_a

The term "Level" (abbreviation).

hp

The term "HP".

hp_a

The term "HP" (abbreviation).

mp

The term "MP".

mp_a

The term "MP" (abbreviation).

atk

The term "Attack".

def

The term "Defense".

spi

The term "Spirit".

agi

The term "Agility".

weapon

The term "Weapon".

armor1

The term "Shield".

armor2

The term "Helmet".

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 153 of 172

armor3

The term "Body Armor".

armor4

The term "Accessory".

weapon1

The term "Weapon1"。

weapon2

The term "Weapon2"。

attack

The term "Attack".

skill

The term "Skill".

guard

The term "Guard".

item

The term "Item".

equip

The term "Equip".

status

The term "Status".

save

The term "Save".

game_end

The term "Game End".

fight

The term "Fight".

escape

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 154 of 172

The term "Escape".

new_game

The term "New Game".

continue

The term "Continue".

shutdown

The term "Shutdown".

to_title

The term "To Title".

cancel

The term "Cancel".

gold

The term "G" (the unit of currency).

Definition
module RPG
class System
class Terms
def initialize
@level = ""
@level_a = ""
@hp = ""
@hp_a = ""
@mp = ""
@mp_a = ""
@atk = ""
@def = ""
@spi = ""
@agi = ""
@weapon = ""
@armor1 = ""
@armor2 = ""
@armor3 = ""
@armor4 = ""
@weapon1 = ""
@weapon2 = ""
@attack = ""
@skill = ""
@guard = ""
@item = ""
@equip = ""
@status = ""
@save = ""
@game_end = ""
@fight = ""
@escape = ""
@new_game = ""
@continue = ""
@shutdown = ""
@to_title = ""

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 155 of 172

@cancel = ""
@gold = ""
end
attr_accessor :level
attr_accessor :level_a
attr_accessor :hp
attr_accessor :hp_a
attr_accessor :mp
attr_accessor :mp_a
attr_accessor :atk
attr_accessor :def
attr_accessor :spi
attr_accessor :agi
attr_accessor :weapon
attr_accessor :armor1
attr_accessor :armor2
attr_accessor :armor3
attr_accessor :armor4
attr_accessor :weapon1
attr_accessor :weapon2
attr_accessor :attack
attr_accessor :skill
attr_accessor :guard
attr_accessor :item
attr_accessor :equip
attr_accessor :status
attr_accessor :save
attr_accessor :game_end
attr_accessor :fight
attr_accessor :escape
attr_accessor :new_game
attr_accessor :continue
attr_accessor :shutdown
attr_accessor :to_title
attr_accessor :cancel
attr_accessor :gold
end
end
end

RPG::System::TestBattler
Data class for the battlers used in battle tests.

Superclass

{ Object

Referrer

{ RPG::System

Attributes

actor_id

The actor ID.

level

The actor's level.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 156 of 172

weapon_id

The actor's weapon ID.

armor1_id

The actor's shield ID.

armor2_id

The actor's helmet ID.

armor3_id

The actor's body armor ID.

armor4_id

The actor's accessory ID.

Definition
module RPG
class System
class TestBattler
def initialize
@actor_id = 1
@level = 1
@weapon_id = 0
@armor1_id = 0
@armor2_id = 0
@armor3_id = 0
@armor4_id = 0
end
attr_accessor :actor_id
attr_accessor :level
attr_accessor :weapon_id
attr_accessor :armor1_id
attr_accessor :armor2_id
attr_accessor :armor3_id
attr_accessor :armor4_id
end
end
end

RPG::AudioFile
Superclass of BGM, BGS, ME, and SE.

Superclass

{ Object

Attributes

name

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 157 of 172

The sound file name.

volume

The sound's volume (0..100). The default values are 100 for BGM and ME and 80 for BGS and SE.

pitch

The sound's pitch (50..150). The default value is 100.

Definition
module RPG
class AudioFile
def initialize(name = "", volume = 100, pitch = 100)
@name = name
@volume = volume
@pitch = pitch
end
attr_accessor :name
attr_accessor :volume
attr_accessor :pitch
end
end

RPG::BGM
Data class for BGM. This class has a method to play oneself with Audio module.

Superclass

{ RPG::AudioFile

Referrers

{ RPG::Map
{ RPG::System
{ RPG::System::Vehicle
{ RPG::EventCommand

Class Methods

RPG::BGM.last

Returns BGM (RPG::BGM) that playing now. If no playing BGM, returns nil.

RPG::BGM.stop

Stops BGM playback.

RPG::BGM.fade(time)

Starts BGM fadeout. time is the length of the fadeout in milliseconds.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 158 of 172

Method

play

Starts the BGM playback.

Definition
module RPG
class BGM < AudioFile
@@last = BGM.new
def play
if @name.empty?
Audio.bgm_stop
@@last = BGM.new
else
Audio.bgm_play("Audio/BGM/" + @name, @volume, @pitch)
@@last = self
end
end
def self.stop
Audio.bgm_stop
@@last = BGM.new
end
def self.fade(time)
Audio.bgm_fade(time)
@@last = BGM.new
end
def self.last
@@last
end
end
end

RPG::BGS
Data class for BGS. This class has a method to play oneself with Audio module.

Superclass

{ RPG::AudioFile

Referrers

{ RPG::Map
{ RPG::EventCommand

Class Methods

RPG::BGS.last

Returns BGS (RPG::BGS) that playing now. If no playing BGS, returns nil.

RPG::BGS.stop

Stops BGS playback.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 159 of 172

RPG::BGS.fade(time)

Starts BGS fadeout. time is the length of the fadeout in milliseconds.

Method

play

Starts the BGS playback.

Definition
module RPG
class BGS < AudioFile
@@last = BGS.new
def play
if @name.empty?
Audio.bgs_stop
@@last = BGS.new
else
Audio.bgs_play("Audio/BGS/" + @name, @volume, @pitch)
@@last = self
end
end
def self.stop
Audio.bgs_stop
@@last = BGS.new
end
def self.fade(time)
Audio.bgs_fade(time)
@@last = BGS.new
end
def self.last
@@last
end
end
end

RPG::ME
Data class for ME. This class has a method to play oneself with Audio module.

Superclass

{ RPG::AudioFile

Referrers

{ RPG::System
{ RPG::EventCommand

Class Methods

RPG::ME.stop

Stops ME playback.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 160 of 172

RPG::ME.fade(time)

Starts ME fadeout. time is the length of the fadeout in milliseconds.

Method

play

Starts the ME playback.

Definition
module RPG
class ME < AudioFile
def play
if @name.empty?
Audio.me_stop
else
Audio.me_play("Audio/ME/" + @name, @volume, @pitch)
end
end
def self.stop
Audio.me_stop
end
def self.fade(time)
Audio.me_fade(time)
end
end
end

RPG::SE
Data class for SE. This class has a method to play oneself with Audio module.

Superclass

{ RPG::AudioFile

Referrers

{ RPG::Animation::Timing
{ RPG::System
{ RPG::EventCommand
{ RPG::MoveCommand

Class Methods

RPG::SE.stop

Stops SE playback.

Method

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 161 of 172

play

Starts the SE playback.

Definition
module RPG
class SE < AudioFile
def play
unless @name.empty?
Audio.se_play("Audio/SE/" + @name, @volume, @pitch)
end
end
def self.stop
Audio.se_stop
end
end
end

Appendix
{ Regular Expressions
{ sprintf Format

Regular Expressions
{ Back References
{ Character Class

Bellow is a list of all the metacharacters that Ruby supports.

{ Letters and numbers without \ are not metacharacters

{ Symbols with \ are not metacharacters

窶ヲis the rule.

{ ^

Beginning of line. Match directly before the first character or line feed.

{ $

End of line. Match directly before the end of a character string or line feed.

p "\n".gsub(/$/, "o") # => "o\no"

{ .

Match any single character that excludes a line feed (when working with multi-byte characters, this refers to
one character, not one byte). With the Regular Expression option m (multiple line mode. See the Regular
Expression Literal.), it matches with any character that includes a line feed.

{ \w

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 162 of 172

Letters or numbers. The same as [0-9A-Za-z_]

Matches the Japanese double-byte characters.

{ \W

Non-alphanumeric character. Characters besides \w.

{ \s

Space character. The same as [ \t\n\r\f].

{ \S

Non-blank character. Characters besides [ \t\n\r\f]

{ \d

Number. The same as [0-9].

{ \D

Non-number.

{ \A

Beginning of a Character String. Differently from ^, it does not influence the effectiveness of a line feed.

{ \Z

End of a character string. Matches the front of a line feed if the character string ends at the line feed.

p "\n".gsub(/\Z/, "o") # => "o\no"

{ \z

End of a character string. Differently from $ or \Z, it does not influence the effectiveness of a line feed.

{ \b

Outside the specified character class it is a language boundary. (Matches between \a and \W.) While in the
specified class it is a back space (0x08).

{ \B

Non-language boundary.

{ \G

Matches (doesn't have a width) the place matched from the previous one (directly after). Matches the front
position only the first time. (Same as \A)

Can use with scan or gsub. Use when you want to make a match after the location that was matched the

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 163 of 172

time before.

# Takes values from the front of the line three at a time (for as long as the values continue.)
str = "123456 789"
str.scan(/\G\d\d\d/) {|m| p m }

{ []

Set character class. See character class.

{ *

Return the expression from directly before more then 0 times. Will try to match for as long as possible.

{ *?

Quantifiers. Return the expression from directly before more then 0 times. (At shortest 1 match)

{ +

Quantifiers. Return the expression from directly before more then 1 time.

{ +?

Quantifiers. Return the expression from directly before more then 1 time. (At shortest 1 match.)

{ {m}
{ {m,}
{ {m,n}

Control the return of a set group (interval quantifier). Return all of the Regular Expressions from directly
before.

„ m times
„ more then m times
„ more then m times, at most n times.

Matches for {n} or {,} will always fail.

str = "foofoofoo"
p str[/(foo){1}/] # => "foo"
p str[/(foo){2,}/] # => "foofoofoo"
p str[/(foo){1,2}/] # => "foofoo"

Regular Expression ?, *, + are all the same as {0,1}, {0,} {1,}.

{ {m}?
{ {m,}?
{ {m,n}?

Interval Quantifier. Will return the regular expression from each before for

„ m times
„ more then m times
„ more then m times, at most n times.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 164 of 172

at least one time.

{ ?

Quantifiers. Will return the previous regular expression 1 or 0 times.

{ ??

Quantifiers. Will return the previous regular expression 1 or 0 times (at least once).

{ |

Alternative.

{ ()

Regular Expression group movement. The character string matched to the regular expression in parenthesis
is remembered for back referencing.

{ \1, \2 ... \n

Back reference. Reference a Back Reference.

{ (?# )

Comment. Ignore all the character strings in parentheses.

{ (?: )

Back Reference without group movement. That is, use a flexible group movement without becoming the
targets \1, \2 (also $1, $2) etc .

/(abc)/ = セ "abc"
p $1
=> "abc"

/(?:abc)/ = セ "abc"
p $1
=> nil

{ (?= )

Lookahead. Set location according to pattern. (Has no width.)

The

(?=re1)re2

expression is a regular expression that matches a match of both re1 and re2.

The

re1(?=re2)

expression, is a regular expression that continues to the following character string which matches with re2,

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 165 of 172

called re1.

p /foo(?=bar)/ = セ "foobar" # => 0


p $& # => "foo" (no information about the "bar" section)

{ (?! )

Negative Loookahead. Set place depending on the negation of a pattern. (Has not width.)

The

(?!re1)re2

expression, is a regular expression that does not match re1 but does match re2.

# 000 Number that excludes 3 characters


re = /(?!000)\d\d\d/
p re = セ "000" # => nil
p re = セ "012" # => 0
p re = セ "123" # => 0

#C Identifier (Starts at [A-Za-z_] and continues with the [0-9A-Za-z_] character string.

/\b(?![0-9])\w+\b/

Back References

The regular expression \1 \2 窶ヲ \n is a back reference. It matches the character string matched in the nth
parentheses (Regular Expression ( ) Grouping).

/((foo)bar)\1\2/

is the same as:

/((foo)bar)foobarfoo/

Example:

re = /(foo|bar|baz)\1/
p re = セ 'foofoo' # => 0
p re = セ 'barbar' # => 0
p re = セ 'bazbaz' # => 0
p re = セ 'foobar' # => nil

The parentheses in use must be more to the left than the back reference.

If there is a back reference in the parentheses in use the match will consistently fail. Also, the match will
consistently fail when a single digit back reference has no parenthesis too.

p /(\1)/ = セ "foofoofoo" # => nil


p /(foo)\2/ = セ "foo\2" # => nil

While one can specify a back reference greater then 2 digits, one must be carefull not to confuse it with \nnn
(characters corresponding to the octal nnn) of backslash notation. If a numeric value is 1 digit, it is a back
reference. When establishing more then 2 digits, it will be perceived as 8-bit code if parentheses are not used.

Also, when working with regular expressions it is necessary to start with 0 (such as \01, etc.) when using 1 bit
code in 8 bit. (There is no back reference \0 so it isn't unclear.)

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 166 of 172

p /\1/ = セ "\1" # => nil # back reference that doesn use parentheses.
p /\01/ = セ "\1" # => 0 8 bit code
p /\11/ = セ "\11" # => 0 8 bit code

# 8 bit code (because there are no parentheses in use)


p /(.)\10/ = セ "1\10" # => 0

# back reference (because there are parentheses in use)


p /((((((((((.))))))))))\10/ = セ "aa" # => 0

# 8 bit code (However because there is no such


# \08 "\0" + "8" 8 bit code)
p /(.)\08/ = セ "1\0008" # => 0

#If you want to write numbers following a back reference


#you have to use parentheses to group them and split them up.
p /(.)(\1)1/ = セ "111" # => 0

Character Class

Regular class [] is a set character class. One character listed inside the [] will be matched.

For example, for /[abc]/ one of "a", "b" or "c" will be matched. You can also write character strings using the "-"
when characters follow the ASCII code order like this: /[a-c]/. Also, if the first character is a ^ character from
outside of the set character string will be matched.

Any 窶録' not at the beginning will be matched with that character. Also, any "-" at the front or end of a line will be
matched with that character.

p /[a^]/ = セ "^" # => 0


p /[-a]/ = セ "-" # => 0
p /[a-]/ = セ "-" # => 0
p /[-]/ = セ "-" # => 0

A blank character class will result in an error.

p /[]/ = セ ""
p /[^]/ = セ "^"
# => invalid regular expression; empty character class: /[^]/

The "]" at the front of a line (or directly after a NOT "^") doesn't mean that the character class is over but is just a
simple "]". It is recommended that this kind of "]" performs a backslash escape.

p /[]]/ = セ "]" # => 0


p /[^]]/ = セ "]" # => nil

"^", "-", "]" and "\\" (backslash) can do a backslash escape and make a match with that character.

p /[\^]/ = セ "^" # => 0


p /[\-]/ = セ "-" # => 0
p /[\]]/ = セ "]" # => 0
p /[\\]/ = セ "\\" # => 0

Inside the [] you can use character string and the same backslash notation, and also the regular expressions \w,
\W, \s, \S, \d, \D (these are short-hand for the character class).

Please pay attention to to the fact that the character classes below can make a match with a line feed character
too according to the negation (the same is true with regular expressions \W and \D.)

p /[^a-z]/ = セ "\n" # => 0

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 167 of 172

sprintf Format
The sprintf format of Ruby is basically the same as that the C language. However, there are some differences
such as, (1) there is no short or long modifier like in C, (2) there is a 2 bit variable indicator (%b), and (3) not all of
the dialects of sprintf (': 3-digit separators) are supported.

A complete explanation of Ruby's sprintf format is given below.

Below is a sprintf format form. The parts enclosed in [] can be omitted.

%[flag][width][.accuracy]indicator

To output '%' type '%%'.

Below is an explanation of each of the elements.

Flag

There are 5 types of flags: '#', '+', ' ' (space), '-', '0'

With the 2, 8, and 16 bit indicators ('b', 'o', 'x', 'X'), "0b", "0", "0x" and "0X" are added as prefixes.

p sprintf("%#b", 10) # => "0b1010"


p sprintf("%#o", 10) # => "012"
p sprintf("%#x", 10) # => "0xa"
p sprintf("%#X", 10) # => "0XA"

For floating point numbers ('f', 'e', 'E', 'g' and 'G') always put a "." in the output.

p sprintf("%.0f", 10) # => "10"


p sprintf("%#.0f", 10) # => "10."
p sprintf("%.0e", 10) # => "1e+01"
p sprintf("%#.0e", 10) # => "1.e+01"

By adding 'g', 'G' to the above there is a left over 0 on the end.

p sprintf("%.05g", 10) # => "10"


p sprintf("%#.05g", 10) # => "10.000"

Symbols will be attached to output character strings. A '+' symbol will especially be added to positive
numbers. This only applies to the following numerical value indicators: 'd', 'i', 'b', 'o', 'x', 'X', 'u', 'f', 'e', 'E', 'g'
and 'G'. Also, for 'b', 'o', 'x', 'X', and 'u', a '-' symbol will be added to negative numbers.

p sprintf("%d", 1) # => "1"


p sprintf("%+d", 1) # => "+1"

p sprintf("%x", -1) # => "..f" # ".." shows that f continues infinitely


p sprintf("%+x", -1) # => "-1"

' ' (space)

Same meaning as a '+' symbol but here, a blank space is used in place of the '+' symbol, meaning positive.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 168 of 172

This only applies to the following numerical value indicators: 'd', 'i', 'b', 'o', 'x', 'X', 'u', 'f', 'e', 'E', 'g', 'G'.

p sprintf("%d", 1) # => "1"


p sprintf("%+d", 1) # => "+1"
p sprintf("% d", 1) # => " 1"

p sprintf("%x", -1) # => "..f"


p sprintf("% x", 1) # => " 1"
p sprintf("% x", -1) # => "-1"

Output is left justified. It only has meaning if "Width" is specified.

If output is right justified, '0' will fill in the left over sections in place of a blank space.

This only applies to the following numerical value indicators: 'd', 'i', 'b', 'o', 'x', 'X', 'u', 'f', 'g', 'G' (It does not
apply to 'e' or 'E').

p sprintf("%010d", 10)
# => "0000000010"

Outputs specified together with '#' are shown below.

p sprintf("%#010x", 10) # => "0x0000000a"


p sprintf("%#010o", 10) # => "0000000012"
p sprintf("%#010b", 10) # => "0b00001010"

This is the same as below.

p sprintf("%#10.8x", 10) # => "0x0000000a"


p sprintf("%#10.9o", 10) # => "0000000012"
p sprintf("%#10.8b", 10) # => "0b00001010"

Normally shown as displayed below.

p sprintf("%#10x", 10) # => " 0xa"


p sprintf("%#10o", 10) # => " 012"
p sprintf("%#10b", 10) # => " 0b1010"

Width

A number string that begins with any number other than 0 is the specified width. Width displays the length of the
character string produced. Contrary to the value of "Precision", which is mentioned later, only the number string of
the width part is produced.

As for width specification, the length of " ", "+", "-", "0b", "0", "0x", "0X", which are presented as "Flags", is also
considered.

p sprintf("%#05x", 10) # => "0x00a"

Width is a specification of the "minimum necessary width." If the resulting number string goes over the specified
width, width specification is no longer valid.

If width is specified as '*', then the width value is received from an argument.

p sprintf("%10s", "foo") # => " foo"

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 169 of 172

p sprintf("%*s", 10, "foo") # => " foo"

Precision

A number string that follows a "." shows the precision (when only a "." is displayed, it is the same as ".0").
Precision means the length of a portion of numerical value strings for the following integer indicators: 'd', 'i', 'b', 'o',
'x', 'X', 'u'.

p sprintf("%10.5d", 1) # => " 00001"


p sprintf("%#10.5x", 1) # => " 0x00001"
p sprintf("%+10.5x", 1) # => " +00001"

This means the decimal places for the floating point indicator 'f'.

p sprintf("%10.5f", 1) # => " 1.00000"


p sprintf("%10.5f", 10) # => " 10.00000"

This means the number of significant figures for floating point indicators 'e', 'E', 'g', and 'G'.

p sprintf("%10.5e", 1) # => "1.00000e+00"


p sprintf("%10.5e", 10) # => "1.00000e+01"
p sprintf("%10.5g", 10) # => " 10"
p sprintf("%#10.5G", 10) # => " 10.000"

For character string indicators 's' and 'p', the portion which goes over the specified number within the argument
character string is cut out. If width and precision values are the same, only the output for that length will be
performed, no matter what argument is being considered.

p sprintf("%10.2s", "foo") # => " fo"

p sprintf("%5.5s", "foo") # => # => " foo"


p sprintf("%5.5s", "foobar") # => # => "fooba"

If '*' is specified as precision, the precision value will be received from the argument.

p sprintf("%.5s", "foobar") # => "fooba"


p sprintf("%.*s", 5, "foobar") # => "fooba"

Indicators

Indicators show argument pattern interpretations. They cannot be abbreviated, and are divided into the following
groups:

{ Indicators showing character strings: 'c', 's', 'p'


{ Indicators showing integers: 'd', 'i', 'u', 'b', 'o', 'x', 'X',
{ Indicators showing floating points: 'f', 'g', 'e', 'E', 'G'

Argument values 0-255 are considered together with character codes, then the corresponding characters are
outputted. Argument conversion is attempted with the to_int method for objects other than numerical values,
String, nil, true, and false.

This only applies to flag '-' and "width" specification.

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 170 of 172

Character strings are outputted.

If the argument is not a String object, the to_s method causes the object turned into a character string to be
treated as an argument.

Object#inspect results are outputted.

p sprintf("%s", [1, 2, 3]) # => "123"


p sprintf("%p", [1, 2, 3]) # => "[1, 2, 3]"

d
i

An argument's numerical value is outputted as an integer decimal expression.

If the argument is not an integer it will be converted to one.

The argument value is considered as an integer without a symbol, then outputted as a decimal integer.

p sprintf("%u", -1) # => "4294967295"

outputs p 0xffff_ffff.to_s.

'%u' regards the argument as an integer's fixed length, and

printf("%u", n)

has the same meaning as

printf("%d", n & ~(-1 << n.size*8))

for negative integer n.

b
o
x
X

Integers are outputted as character strings with binary, octal, hexadecimal, and hexadecimal (upper case
letter) expressions.

If the '#' flag is specified, "0b", "0", "0x", "0X" are added to the front.

If the '+' or ' ' flags are not used, ".." (if the '#' flag is used, after "0x" etc.) is added to the front of negative
numbers. This means that characters of the highest-order digit continue infinetely, and negative numbers are
shown in complementary numbers of 2.

p sprintf("%#b", 10) # => "0b1010"


p sprintf("%#o", 10) # => "012"
p sprintf("%#x", 10) # => "0xa"

".." is added to # negative numbers

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 171 of 172

p sprintf("%#b", -1) # => "0b..1"


p sprintf("%#o", -1) # => "0..7"
p sprintf("%#x", -1) # => "0x..f"

p sprintf("%10x", -1) # => " ..f"


p sprintf("%-10x", -1) # => "..f "

If # "precision" has been specified, ".." is not added.


p sprintf("%.10x", -1) # => "ffffffffff"

f
e
E
g
G

'f' outputs numerical values with a decimal expression (xxx.xxx).

'e' outputs numerical values with an exponential notation (x.xxxe+xx).

When the exponent is smaller then -4, or higher than the precision, 'g' outputs the same as 'e'. In all other
cases, it outputs the same as 'f'. However, 0 at the end of a decimal fraction is omitted.

Upper case indicators 'E' and 'G' change the output alphabet into upper case letters.

p sprintf("%f", 1.0) # => "1.000000"


p sprintf("%e", 1.0) # => "1.000000e+000"
p sprintf("%g", 1.0) # => "1"

p sprintf("%f", 10.1) # => "10.100000"


p sprintf("%e", 10.1) # => "1.010000e+001"
p sprintf("%g", 10.1) # => "10.1"

p sprintf("%g", 10 ** 6) # => "1e+006"


p sprintf("%g", 10 ** -5) # => "1e-005"

The precision default value is 6.

Argument Specification

This is not used often, so it is explained last.

nth$

Indicates that formatting of the nth argument will be performed.

p sprintf("%1$d, %1$x, %1$o", 10)


=> "10, a, 12"

p sprintf("%3$d, %2$x, %1$o", 1, 2, 3)


=> "3, 2, 1"

Used when you want to change the format according to the situation, but do not want to change the order.

case ENV['LC_TIME']
when /^ja_JP/
fmt = "%1$d エ%2$d ・3$d ・"
else
fmt = "%2$02d/%03$2d/%1$02d"
end

p sprintf(fmt, 1, 4, 22)

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010


RGSS Reference Manual Page 172 of 172

=> "04/22/01"

file://C:\Documents and Settings\Admin\Local Settings\Temp\~hh3715.htm 12/13/2010

You might also like