Anderswo
Anderswo

Reputation: 43

Attempt to index a nil value

Beginner to Lua (and programming) here. I'm trying to create a table and fill it with random integers, but I keep getting the "attempt to index a nil value" error. I had previously neglected to define the table map, so when I searched around here, I found that solution and added in map = { }. Unfortunately, this didn't fix the issue.

I suspect that the loop is trying to put random values into an undefined table, and that that is just not possible. How would I then go about putting an arbitrary amount of random numbers into a table?

Here is my code so far:

map = { }

for k = 1, 20 do
    for l = 1, 5 do
        map[k][l] = math.random(0,3)
    end
end

Upvotes: 3

Views: 1671

Answers (2)

Alexander Altshuler
Alexander Altshuler

Reputation: 3064

I would offer a simpler version:

map = { }

for k = 1, 20 do
    map[k] = {}    
    for l = 1, 5 do
        map[k][l] = math.random(0,3)
    end
end

Upvotes: 2

user142162
user142162

Reputation:

The issue is that map[k] is initially nil. In order to get the desired result, create a table at that index if one does not already exist:

map = { }

for k = 1, 20 do
    for l = 1, 5 do
        if not map[k] then
            map[k] = {}
        end
        map[k][l] = math.random(0,3)
    end
end

Upvotes: 4

Related Questions