From 532c4887bc01e8e4fbf2c0f43e421e7a315a28f4 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Tue, 16 Sep 2025 20:27:07 +0300 Subject: [PATCH] add Random class --- res/modules/internal/random_generator.lua | 35 ++++++++++++++++++++++ res/scripts/stdmin.lua | 2 ++ src/logic/scripting/lua/libs/librandom.cpp | 2 +- 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 res/modules/internal/random_generator.lua diff --git a/res/modules/internal/random_generator.lua b/res/modules/internal/random_generator.lua new file mode 100644 index 00000000..0c9073cc --- /dev/null +++ b/res/modules/internal/random_generator.lua @@ -0,0 +1,35 @@ +local Random = {} + +local M = 2 ^ 31 +local A = 1103515245 +local C = 12345 + +function Random.randint(self) + self._seed = (A * self._seed + C) % M + return self._seed +end + +function Random.random(self, a, b) + local num = self:randint() % M / M + if b then + return math.floor(num * (b - a + 1) + a) + elseif a then + return math.floor(num * a + 1) + else + return num + end +end + +function Random.seed(self, number) + if type(number) ~= "number" then + error("number expected") + end + self._seed = number +end + +return function(seed) + if seed and type(seed) ~= "number" then + error("number expected") + end + return setmetatable({_seed = seed or random.random(M)}, {__index = Random}) +end diff --git a/res/scripts/stdmin.lua b/res/scripts/stdmin.lua index 669d5874..742c9506 100644 --- a/res/scripts/stdmin.lua +++ b/res/scripts/stdmin.lua @@ -668,3 +668,5 @@ end bit.compile = require "core:bitwise/compiler" bit.execute = require "core:bitwise/executor" + +random.Random = require "core:internal/random_generator" diff --git a/src/logic/scripting/lua/libs/librandom.cpp b/src/logic/scripting/lua/libs/librandom.cpp index 0560d6f2..192f83d1 100644 --- a/src/logic/scripting/lua/libs/librandom.cpp +++ b/src/logic/scripting/lua/libs/librandom.cpp @@ -12,7 +12,7 @@ static int l_random(lua::State* L) { std::uniform_real_distribution<> dist(0.0, 1.0); return lua::pushnumber(L, dist(randomEngine)); } else if (argc == 1) { - std::uniform_int_distribution dist(0, lua::tointeger(L, 1)); + std::uniform_int_distribution dist(1, lua::tointeger(L, 1)); return lua::pushinteger(L, dist(randomEngine)); } else { std::uniform_int_distribution dist(