1
votes

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

2
Can't you change the c++ function? srand() should be called only once for the whole program. - πάντα ῥεῖ
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
If you can't change either of math.randomseed and c++function, I'm afraid you're out of luck... - Quentin

2 Answers

1
votes

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.

0
votes

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.