2017-05-29 11 views
1

ランダム質問をqusから得るには、4つの質問のテーブルですか?ルアでテーブルのインデックスをランダムに取得するにはどうすればよいですか?

-- qus = table of questions 
for i = 1 , 4 do 
    qus = {} 
    qus[i] = "what is your name?" 
    qus[i] = "how old are you?" 
    qus[i] = "where are you living?" 
    qus[i] = "what are you doing?" 

    local label = display.newText(qus[i],160,100) 
end 
print(qus[i]) 

-- Prints: 
-- what are you doing 
-- what are you doing 
-- what are you doing 
-- what are you doing 

私はこれを試してみました:

qus[1] = "what is your name?" 
qus[2] = "how old are you?" 
qus[3] = "where are you living?" 
qus[4] = "what are you doing?" 

label = all qus shows 

を助けることができる誰もいただきありがとうございます。

答えて

4

使用math.random()関数:

local qus = {} 

qus[1] = "what is your name?" 
qus[2] = "how old are you?" 
qus[3] = "where are you living?" 
qus[4] = "what are you doing?" 

math.randomseed(os.time()) -- init generator 

local index = math.random(#qus) -- between 1 and 4 (size of table) 
print(qus[index]) 
+0

だけの明確化: 'math.randomseed(os.time()) - INIT generator'アプリの起動時に一度呼び出されなければなりません。 'math.random'呼び出しの前に呼び出す必要はありません –

関連する問題