I was trying to make a system that picked a random table
inside the main table database
, and print the red string
inside said table. The problem is every time I run the server, this error appears;
ServerScriptService.Script:34: attempt to index global 'pickedWord' (a nil value)
Here's the code:
local database = { word1 = {red = "word1", blue = "word2"}, word2 = {red = "word2", blue = "word3"}, word3 = {red = "word3", blue = "word4"}, } numberofDatabaseItems = 0 for i,v in pairs(database) do numberofDatabaseItems = numberofDatabaseItems + 1 end wait(1) function selectRandom(tbl) math.randomseed(tick()) local chosenNumber = math.random(1, numberofDatabaseItems) local picked = {} print(chosenNumber) local pickedWord for i=1, #database do if database[i] == database[chosenNumber] then print(database[i].red) pickedWord = database[i] else print'Not the word!' end end print(pickedWord) --print(pickedWord.red) return pickedWord.red end local picked = selectRandom(database) wait(1) print(picked)
I'm not very experienced with calling a table inside of another table, so anyone that could offer some help would be awesome!
database
has no length
The issue is simple - database
has a length of 0 because it's a dictionary. This means that
for i=1, #database do
Expands to
for i=1, 0 do
Which clearly doesn't work. Use an iterator for loop instead with pairs so that you can actually iterate over the table.