1

we are in the context of a lua script which uses some C/C++ functions exported to be used with lua.

In lua, we have

math.randomseed(12) // 12 for example
for i=0, 10 do
    c++function()
    print(math.random())
end

the output is always the same number. When i saw the cause, i found that in the c++_function, there is an srand(0) and some calls to the rand() function.

So our math.randomseed(12) will have no effect, and we will in each iteration have srand(0), the rand() call, and after that the math.random() call(which just call the C rand() function). and because we are giving always the same seed, we have always the same sequence generated.

The question is, is there a solution to make srand(x) limited to a specific scope ? so the rand() call in c++_function will use the seed 0, and when we return back to lua, the math.random() uses the math.randomseed(x).

If no, any one have a suggestion ?

Thank you

  • Can't you change the c++ function? `srand()` should be called only once for the whole program. – πάντα ῥεῖ Jul 03 '15 at 07:51
  • No, because the c++ function call is independant from the lua script, the problem is caused only in this example, because both of them did srand. in another lua script, we can call the c++_function without math.randomseed in lua. – ahmed bouchaala Jul 03 '15 at 08:03
  • 1
    If you can't change either of `math.randomseed` and `c++function`, I'm afraid you're out of luck... – Quentin Jul 03 '15 at 08:07

2 Answers2

1

Unfortunately, srand does not return its current seed. Nevertheless, you can fake it. Try this:

function call_c_function()
    local s=math.random(1,2^30)
    c++function()
    math.randomseed(s)
end

for i=0, 10 do
    call_c_function()
    print(math.random())
end

Just make sure that you don't call math.randomseed before each call to math.random, but only after calling c++function, as above.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • Thx.this will work, but the modification should be in c++ code. we deliver our c++ code to be used in lua scripts by the client. So, i can't act on the choices in their lua files. i saw the code, and , in my opinion, i can delete srand from the c++ function, i made a suggestion and i wait for answer. this will resolve the problem :) – ahmed bouchaala Jul 03 '15 at 12:19
  • @ahmedbouchaala, you can always distribute a tiny Lua file that wraps as above the functions that mess with `srand`. But avoid the mess in the first place is the way to go: `srand` is supposed to be called only once in a program. – lhf Jul 03 '15 at 12:22
0

You probably will not be able to limit the scope of srand() to affect only your invocation of math.random().

I'd suggest to use a random number generator that is independent of the built-in. See Generating uniform random numbers in Lua for an example.

Community
  • 1
  • 1
astraujums
  • 709
  • 8
  • 20