【问题标题】:lua - Choose random values from a random chosen keylua - 从随机选择的键中选择随机值
【发布时间】:2019-07-30 20:03:16
【问题描述】:

我正在尝试从表中随机选择一个键,然后从该随机键中随机化一个值。

示例表

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

然后这个函数

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

它会打印一个随机键及其值,但随后会打印出更多随机键,但会打印出更多随机键,但它的值更少。

我要做的是,打印其中一个键,然后只打印所述键的值,

Sand 6

Glass 31

那么第四个。

任何帮助都会很棒!

【问题讨论】:

  • 您的示例有错误。你打印(item,数量)而不是k。改变后我得到了你想要的输出。岩石 3 沙子 11 玻璃 32。此外,您随机检索物品的方法可能不像您希望的那样随机
  • 有什么技巧可以让它更随机吗?另外,我的意图是只打印 1 个键及其指定值。而不是全部 3 个或多个键。
  • 使用math.randomseed() 生成真正的随机数

标签: lua lua-table


【解决方案1】:

由于没有预先定义或通过循环索引收集表就无法获取表的索引,您可以创建一个包含每个表的索引的表,然后使用它来随机选择要使用的项目.

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

将此与您的 printTable 函数一起使用。

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

【讨论】:

  • 你应该用math.randomseed()解释真正的随机数
【解决方案2】:

在这段代码中,您可以看到我如何继续在给定表中选择随机值。 这将返回您正在查看的输出。

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

请随意测试here

【讨论】:

  • 很好 - 但是如何获得更多的熵呢?我的意思是你的代码,把它放在 rvchk.lua 中并执行for i=0,10 do; dofile 'rvchk.lua'; i=i+1; end; - 这会产生相同输出的 11 倍。我的意思是我们都需要一个更好的解决方案来解决math.randomseed(os.time())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-14
  • 1970-01-01
相关资源
最近更新 更多