Table returning 3 values instead of 1

Currently I have been trying to make a script where a table gets looped through and out of that table 1 value gets picked randomly. Instead, I get 3 values! I only want 1 value to appear. I tried searching for this problem but did not find an answer. The problems were similar, but not exact.

Here is the script:

local vegetables = {"Carrots", "Potatos", "Salad"}

for index = 1, #vegetables do
	local random = vegetables[math.random(1, #vegetables)]

If I’m understanding correctly, you’re getting three different printed lines. That’s because you’re using a for loop which does the random picker 3 times. You can have it do it once by removing the for loop.


It works! But how? You first need to loop through a table to get a value or no?


Nope! You can get the length of a table/array and a value within one without having to iterate through it.

Dictionaries though are a bit more funky and require loops to know their length, which might be what you’re thinking of.


Ye, maybe I was thinking about dictionaries. Anyway, thanks for helping out!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.