I am trying to generate 5 random non duplicate values between 0,500 and assign them to 5 variables using Lua.
So far I have used the following code which unsuccessfully attempts to generate the random numbers and assigns the values. The problem is:
Can you please help me with this.
Example:
v_Name = "x-"
for i =1, 5 do
X = math.random (0, 500)
v_Name = v_Name..(i)
print (v_Name)
print (X)
end
Here is a solution, clarified in the comments:
math.randomseed( os.time() ) -- first, sets a seed for the pseudo-random generator
local function my_random (t,from, to) -- second, exclude duplicates
local num = math.random (from, to)
if t[num] then num = my_random (t, from, to) end
t[num]=num
return num
end
local t = {} -- initialize table with not duplicate values
local v_Name = "x-"
for i =1, 5 do
X = my_random (t, 0, 500)
v_Name = v_Name .. i -- It is better to use the table here and concatenate it after..
print (v_Name, "=" ,X)
end