Attempting to index a nil value

A beginner for Lua (and programming) here. I am trying to create a table and populate it with random integers, but I keep getting "trying to index the zero value". I previously neglected to define a table, so when I searched here I found this solution and added it to map = { }

. Unfortunately this did not solve the problem.

I suspect that the loop is trying to put random values ​​into an undefined table and that is simply not possible. How could I then put an arbitrary number of random numbers into the table?

Here is my code:

map = { }

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

      

+3


source to share


2 answers


The problem is that it is map[k]

initially zero. To get the desired result, create a table at this index if it doesn't 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

      

+4


source


I would suggest 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

      

+2


source







All Articles