Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs

DragonRuby Game Toolkit

An intuitive 2D game engine. Fast, xplat, tiny, hot loaded. · By DragonRuby

Named parameters for primitives

A topic by connorshea created Apr 20, 2019 Views: 237 Replies: 3
Viewing posts 1 to 4

I had hoped to create a nice helper with named parameters for creating sprites, so that you could do something like this:

# before, doesn't really mean anything to me
[10, 10, 100, 100, [0, 0, 0]]
# after, much nicer!
sprite_helper(x: 10, y: 10, width: 100, height: 100, color: [0, 0, 0])

But unfortunately mruby doesn't support named parameters :( https://github.com/mruby/mruby/issues/363


Anyone have any other ideas or want to implement it in mruby for me?

(1 edit) (+1)

You can still do that luckily!

In Rails and other Ruby frameworks that existed before Ruby had KWARGs (named parameters) they would get around this by using Ruby's implicit destructuring of hashes if they're the last argument in a method. So this could be done by doing something like this. 

def sprite_helper(options = {})
  x = options[:x]
  y = options[:y]
  width = options[:width]
  height = options[:height]
  color = options[:color]
end
sprite_helper x: 10, y: 10, width: 100, height: 100, color: [0, 0, 0]


The downsides of this approach is you lose the ability to make certain arguments required without doing your own checking of the options hash and raising errors, but the upside is that it still allows for default arguments and allows you to pass a hash in as arguments in any order.

(+1)

What about something like this:

class Sprite
  attr_accessor :x, :y, :width, :height, :color
  def initialize(options = {})
     # set values based on options, assign defaults?
  end
  def to_primitive
    # check to make sure all values make sense, then
    [@x, @y, @width, @height, @color]
  end
end

and have simple classes with  `.to_primitive` calls when you want to render them

Developer(+4)

We're trying to decide what we want to do here, still....this already goes through a processing step between your code and the engine, so there's no reason we couldn't optionally process them as hashes instead of arrays without you having to maintain that code yourself. Stay tuned on this one!