]> granicus.if.org Git - nethack/commitdiff
Implement dice and percent as global lua functions
authorcopperwater <aosdict@gmail.com>
Sat, 29 Feb 2020 02:19:50 +0000 (21:19 -0500)
committerPasi Kallinen <paxed@alt.org>
Mon, 6 Apr 2020 16:43:56 +0000 (19:43 +0300)
Intended to simplify many of the math.random calls currently in use, and
make them more semantic and thus more readable.

The dice function d() takes either a two-argument form which is the same
as in the C source (number of dice, faces per die) or a one-argument
form that rolls a single die.

The percent(N) function returns true N% of the time.

dat/nhlib.lua

index fb35acd1c5eae2b7ea5105391a2c339b3427a622..983542b5b388ff0833b4bdcda27133bcde1a0c4b 100644 (file)
@@ -21,3 +21,23 @@ end
 
 align = { "law", "neutral", "chaos" };
 shuffle(align);
+
+-- d(2,6) = 2d6
+-- d(20) = 1d20 (single argument = implicit 1 die)
+function d(dice, faces)
+   if (faces == nil) then
+      -- 1-arg form: argument "dice" is actually the number of faces
+      return math.random(1, dice)
+   else
+      local sum = 0
+      for i=1,dice do
+         sum = sum + math.random(1, faces)
+      end
+      return sum
+   end
+end
+
+-- percent(20) returns true 20% of the time
+function percent(threshold)
+   return math.random(0,99) < threshold
+end