【问题标题】:How do I get a random index of a table in Lua?如何在 Lua 中获取表的随机索引?
【发布时间】:2017-10-29 20:02:39
【问题描述】:

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

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

【问题讨论】:

    标签: lua coronasdk


    【解决方案1】:

    使用 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 调用之前调用它
    猜你喜欢
    • 2015-03-08
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 2019-03-16
    • 2013-03-30
    • 1970-01-01
    • 2015-07-11
    • 2021-02-21
    相关资源
    最近更新 更多