lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Nov 28, 2017 06:09, "Abhishek Ranjan" <abhishek@blacklightsw.com> wrote:

Hello All,

I have just started with Lua and I was building a function that generates a random string from a array of strings and returns it to the user.

On the client side I have two clients. when the enter a common room I call this function so that the string returned by the Lua function remains same for both of them.

Here is the Lua function:

local function my_func(parameter1,parameter2)
    local theSeed = os.time()
    math.randomseed(theSeed)

   local my_array1 ={"String1", "String2","String3","String4","String5","String5","String6","String7","String8","String9","String10"}

  local var = my_array1[math.random(table.getn(my_array1))]


  return var

end

But when I execute this code I am getting the common strings at both the clients most of the times, but there are instances where I am getting different strings at each client. 
So I needed an opinion from any Lua expert that is there something wrong with the above function?

Any suggestions ?

Best Regards,

Abhishek

If each client is using the time as a seed, then they'll get different results if their clocks aren't perfectly in sync or they don't call os.time() at the same time. (Also as others mentioned, you only need to set the seed once.)