2016-11-30 4 views
1

if文がtrueのときにランダム関数を呼び出す場合はどうすればよいですか?ルアでランダム関数を呼び出すには?

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

ローカル{ next_move() ' –

答えて

5

私は、これらの機能をテーブルに入れて、実行する関数のランダムインデックスを選択すると考えましたか?たとえば、次のようなものです。

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

関連する問題