0

I'm trying to make a randomized table that takes up less code space for organization.

Current code:

math.randomseed(tick())
local MyTable = {math.random(0, 100), math.random(0, 100), math.random(0, 100), math.random(0, 100)}

for i, v in ipairs(MyTable) do
    print(i.."- "..v)
end

expected output:

1- some random number
2- a different random number
3- a different random number
4- a different random number

This does give me the output I want but the length of line 3 local MyTable = {...} is annoying to deal with so I was wondering if there was a way I could assign a variable to give a random number and put that in place of each table index.

I already tested this btw:

math.randomseed(tick())
local rand = math.random(0, 100)
local MyTable = {rand, rand, rand, rand}

for i, v in ipairs(MyTable) do
    print(i.."- "..v)
end

The issue with this is that because rand is a pre-defined variable, it outputs the same number for each index.

If you have a solution it would be very helpful as I'm trying to work with 30 index long randomized tables and it is very difficult to go through. Thanks.

1

1 Answer 1

1

To specifically answer your question, "can you assign a variable to give a random number", you can save a function to a variable like this :

local rnd = function() return math.random(0, 100) end
local MyTable = { rnd(), rnd(), rnd(), rnd() }

But rather than manually adding these values, why not just use a loop to insert as many entries as you want? While this is a few more lines of code, it is significantly easier to read, and in the long run that might be better.

math.randomseed(tick())

local MyTable = {}

-- generate a bunch of random numbers
local entriesToAdd = 30
for i = 1, entriesToAdd, 1 do
    MyTable[i] = math.random(0, 100)
end

-- print the entries
for i, v in ipairs(MyTable) do
    print(i.."- "..v)
end
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.