lua-users home
lua-l archive

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

On Tue, Nov 28, 2017 at 11:09 AM, Abhishek Ranjan
<> wrote:
> 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 you call os.time() twice (one for each client), there is no
guarantee that it will return the same value twice.

> Any suggestions ?

You need some mechanism to have the two function invocation receive
the same seed. You can use os.time(), but you need to call it only
once for your two clients, and somehow pass the value to the two
function calls. If you don't see how to do that please tell us how
your function is called.