如何在lua中调用一个随机函数?

问题描述:

如果我想在if语句为真时调用随机函数,该怎么办?如何在lua中调用一个随机函数?

local function move() end 
local function move2() end 
local function move3() end 

if (statement) then 
//make it choose a random function from the three which are above 
end 
+4

'local next_move =({move,move2,move3})[math.random(3)]; next_move()' –

您是否考虑过将这些函数放在表格中,并为要执行的函数选择随机索引?例如,如下所示:

local math = require("math") 

function a() 
    print("a") 
end 

function b() 
    print("b") 
end 

function c() 
    print("c") 
end 

function execute_random(f_tbl) 
    local random_index = math.random(1, #f_tbl) --pick random index from 1 to #f_tbl 
    f_tbl[random_index]() --execute function at the random_index we've picked 
end 

-- prepare/fill our function table 
local funcs = {a, b, c} 

-- seed the pseudo-random generator and try executing random function 
-- couple of tens of times 
math.randomseed(os.time()) 
for i = 0, 20 do 
    execute_random(funcs) 
end 
+0

这段代码会报错。在你将它定义为本地之前,你需要调用'f_tbl'。如果在函数之后定义,Lua将不会在块外使用局部变量。 – ATaco

+1

@ATaco''f_tbl'作为'execute_random()'的一个参数传递,所以它与本地/全局范围的范围无关。为了理智和可读性,我会重命名它;) – Kamiccolo

+0

啊,错过了。都好。 – ATaco