ahmed bouchaala
ahmed bouchaala

Reputation: 65

Can we limit the scope of srand

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

Upvotes: 1

Views: 757

Answers (2)

lhf
lhf

Reputation: 72362

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.

Upvotes: 1

astraujums
astraujums

Reputation: 754

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.

Upvotes: 0

Related Questions