String formatting
The ROT.Util.format
function is used to perform complex replacements within string templates:
SHOW(
ROT.Util.format("%s %s", "hello", "world")
);
It is possible to alter and enrich the behavior of this function by adding mappings to the format.map
object. Keys correspond to individual formatting specifiers; values are method names to be called. The default value of format.map
is {s:"toString"}
.
var myObj = {
foo: function() { return "bar"; }
}
ROT.Util.format.map.f = "foo";
SHOW( ROT.Util.format("%f", myObj) );
Finally, using formatting specifier with an upper-case letter will result in a capitalized replacement. Let's show a more convoluted example:
var Item = function(name) {
this._name = name;
}
Item.prototype.a = function() {
var first = this._name.charAt(0);
return (first.match(/[aeiouy]/i) ? "an" : "a") + " " + this._name;
}
Item.prototype.the = function() {
return "the " + this._name;
}
ROT.Util.format.map.a = "a";
ROT.Util.format.map.the = "the";
var apple = new Item("apple");
var banana = new Item("banana");
var template = "You eat %a. %The was delicious.";
SHOW( ROT.Util.format(template, apple, apple) );
SHOW( ROT.Util.format(template, banana, banana) );
It is possible to pass additional arguments to the formatting function, using the {,} notation.
var Animal = function(name) {
this._name = name;
}
Animal.prototype.adjective = function(x) {
return x + " " + this._name;
}
ROT.Util.format.map.adjective = "adjective";
var cat = new Animal("cat");
var template = "You see a %{adjective,black}.";
SHOW( ROT.Util.format(template, cat) );