lua-users home
lua-l archive

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

On Tue, Nov 28, 2017 at 8:40 AM, Rena <> wrote:
> On Nov 28, 2017 06:09, "Abhishek Ranjan" <> 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?

If I am reading this correctly, you are seeding math.random, then
asking the system to return a random item from the array. It seems to
me that the bug is getting the same value on both clients (based
solely on my understanding of why you would use random).

The questions that I can see are:
Is there a reason you are using random and expecting uniformity?
Are you getting items outside the scope of the list?
Are you *expecting* it to return the EXACT string from both clients at
any given time?

If you could give use a "use case" (i.e. definitive example of what
you expect) of how the code is *supposed* to function, someone may be
able to suggest a better pattern.



> 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.)