Lua函数选择器

我有三个函数。当用户按下'E'键时,我希望它随机选择一个函数,我觉得这与math.random有关,但我想不出来。

点赞
用户1442917
用户1442917

你不使用math.random来选择一个函数;你使用它来选择一个随机数,然后可以将其用作索引从表中获取所需的函数(作为一个例子):

local list = { function() print(1) end, function() print(2) end, function() print(3) end }
math.randomseed(os.time()) -- 别忘了种子,否则你可能会得到相同的序列
for i = 1, 10 do list[math.random(#list)]() end
2015-05-29 18:34:51