The Battle for Wesnoth  1.17.23+dev
lua_mathx.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2014 - 2023
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 #include "scripting/lua_mathx.hpp"
17 #include "scripting/lua_common.hpp"
18 #include "scripting/push_check.hpp"
19 #include "random.hpp"
20 #include "SDL2/SDL_timer.h" // for SDL_GetTicks
21 
22 #include "lua/lauxlib.h"
23 
24 #include <cstdio>
25 #include <cmath>
26 
27 namespace lua_mathx {
28 
29 /**
30 * Returns a random number, same interface as math.random.
31 */
32 static int intf_random(lua_State* L)
33 {
34  if (lua_isnoneornil(L, 1)) {
35  double r = static_cast<double>(randomness::generator->next_random());
36  double r_max = static_cast<double>(std::numeric_limits<uint32_t>::max());
37  lua_push(L, r / (r_max + 1));
38  return 1;
39  }
40  else {
41  int32_t min;
42  int32_t max;
43  if (lua_isnumber(L, 2)) {
44  min = lua_check<int32_t>(L, 1);
45  max = lua_check<int32_t>(L, 2);
46  }
47  else {
48  min = 1;
49  max = lua_check<int32_t>(L, 1);
50  }
51  if (min > max) {
52  return luaL_argerror(L, 1, "min > max");
53  }
54  lua_push(L, randomness::generator->get_random_int(min, max));
55  return 1;
56  }
57 }
58 
59 static int intf_round(lua_State* L) {
60  double n = lua_tonumber(L, 1);
61  lua_pushinteger(L, std::round(n));
62  return 1;
63 }
64 
65 int luaW_open(lua_State* L) {
66  auto& lk = lua_kernel_base::get_lua_kernel<lua_kernel_base>(L);
67  lk.add_log("Adding mathx module...\n");
68  static luaL_Reg const math_callbacks[] = {
69  { "random", &intf_random },
70  { "round", &intf_round },
71  { nullptr, nullptr },
72  };
73  lua_newtable(L);
74  luaL_setfuncs(L, math_callbacks, 0);
75  // Set the mathx metatable to index the math module
76  lua_createtable(L, 0, 1);
77  lua_getglobal(L, "math");
78  lua_setfield(L, -2, "__index");
79  lua_setmetatable(L, -2);
80  return 1;
81 }
82 
83 }
uint32_t next_random()
Provides the next random draw.
Definition: random.cpp:85
static int intf_round(lua_State *L)
Definition: lua_mathx.cpp:59
static int intf_random(lua_State *L)
Returns a random number, same interface as math.random.
Definition: lua_mathx.cpp:32
int luaW_open(lua_State *L)
Definition: lua_mathx.cpp:65
rng * generator
This generator is automatically synced during synced context.
Definition: random.cpp:61
void lua_push(lua_State *L, const T &val)
Definition: push_check.hpp:373
static map_location::DIRECTION n