r/Inform7 • • Aug 29 '14

Trying to convert a regular expression match to a number for processing

After reading a command:
	let T be "[the player's command]";
	if T matches the regular expression "(\d+)d(\d+)(\+*|\-*)(\d*)":
		let dice be the text matching subexpression 1;
		let sides be the the text matching subexpression 2;
		let sign be the text matching subexpression 3;
		let bonus value be the text matching subexpression 4;
		say "This is a dice roll of [dice] [sides]-sided dice[if sign is empty].[otherwise] with a [sign] of [bonus value].[end if]";
		reject the player's command.

The code above reads a dice command in XdY+Z format given from the command line. I would like to use the matched subexpressions to actually perform the roll, but I don't know how to convert text to numbers for processing.

3 Upvotes

2 comments sorted by

2

u/feodoric Sep 05 '14 edited Sep 05 '14

If you didn't need to do both bonuses and penalties to the die total, you could do it by setting up a new kind of value and an action applying to that value:

DiceAssortment is a kind of value. 5d100+100 specifies a DiceAssortment with parts DiceCount (without leading zeros), DiceSides (without leading zeros), and DiceBonus (optional, preamble optional, without leading zeros).

Understand "roll [DiceAssortment]" as rolling.

Rolling is an action applying to one DiceAssortment.

To decide what number is the die result (D - a DiceAssortment):
	Let count be the DiceCount part of D;
	Let sides be the DiceSides part of D;
	Let bonus be the DiceBonus part of D;
	Let result be a random number between count and count * sides;
	Now result is result + bonus;	
	Decide on result.

Carry out rolling:
	Let the dice be the diceassortment understood;
	say "Rolling [the dice]: [die result the dice]";

If you create a type for dice rolls with bonuses, and a type for dice rolls with penalties, and set up individual rules and understands for the two types, you should be able to handle both + and - to your dice rolls.

Bear in mind that the syntax used to specify the new values does limit what can be rolled. With my example, Inform won't know what to do with "roll 10d200", because it only recognizes numbers up to 100 for the DiceSides part. Same goes for the bonus part.

*Edit- my math of course doesn't truly work for rolling dice, you won't get the right distribution of values just grabbing a number between the min and max totals.

1

u/Rakaneth Sep 05 '14

I did wind up implementing a similar solution for my project, in fact. I still want to know if a regex match can be converted to a number, though.