-1

What i want to do,is print random elements from array,heres example code:

myTable = { "one", "two", "three","four"}

-- print here: one,three,four

Promeheus
  • 7
  • 2
  • Welcome to StackOverflow. Please take a moment to read the guidelines in the Help Center for asking Questions on the site. SO is not a code writing service or tutorial site. You're expected to have done some basic research and show what you've tried, explainng how it hasn't worked. This is missing in your question. – Cindy Meister Feb 14 '16 at 07:04
  • Can you define how many elements should be printed? Or do you mean to print random elements in random order and a random amount of them from 0 to n where n is amount of elements? – Rochet2 Feb 14 '16 at 10:23

2 Answers2

1

Printing random element is simple -- print(myTable[math.random(#myTable)]) -- but if you need to make each printed element unique, then you better shuffle the elements in the array and print the resulting elements one-by-one. You may check this SO answer for ideas.

Community
  • 1
  • 1
Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
  • Thanks for answer,but I actually need elements not element(multiple of them) printing out.Could u give some example of this? – Promeheus Feb 14 '16 at 07:23
  • You can put that `print` in a loop: `for i = 1, 3 do print(myTable[math.random(#myTable)]) end`. Note that some of the randomly picked elements may be the same. – Paul Kulchenko Feb 14 '16 at 19:30
1

If you want N amount of elements, you need to make use of a loop:

local myTable = { "one", "two", "three","four"}
local result = {}
for i=1,3 do -- N here, e.g 3 if you want 3 elements
    result[i] = table.remove(myTable,math.random(#myTable))
end
print(table.concat(result,", "))
-- "four, two, three" as an example

The code will error if you request more elements than there are in the table. If you want to reuse the table later on, you'll have to copy it, as this code actually removes elements from the table.

EinsteinK
  • 745
  • 3
  • 8