How do I generate a set of random numbers in both Lua and C # that are the same?
You will need the same code to generate the same random numbers. The Lua library is uncomplicated and submits the job to the C runtime library . This makes it somewhat likely that you will get the same numbers if you use it. Easy to do with pinvoke:
using System.Runtime.InteropServices;
...
public static double LuaRandom() {
const int RAND_MAX = 0x7fff;
return (double)(rand() % RAND_MAX) / RAND_MAX;
}
public static void LuaRandomSeed(int seed) {
srand(seed);
}
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int rand();
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void srand(int seed);
Write a small test program in both Lua and C #, be sure to use LuaRandomSeed () and math.randomseed () so that they start with the same sequence and compare the first ~ 25 numbers they spit out. If you don't get a match, then your Lua implementation is using a different C runtime library and you will have to write your own random number generator. Simple LCG that Microsoft uses:
private static uint seed;
public static int rand() {
seed = seed * 214013 + 2531011;
return (int)((seed >> 16) % RAND_MAX);
}
source to share
You need 2 random generators that use the same algorithm and parameters.
The .NET framework does not guarantee anything about the generator (i.e. it might change in a future version). I don't know much about Lua, but it probably has a standard generator based on a runtime platform with similar vagaries.
Therefore, your most reliable course is to choose an algorithm and implement it on both platforms. And then all you need is a common seed to create identical sequences.
source to share