如何在lua中调用一个随机函数?
How to call a random function in lua?
如果if语句为真,我想调用一个随机函数怎么办?
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
您是否考虑过将这些函数放在 table 中并为要执行的函数选择随机索引?例如:
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
如果if语句为真,我想调用一个随机函数怎么办?
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
您是否考虑过将这些函数放在 table 中并为要执行的函数选择随机索引?例如:
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