如何在Lua中获得表的随机索引?

如何在Lua中获得表的随机索引?,lua,coronasdk,Lua,Coronasdk,我如何从qus中获得一个随机问题,一个包含四个问题的表格 -- 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 = displa

我如何从
qus
中获得一个随机问题,一个包含四个问题的表格

-- 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 
谢谢您的帮助。

使用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])
使用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])

只是澄清一下:
math.randomseed(os.time())--init generator
应该在应用程序启动时调用一次。无需在每次调用math.random之前调用它。只需澄清:
math.randomseed(os.time())--init generator
应在应用程序启动时调用一次。无需在每次调用math.random之前调用它