Getting a random value out of a table

I’m trying to get a random value out of a table I had that includes seats and checks which is available and not however when I try to get it I get an error saying
bad argument #2 to ‘random’ (interval is empty)

and I’m just unable to fix it?
Script:

-- table
local seats = {
	seat1 = false,
	seat2 = false,
	seat3 = false,
	seat4 = false,
	seat5 = false,
	seat6 = false,
	seat7 = false,
	seat8 = false,
	seat9 = false,
	seat10 = false,
	seat11 = false,
	seat12 = false
}

-- random value script
local Rand = math.random(1,#seats)
local seat = seats[Rand]
print(seat)

How can I fix this?

6 Likes

The issue is that this is a dictionary, dictionaries use keys and not numbered indexes.

And, if I’m not mistaken, using the # operator on a dictionary returns 0 (as it returns the number of indexes, I think)

But, there’s an easy way to get this to work with your current scenario:

local index = math.random(1, 12) --//Pick a random number because there are 12 seats available
local the_seat = seats["seat"..index] --//Access the key in the dictionary based on number drawn
--//Do stuff with 'the_seat'

Should work. :slight_smile:

12 Likes

EDIT : Didn’t notice it was a dictionary ( Didn’t read the actual post oops )

1 Like

That will result into the error I posted in the post as its a dictionary as @C_Sharper said.

1 Like

When I try to do that and print the variable, it prints false. How can I get the string itself?

The key itself would be the string.

So if you just wanted to use the string, use the key directly:

local index = math.random(1, 12)
local key = "seat"..index --/Use this as the string

Yea I wanted to do that but realized that then I wouldn’t be able to get if the seat is true or false from the table which is kind of useless.

You can though. the key variable is the key that was randomly chosen from the table. If at any point you want to check and see what that key is pointing to in the table, just read from the table with that key:

print(seats[key]) 
2 Likes

Oh yeah, didn’t think about that. Tysm!

2 Likes

How would we get get two values from the index?

Well there’s a couple things you could do.

You could use parallel arrays, which just means two separate tables with corresponding indices in them.

So an example could be:

local customers = {"Ron", "Jack"};
local customerBalances = {45, 92};

local customerIndex = 1

local currentCustomer = customers[customerIndex]
local currentCustomerBalance = customerBalances[customerIndex]
--//It's called parallel because the values in both tables refer to the same index

Another thing you could do is use nested tables (tables within tables) to store multiple values at each index.

local nestedTable = { {1, 2, 3} }

local someTable = nestedTable[1]

print(someTable[1])

Hope this helps.

1 Like