在已经有键的表中获取值的索引(选择一个随机键/值对)

我想从一个表中选择一个随机键/值对,但使用 math.random() 不起作用。

--初始化随机化
math.randomseed(os.time()+30) --基于时间设置随机种子
math.random(); math.random(); math.random(); --清除预设

local phrases = {
["a"] = 3
["b"] = 7
["d"] = 4
["f"] = 8
["p"] = 5
}

local phrase = phrases[math.random(1,5)]

phrase 总是输出为 nil。有没有一种方法可以获取与 math.random() 一起使用的索引或者我可以使用的替代方法?

点赞
用户4567755
用户4567755

math.random(1,5) 返回从1到5的数字。你的键是字符串。

你可以创建一个表格 (如: 数组-整数键), 从中获取一个随机键, 然后访问 phrases:

local phrases = {
  ["a"] = 3,
  ["b"] = 7,
  ["d"] = 4,
  ["f"] = 8,
  ["p"] = 5
}

local keys = {}

for k in pairs(phrases) do
  table.insert(keys, k)
end

local random_key = keys[math.random(1,5)] -- 其中之一: "a", "b", "d", "f", "p"
local phrase = phrases[random_key] -- 其中之一: 3, 7, 4, 8, 5
2019-11-07 14:22:09