Dmytro
Dmytro

Reputation: 17156

Lua: index expected, got nil

Well, I'm very new to lua, LITERALLY today began to study this. So this is my code:

local l = {1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1}

local n = table.getn(l)

local path = {{l[1], 1}}
local index = 1

for i=2,n do    
    if l[i] ~= l[i-1] then
        index = index + 1
        path[index][1] = l[i]
        path[index][2] = 0
    end 
    path[index][2] = path[index][2] + 1 
end

What I want to do is to get path array (table) where zeros and ones should be grouped with their consequent amount. The output should be:

{{1, 1}, {0, 3}, {1, 3}, {0, 8}, {1, 1}}

But the problem is I get index expected, got nil error in line: path[index][1] = l[i] What is wrong with this code? index should be incremented and new item in path array should be created... But it isn't...

Upvotes: 2

Views: 3087

Answers (1)

Craig
Craig

Reputation: 7671

Index is set to to and you are attempting to index into path at position 2, which returns nil. Then you are attempting to set index 1 on nil. You need to create a table at index 2 of path. Try doing this

path[index] = {l[i], 0}

Upvotes: 3

Related Questions