local variables begins with a lowercase letter
example: name, _EXP, i
(but I would ever write local variables completly in lowercase lettern)
They work only in the code block, where they are created. Local variables are also used as arguments.
example:
def test
i = 5 #i is a local variable
i += 1 #i is now 6
end
test #call the method test
print(i)
#this i is not the i in the method test, because this are two different code blocks
#so the output would be NIL, because there exist no local variable i in this block
instance variaböes begins with @
example: @Test, @object, @exp
(Here I would ever write in lowercase lettern, too. Also not @Test, but @test)
Instance variables works only in the object where they are created. When the object change his class, the instance variables will be erased in the cache.
class Hero
def initialize
@exp = 0
end
end
Now the variable @exp is IN an object of the class hero.
To get extern access to this variable use the module-method attr_accessor
class Hero
attr_accessor(:exp)
def initialize
@exp = 0
end
end
alex = Hero.new
alex.exp = 500
print(alex.exp)
Class variables beginns with @@. They works for a class and for all objects of the class.
example: @@counter, @@last_id
They are defined in the class, not in a method.
class Hero
@@counter = 0
def initialize
@@counter += 1
end
def self.counter?
p("There are " + @@counter.to_s + " heroes")
end
alex = Hero.new
judy = Hero.new
Jannis = Hero.new
Hero.counter #output: There are 3 heroes
global variables begins with $
example: $game_player, $game_map
They works global, also overall in the script. And every object has access to them.
$test = "Hello"
class A
def initialize
$test += " how"
end
end
class B
def initialize
$test += " are"
end
def next_word
$test += " you?"
end
end
a = A.new
b = B.new
b.next_word
p $test #output: "Hello how are you?"
At least there are constants. They begin with a uppercase lettern.They can be defined everywhere but they can not be changed. When they are defined in a class or module, you get access through modulename::constantname
constants are usefull for class- and modulnames and for every value which you often need but which is ever the same.
example
module Constants
MY_NAME = 'Jared'
end
p Constants::MY_NAME #output: 'Jared'
For your EXP-Script you should use a instance variable in the $game_actor object.
class Game_Actor
attr_reader(:skill_exp, :skill_level)
GAIN_SKILL_LEVEL = 'Well done you have gained a level!'
def initialize(actor_id) #original script
super() #original script
setup(actor_id) #original script
@skill_exp = 0 #new script
@skill_level = 0 #new script
end
def add_exp(value)
@skill_exp += value
if @skill_exp >= 1000 then @skill_level += 1; p(GAIN_SKILL_LEVEL); @skill_exp = 0; end
end
end
Of course that´s only an example. Instead of the p-method you should work with bitmaps and the draw_text method.