2

Basically what i want is:

local X, Y, Z = math.random()

Without assigning each value to math.random():

local X, Y, Z = math.random(), math.random(), math.random()
Deludank
  • 43
  • 6

3 Answers3

4

There is no need to build an intermediate table though; you can simply write a recursive function to generate the vararg:

local function rand(n)
    if n == 1 then return math.random() end
    return math.random(), rand(n-1)
end

shorter (and possibly faster); also doesn't create a garbage table; even better, you could generalize this:

local function rep(func, n)
    if n == 1 then return func() end
    return func(), rep(func, n-1)
end

then use as follows:

local x, y, z = rep(math.random, 3)
Luatic
  • 8,513
  • 2
  • 13
  • 34
  • 1
    _"and possibly faster"_ Why? – Zakk May 07 '22 at 17:23
  • 3
    @Zakk because your function does more work: it first builds a table (using `table.insert` calls which index `_G` and `table`) only to unpack it; I'm not quite sure how this would perform in Roblox, but in the expected use case of few random variables (~ 10 in my benchmarking) my function performs better (at least when using LuaJIT): `0.142702` vs `0.512701` for LuaJIT, `1.00099` vs `2.280177` for PUC Lua 5.1, all numbers in seconds of CPU time spent (`os.clock()`), benchmarking code used is `for i = 1, 1e6 do local _ = rand(10) end`. – Luatic May 07 '22 at 17:45
  • 1
    For the record, your solution is ~4.5x faster on PUC-Lua with minimal change across 5.1 to 5.4. (FX6300 @ 4Ghz). Your recursive solution takes around 400ms to make 3 random numbers 1,000,000 times, @Zakk solution takes around 2 seconds. – wellinthatcase May 07 '22 at 18:33
3

You can write a function that does that for you:

local function rand(n)
    local res = {}
    for i = 1, n do
        table.insert(res, math.random())
    end
    return table.unpack(res)
end

And call it like that:

local X, Y, Z = rand(3) -- Get 3 random numbers
print(X, Y, Z)
Zakk
  • 1,935
  • 1
  • 6
  • 17
0

math.random() only returns one number, but you can just set one variable to be the result of math.random(), then set the others based on some mathematical operation of the variable you assigned to be math.random().

For instance:

local x = math.random()
local y = x * 5
local z = y - x

y and z are still "random" values because they're indirectly generated from math.random().

fireshadow52
  • 6,298
  • 2
  • 30
  • 46