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

时间:2017-05-29 13:29:13

标签: lua corona

如何从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 

感谢任何可以提供帮助的人。

1 个答案:

答案 0 :(得分: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])