Attemp to index nil with number

Hello developers, im into learning part of the neural network system. I was creating a code myself, like converting the deep learning code “from pyhton” to lua. I did all things correctly but there’s an error says that 42. line has error. Anybody can help?

function getRandom(min, max)
	return min + math.random() * (max - min)   
end



local bldeger= {{3,   1.5, 1},
        {2,   1,   0},
        {4,   1.5, 1},
        {3,   1,   0},
        {3.5, .5,  1},
        {2,   .5,  0},
        {5.5,  1,  1},
        {1,    1,  0}}


function sigmoid(x)
	return 1/(1+math.exp(-x))
end


function train()
	local denemeler = 10000
	local ogrenmedegeri = 0.1
	
	local w1,w2,b = getRandom(-1,1),getRandom(-1,1),getRandom(-1,1)
	
	for i=0,denemeler,1 do
		local randomtable = bldeger[math.random(1,#bldeger)]
		
		local nntoplam = randomtable[1]*w1+randomtable[2]*w2+b
		
		local tahmin = sigmoid(nntoplam)
		local hedef = randomtable[3]
		
		local maliyet = (tahmin-hedef)*(tahmin-hedef)
		
		if i % 100 == 0 then
			local c=0
			for ina=0, #bldeger, 1 do
				p = bldeger[ina+1]
                                --line that gives the error
				ptahmin = sigmoid(w1*p[1]+w2*p[2]+b)
				c += (ptahmin - p[3])*(ptahmin - p[3])
			end
			
		end
		
		local degerslopesi = 2*(tahmin-hedef)
		local dpred = sigmoid(nntoplam) * (1-sigmoid(nntoplam))
		dzdw1 = randomtable[1]
		dzdw2 = randomtable[2]
		dzdb = 1
		
		dcost = degerslopesi * dpred
		
		dzdw1 = dcost * dzdw1
		dzdw2 = dcost * dzdw2
		dzdb = dcost * dzdb
		
		w1 = w1 - ogrenmedegeri * dzdw1
		w2 = w2 - ogrenmedegeri * dzdw2
		b = b - ogrenmedegeri * dzdb
	end
	return w1, w2, b
	
end

local w1,w2,b = train()

print(sigmoid(w1*4.5+w2*1+b))

It’s saying that you’re trying to index global ‘p’ which is a nil with a number value and since nil has no raw operation in the gettable opcode, and there’s nothing to fallback when indexing nil, the gettable opcode errors.

Also the limit in the for loop, the limit variable is included in Lua(u), unlike in Python, where the stop argument in the range does not include the stop value. The problem stems from that the ina local is above the length of the bledger table so it returns nil.

Start the for loop at 1 (for ina = 1, #bledger do) and replace ina+1 with ina, and ina with ina-1.

2 Likes

Wow, it’s really easy than i thought, thanks for helping.

To add on to what he said, Python begins indices at 0 whereas Luau begins at 1. When this code ran: p = bledger[ina+1] for the very last item, it set p to an index that doesn’t exist. This then through an error when trying to index p with 1 since p became nil.