Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Problems With Calling a Table?

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!

1 comment

2

It's not calling a table. It's indexing a table. You call a function.

1 answer

✓ Accepted answer

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.

1 comment

0

Thanks for the help! First time using a dictionary so now I know.

This discussion is preserved as it was. New answers, comments, and votes are closed.