make wesnoth.random avaiable in for lua map gerneration

It has the same interface as math.random and the normal wesnoth.random
that is used in games.
This commit is contained in:
gfgtdf 2016-02-08 21:10:38 +01:00
parent 12b40cf458
commit 80a99f828c
2 changed files with 46 additions and 0 deletions

View file

@ -28,6 +28,7 @@
#include "lua/lauxlib.h"
#include "lua/lua.h"
#include "scripting/push_check.hpp"
static lg::log_domain log_mapgen("mapgen");
#define ERR_NG LOG_STREAM(err, log_mapgen)
@ -37,6 +38,38 @@ static lg::log_domain log_mapgen("mapgen");
struct lua_State;
/**
* Returns a random numer, same interface as math.random.
*/
static int intf_random(lua_State *L)
{
boost::mt19937& rng = lua_kernel_base::get_lua_kernel<mapgen_lua_kernel>(L).get_default_rng();
if(lua_isnoneornil(L, 1)) {
double r = double (rng());
double r_max = double (rng.max());
lua_push(L, r / (r_max + 1));
return 1;
}
else {
int32_t min;
int32_t max;
if(lua_isnumber(L, 2)) {
min = lua_check<int32_t>(L, 1);
max = lua_check<int32_t>(L, 2);
}
else {
min = 1;
max = lua_check<int32_t>(L, 1);
}
if(min > max) {
return luaL_argerror(L, 1, "min > max");
}
lua_push(L, min + static_cast<int>(rng() % (max - min + 1)));
return 1;
}
}
/**
* Finds a path between two locations.
* - Args 1,2: source location.
@ -83,12 +116,14 @@ static int intf_find_path(lua_State *L)
mapgen_lua_kernel::mapgen_lua_kernel()
: lua_kernel_base(NULL)
, random_seed_()
, default_rng_()
{
lua_State *L = mState;
lua_settop(L, 0);
static luaL_Reg const callbacks[] = {
{ "find_path", &intf_find_path },
{ "random", &intf_random },
{ NULL, NULL }
};
@ -154,3 +189,11 @@ boost::uint32_t mapgen_lua_kernel::get_random_seed()
return lua_kernel_base::get_random_seed();
}
}
boost::mt19937& mapgen_lua_kernel::get_default_rng()
{
if(!default_rng_) {
default_rng_ = boost::mt19937(get_random_seed());
}
return *default_rng_;
}

View file

@ -18,6 +18,7 @@
#include "scripting/lua_kernel_base.hpp"
#include <boost/optional.hpp>
#include <boost/cstdint.hpp>
#include <boost/random/mersenne_twister.hpp>
class config;
@ -34,9 +35,11 @@ public:
config create_scenario(const char * prog, const config & generator, boost::optional<boost::uint32_t> seed); // throws game::lua_error
virtual boost::uint32_t get_random_seed();
boost::mt19937& get_default_rng();
private:
void run_generator(const char * prog, const config & generator);
boost::optional<boost::uint32_t> random_seed_;
boost::optional<boost::mt19937> default_rng_;
};
#endif