Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

Problems With Calling a Table?

Asked by 8 years ago

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!

2
It's not calling a table. It's indexing a table. You call a function. User#6546 35 — 8y

1 answer

Log in to vote
1
Answered by 8 years ago

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.

0
Thanks for the help! First time using a dictionary so now I know. User#9949 0 — 8y
Ad

Answer this question