The Battle for Wesnoth 1.21.0-dev
 
Loading...
Searching...
No Matches
lua_mathx.cpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2014 - 2025
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
18#include "random.hpp"
19
20
21#include <cmath>
22
23namespace lua_mathx {
24
25/**
26* Returns a random number, same interface as math.random.
27*/
28static int intf_random(lua_State* L)
29{
30 if (lua_isnoneornil(L, 1)) {
31 double r = static_cast<double>(randomness::generator->next_random());
32 double r_max = static_cast<double>(std::numeric_limits<uint32_t>::max());
33 lua_push(L, r / (r_max + 1));
34 return 1;
35 }
36 else {
37 int32_t min;
38 int32_t max;
39 if (lua_isnumber(L, 2)) {
40 min = lua_check<int32_t>(L, 1);
41 max = lua_check<int32_t>(L, 2);
42 }
43 else {
44 min = 1;
45 max = lua_check<int32_t>(L, 1);
46 }
47 if (min > max) {
48 return luaL_argerror(L, 1, "min > max");
49 }
50 lua_push(L, randomness::generator->get_random_int(min, max));
51 return 1;
52 }
53}
54
55static int intf_round(lua_State* L) {
56 double n = lua_tonumber(L, 1);
57 lua_pushinteger(L, std::round(n));
58 return 1;
59}
60
61int luaW_open(lua_State* L) {
62 auto& lk = lua_kernel_base::get_lua_kernel<lua_kernel_base>(L);
63 lk.add_log("Adding mathx module...\n");
64 static luaL_Reg const math_callbacks[] = {
65 { "random", &intf_random },
66 { "round", &intf_round },
67 { nullptr, nullptr },
68 };
69 lua_newtable(L);
70 luaL_setfuncs(L, math_callbacks, 0);
71 // Set the mathx metatable to index the math module
72 lua_createtable(L, 0, 1);
73 lua_getglobal(L, "math");
74 lua_setfield(L, -2, "__index");
75 lua_setmetatable(L, -2);
76 return 1;
77}
78
79}
uint32_t next_random()
Provides the next random draw.
Definition random.cpp:84
static int intf_round(lua_State *L)
Definition lua_mathx.cpp:55
static int intf_random(lua_State *L)
Returns a random number, same interface as math.random.
Definition lua_mathx.cpp:28
int luaW_open(lua_State *L)
Definition lua_mathx.cpp:61
rng * generator
This generator is automatically synced during synced context.
Definition random.cpp:60
void lua_push(lua_State *L, const T &val)
static map_location::direction n