Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
Tags

DragonRuby Game Toolkit

An intuitive 2D game engine. Fast, cross-platform, tiny, hot loaded. · By DragonRuby

strange behavior with constants, require and 'uninitialized constant error'

A topic by rathersilly created Apr 18, 2021 Views: 326 Replies: 1
Viewing posts 1 to 2

Hey, I found a strange bug and also a workaround.

If I define a constant (class or variable) in another file and require that file in main.rb, accessing that constant will throw an uninitialized constant error, UNLESS one of the following:

  • the constant is accessed in a method (like tick)
  • the constant is forward declared ( (suspiciously) as though it was C - see the Init module below)

Hopefully the code included explains what I mean:

####### main.rb #######
require '/app/init.rb'
module Init          # if Init is forward declared, it works as otherwise expected
end
class Game
  include Init       # this throws error unless the forward declaration exists
end
$game = Game.new
puts Color           # error: uninitialized constant
def tick
  puts Color         # works fine
  $game.fun          # works fine, as long as Init is forward declared.
end
###### init.rb #######
Color = [100,100,100]
module Init
  def fun
    puts "sup"
  end
end

I'm a total noob so forgive me if I missed something, but hopefully this helps someone else who was baffled by this behavior.

Developer (2 edits) (+2)

Try this structure:

################ app/main.rb
require 'app/init.rb'
require 'app/tick.rb'

################ app/init.rb
Color = [100,100,100]

module Init
  def fun
    puts "sup"
  end
end

################ app/tick.rb
class Game
  include Init       
end

$game = Game.new

puts Color           

def tick
  puts Color         
  $game.fun          
end