From: Pasi Kallinen Date: Wed, 25 Mar 2020 10:24:02 +0000 (+0200) Subject: Expose core random number functions to lua X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=eec9c2e2091053e9abeb3b090e5026b71bd09225;p=nethack Expose core random number functions to lua Expose nh.rn2() and nh.random() to lua. Add a math.random() compatibility shim to nhlib.lua --- diff --git a/dat/nhlib.lua b/dat/nhlib.lua index 5cd1e6cf2..fb35acd1c 100644 --- a/dat/nhlib.lua +++ b/dat/nhlib.lua @@ -1,5 +1,16 @@ -math.randomseed( os.time() ) +-- compatibility shim +math.random = function(...) + local arg = {...}; + if (#arg == 1) then + return 1 + nh.rn2(arg[1]); + elseif (#arg == 2) then + return nh.random(arg[1], arg[2] + 1 - arg[1]); + else + -- we don't support reals + error("NetHack math.random requires at least one parameter"); + end +end function shuffle(list) for i = #list, 2, -1 do diff --git a/doc/lua.adoc b/doc/lua.adoc index 0677a9211..dff865cd7 100644 --- a/doc/lua.adoc +++ b/doc/lua.adoc @@ -158,6 +158,23 @@ Example: nh.pline("Message text to show."); +=== random + +Generate a random number. + +Example: + + nh.random(10); -- returns a number between 0 and 9, inclusive. + nh.random(1,5); -- same as 1 + nh.random(5); + +=== rn2 + +Generate a random number. + +Example: + + nh.rn2(10); -- returns a number between 0 and 9, inclusive. + === s_suffix Return a string converted to possessive. diff --git a/src/nhlua.c b/src/nhlua.c index 358d50925..0e5fb08de 100644 --- a/src/nhlua.c +++ b/src/nhlua.c @@ -30,6 +30,8 @@ static int FDECL(nhl_makesingular, (lua_State *)); static int FDECL(nhl_s_suffix, (lua_State *)); static int FDECL(nhl_ing_suffix, (lua_State *)); static int FDECL(nhl_an, (lua_State *)); +static int FDECL(nhl_rn2, (lua_State *)); +static int FDECL(nhl_random, (lua_State *)); static int FDECL(nhl_meta_u_index, (lua_State *)); static int FDECL(nhl_meta_u_newindex, (lua_State *)); static int FDECL(nhl_u_clear_inventory, (lua_State *)); @@ -615,6 +617,39 @@ lua_State *L; return 1; } +/* rn2(10) */ +static int +nhl_rn2(L) +lua_State *L; +{ + int argc = lua_gettop(L); + + if (argc == 1) + lua_pushinteger(L, rn2(luaL_checkinteger(L, 1))); + else + nhl_error(L, "Wrong args"); + + return 1; +} + +/* random(10); -- is the same as rn2(10); */ +/* random(5,8); -- same as 5 + rn2(8); */ +static int +nhl_random(L) +lua_State *L; +{ + int argc = lua_gettop(L); + + if (argc == 1) + lua_pushinteger(L, rn2(luaL_checkinteger(L, 1))); + else if (argc == 2) + lua_pushinteger(L, luaL_checkinteger(L, 1) + rn2(luaL_checkinteger(L, 2))); + else + nhl_error(L, "Wrong args"); + + return 1; +} + /* get mandatory integer value from table */ int get_table_int(L, name) @@ -787,6 +822,8 @@ static const struct luaL_Reg nhl_functions[] = { {"s_suffix", nhl_s_suffix}, {"ing_suffix", nhl_ing_suffix}, {"an", nhl_an}, + {"rn2", nhl_rn2}, + {"random", nhl_random}, {NULL, NULL} };