lua - lua: attempt to index a nil value (field '?')
问题描述
I'm getting this error in this file:
-- mid point circle drawing algoritm taken from here:
-- https://stackoverflow.com/questions/17163636/filled-circle-in-matrix2d-array
-- code translated from java
-- initates 2d array
matrix = {}
for i = 1, 2 do
matrix[i] = {}
end
-- given matrix and diameter populates array
function mCircle(matrix, d)
local startX = d/2
local startY = d/2
local r = d/2
mCircleRec(matrix, d, startX, startY, r, r)
--prints matrix
for i = 1, d do
for j = 1, d do
print(matrix[x][y])
end
end
end
function mCircleRec(matrix, d, startX, startY, x, y)
if (x >= d or y >= d or x < 0 or y < 0 or matrix[x][y] == 1)
then
return
elseif (matrix[x][y] == 9)
then
return
end
local r = d/2
if (((x - startX) * (x - startX) + (y - startY) * (y - startY)) <= (r * r))
then
matrix[x][y] = 1
else
matrix[x][y] = 9
end
mCircleRec(matrix, d, startX, startY, x+1, y); -- down
mCircleRec(matrix, d, startX, startY, x, y+1); -- right
mCircleRec(matrix, d, startX, startY, x-1, y); --up
mCircleRec(matrix, d, startX, startY, x, y-1); --left
mCircleRec(matrix, d, startX, startY, x-1, y-1); -- diagonal up-left
mCircleRec(matrix, d, startX, startY, x+1, y+1); -- diagonal right-down
mCircleRec(matrix, d, startX, startY, x+1, y-1); -- diagonal left-down
mCircleRec(matrix, d, startX, startY, x-1, y+1); -- diagonal right-up
end
mCircle(matrix, 20)
The complete error message:
lua: circle.lua:27: attempt to index a nil value (field '?')
stack traceback:
circle.lua:27: in function 'mCircleRec'
circle.lua:16: in function 'mCircle'
circle.lua:54: in main chunk
[C]: in ?
This is a simple filled circle algoritm that creates a 2d array and places inside a filled circle, the code was translated from java and the original code is in one of the answers here .
I'm new to lua and I looked in every other question about the same error but none of them was relevant. Thanks in advance for the help
edit: typo
edit: While troubleshooting I discovered another error: I got wrong the 2d array creation and modified it:
- initates 2d array
local radius = 20
local diameter = radius * 2
-- Create a diameter x diameter array
matrix = {}
for i = 1, diameter do
matrix[i] = {}
for j = 1, diameter do
matrix[i][j] = 0 -- Fill the values here
end
end
Changing this didn't change the error message
解决方案
您提供的代码不会导致引用的错误消息。
首先你有这个
local start Y = d/2
你已经修好了
然后有一个损坏的 if 语句
if (x >= d or y >= d or x < 0 or y < 0 or matrix[x][y] == 1) --the error is in this line (27) apparently
then
matrix[x][y] = 1
then
return
elseif (matrix[x][y] == 0)
then
return
end
你有两个then
s
只有在修复了这些错误之后,您才会看到引用的错误。
里面mCircle
x
和y
都是零。所以matrix[x][y]
是不可能的。