---------------------------------------------------------------- -- -- dice.lua -- -- Copyright (C) 2002 Ian King -- All Rights Reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that this entire copyright notice -- is duplicated in all such copies. -- -- This software is provided "as is" and without any expressed or implied -- warranties, including, without limitation, the implied warranties of -- merchantibility and fitness for any particular purpose. -- ---------------------------------------------------------------- -- salt the random number generator from the date and time math.randomseed(tonumber(os.date("%m%d%H%M%S"))) -- make a nice module dice = {} -- coin flipper function dice.FlipCoin(flips) local sum = 0, i flips = flips or 1 -- if argument missing flip once for i = 1, flips do sum = sum + math.random(0,1) end return sum end -- roll some dice function dice.Roll(rolls, sides) local sum = 0, i for i = 1, rolls do sum = sum + math.random(sides) end return sum end -- Create a function to evaluate expressions like "3d4 + 5D100 - 1" function dice.DiceFunction(str) assert(str ~= "", "Dice String Empty") return loadstring("return "..string.gsub(str, "(%d+)[dD](%d+)", "dice.Roll(%1, %2)"), "dice.DiceFunction") end -- The End ----------------------------------------------------- -- vvvvvvvvvvvvvvvvvvvv Cut Here vvvvvvvvvvvvvvvvvvvvvvv -- example code Attrib = dice.DiceFunction("3d6") Attack = dice.DiceFunction("10+1d20+3D8") Complex = dice.DiceFunction("(3d7 / 3.14159) + Attack()") function hit() if Attack() >= 35 then return "Hit" else return "Missed" end end print("One Hundred Coins", dice.FlipCoin(100)) print("One Hundred Coins", dice.FlipCoin(100)) print("One Hundred Coins", dice.FlipCoin(100)) print("One Coin", dice.FlipCoin(1)) print("One Coin", dice.FlipCoin()) -- one flip if no argument print("str", Attrib()) print("int", Attrib()) print("dex", Attrib()) print("Attack", hit()) print("Attack", hit()) print("Attack", hit()) print("Attack", hit()) print("Complex", Complex()) print("Complex", Complex()) print("Complex", Complex()) print("Complex", Complex()) print("Complex", Complex()) -- ^^^^^^^^^^^^^^^^^^^^ Cut Here ^^^^^^^^^^^^^^^^^^^^^^^