Arian Coipel
Arian Coipel

Reputation: 23

lua - Choose random values from a random chosen key

I am trying to randomly choose a key from a table then also randomize a value from that random key.

Example Table

items = {
    ["Rock"] = {min = 1, max = 5},
    ["Sand"] = {min = 4, max = 12},
    ["Glass"] = {min = 20, max = 45},
}

Then this function

function printTable()
    local keys = {} 
    for k,v in pairs(items) do
        table.insert(keys, k)
        local keys = keys[math.random(1, #keys)]
        local amount = math.random(v.min,v.max)
        print(item, amount)
    end
end

It prints a random key, with its values, but then it prints more random keys with less values that don't go with it.

What i am looking to do is, print one of the keys then only the values for said key so,

Sand 6

or

Glass 31

So on so fourth.

Any help would be awesome!

Upvotes: 2

Views: 2680

Answers (2)

Skully
Skully

Reputation: 3126

Because there is no way to obtain the index of a table without predefining it or gathering it through a loop's index, you could create a table which holds the index of each table, and then use that to randomly select which item to use.

local indexes = {"Rock", "Sand", "Glass"}

Use this with your printTable function.

items = {
    ["Rock"] = {min = 1, max = 5},
    ["Sand"] = {min = 4, max = 12},
    ["Glass"] = {min = 20, max = 45},
}

local indexes = {"Rock", "Sand", "Glass"}

function printTable()
    math.randomseed(os.time())
    local index = indexes[math.random(1, 3)] -- Pick a random index by number between 1 and 3.
    print(index .. " " .. math.random(items[index].min, items[index].max))
end

Run Code Snippet

Upvotes: 1

ShaH
ShaH

Reputation: 170

In this piece of code you can see how I go on selecting a random value in the given table. This returns the output you are looking.

math.randomseed(os.time())

local items = {
    ["Rock"] = {min = 1, max = 5},
    ["Sand"] = {min = 4, max = 12},
    ["Glass"] = {min = 20, max = 45},
}

local function chooseRandom(tbl)
    -- Insert the keys of the table into an array
    local keys = {}

    for key, _ in pairs(tbl) do
        table.insert(keys, key)
    end

    -- Get the amount of possible values
    local max = #keys
    local number = math.random(1, max)
    local selectedKey = keys[number]

    -- Return the value
    return selectedKey, tbl[selectedKey]
end

local key, boundaries = chooseRandom(items)
print(key, math.random(boundaries.min, boundaries.max))

Feel free to test it here

Upvotes: 0

Related Questions