Choose a random item from a table

后端 未结 6 1709
既然无缘
既然无缘 2021-02-03 20:52

My goal is to pick out a random item from a table in Lua.

This is what I\'ve got so far, but it currently does not work:

local myTable = { \'a\', \'b\',          


        
6条回答
  •  悲哀的现实
    2021-02-03 21:17

    Test:

    t = {'a', 'b', 'c'}
    print(t[0])
    

    gives nil. In fact 0 is out of bounds (try t[20])... so random must be from 1 to #myTable (inclusive) because the first element of a table is labeled (indexed) as 1 if you write just exp, see Table constructor ("Finally, fields of the form exp are equivalent to [i] = exp, where i are consecutive integers starting with 1.").

    If you pass to math.random just an argument n, you obtain a random number from 1 to n inclusive. This fixes your example:

    print(myTable[math.random(#myTable)])
    

提交回复
热议问题