Skip to content

Instantly share code, notes, and snippets.

@nadar71
Forked from coronarob/dice.lua
Last active August 29, 2015 14:16
Show Gist options
  • Save nadar71/bb0839b1990db1c6737a to your computer and use it in GitHub Desktop.
Save nadar71/bb0839b1990db1c6737a to your computer and use it in GitHub Desktop.
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