Skip to content

Instantly share code, notes, and snippets.

@coronarob
Created February 2, 2015 00:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save coronarob/adb039d0d0c63a4af12c to your computer and use it in GitHub Desktop.
Save coronarob/adb039d0d0c63a4af12c to your computer and use it in GitHub Desktop.
Code from Tutorial: Advanced Random Numbers (http://coronalabs.com/blog/2014/03/11/tutorial-advanced-random-numbers/)
math.randomseed( os.time() )
local function rollDice( dicePattern )
-- Dice pattern 3d6+3k3
-- First number : number of dice
-- d : required string
-- Second number : sides to the dice
-- +/- : optional modifier
-- ^/k : optional string; '^' keeps the high values, 'k' keeps the low values
-- Third number : number of dice to keep, i.e. 4d6^3 keeps the best three numbers
local dice = {}
local random = math.random
local total = 0
-- Parse the string
local count, sides, sign, modifier, keepHiLo, keep = string.match( dicePattern, "(%d+)[dD](%d+)([%+%-]*)(%d*)([%^k]*)(%d*)" )
modifier = tonumber(modifier)
keep = tonumber(keep)
if ( modifier == nil ) then
modifier = 0
end
if ( sign == "-" and modifier > 0 ) then
modifier = modifier * -1
end
for i = 1, count do
dice[i] = random( sides )
end
if ( keep ) then
local function keepCompare( a, b )
return a > b
end
if ( keepHiLo == "k" ) then
table.sort( dice )
else
table.sort( dice, keepCompare )
end
for i = 1, keep do
total = total + dice[i]
end
else
for i = 1, count do
total = total + dice[i]
end
end
total = total + modifier
return total, dice
end
local result, rolls = rollDice( "3d6" )
for i = 1, #rolls do
print( i, rolls[i] )
end
print( result )
result, rolls = rollDice( "4d6+1^3" )
for i = 1, #rolls do
print( i, rolls[i] )
end
print( result )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment