Arrays Lua/为什么向矩阵添加新元素会覆盖以前添加的元素?
我正在学习Lua,所以我决定尝试实现一个函数,从数组中获取坐标并输出ASCII图片 只要我没有在一条直线上画几个点(纵坐标),一切都很顺利: 它输出这个Arrays Lua/为什么向矩阵添加新元素会覆盖以前添加的元素?,arrays,matrix,lua,overwrite,ascii-art,Arrays,Matrix,Lua,Overwrite,Ascii Art,我正在学习Lua,所以我决定尝试实现一个函数,从数组中获取坐标并输出ASCII图片 只要我没有在一条直线上画几个点(纵坐标),一切都很顺利: 它输出这个 ...X .X.. ..X. ...X 而不是这个 XXXX .X.. ..X. ...X 经过一些调查,我得出了一个结论,除了create\u massible()之外,所有的局部函数都工作得很好。当它放置一个点时,先前添加在同一y轴上的点将被删除 为了澄清,我是如何得出这个结论的: 我只是删除了函数create_massible()并
...X
.X..
..X.
...X
而不是这个
XXXX
.X..
..X.
...X
经过一些调查,我得出了一个结论,除了create\u massible()
之外,所有的局部函数都工作得很好。当它放置一个点时,先前添加在同一y轴上的点将被删除
为了澄清,我是如何得出这个结论的: 我只是删除了函数
create_massible()
并定义了它的massibledrawing
我自己:
local n=nil
drawing={
{1,1,1,1},
{n,1,n,n},
{n,n,1,n},
{n,n,n,1},
}
程序输出我想要的东西
完整代码 我可以只保留函数
create_massible()
,因为只需要修复它,但我认为完整的代码会更有帮助:
功能图(坐标、符号、spc)
局部sym=sym或“X”--点
本地spc=spc或“-”-空插槽
局部最大值={}——包含最大坐标的质量
局部最小={}——包含最小坐标的大规模
局部图形={}--包含大量图形
局部函数find_min_max()
--查找最小/最大坐标
对于i=1,#coords做
局部c=坐标[i]
如果i%2~=0,那么
max.x=max.x和((c>max.x)和c或max.x)或c
最小x=最小x和((cmax.y)和c或最大y)或c
min.y=min.y和((cdrawing[y]={[x]=1}
使用单个条目创建新行
尝试drawing[y][x]=1
我尝试过,但它输出了一个错误:lua5.3:source\u文件。lua:33:尝试索引一个空值(字段“?”)堆栈回溯:source\u文件。lua:33:在本地“create\u massible”源文件中。lua:70:在函数“draw”源文件中。lua:77:在主块[C]:in?中,所以我添加了drawing[y]={}
在绘图[y][x]=1之前,但它没有帮助。@ViChyavIn-绘图[y]=绘图[y]或{};绘图[y][x]=1
function draw(coords,sym,spc)
local sym = sym or "X" -- dot
local spc = spc or "-" -- empty slot
local max={} -- massive containing max co-ordinates
local min={} -- massive containing min co-ordinates
local drawing={} -- massive containing drawing
local function find_min_max()
-- finds min/max co-ordinates
for i=1,#coords do
local c=coords[i]
if i%2~=0 then
max.x=max.x and ((c>max.x) and c or max.x) or c
min.x=min.x and ((c<min.x) and c or min.x) or c
else
max.y=min.y and ((c>max.y) and c or max.y) or c
min.y=min.y and ((c<min.y) and c or min.y) or c
end
end
end
local function create_massive()
-- creates massive containing drawing
for i=2,#coords,2 do
local y=coords[i]
local x=coords[i-1]
drawing[y]={[x]=1} -- the thing is, it overwrites previous dots' position, so line can contain only the last called dot
end
end
local function print_drawing()
local n=1
local line={}
for i=min.y,max.y do
if drawing[i] then
for k=min.x,max.x do
if drawing[i][k] then
line[n]=line[n] and line[n]..sym or sym
else
line[n]=line[n] and line[n]..spc or spc
end
if k==max.x then
n=n+1
end
end
else
for p=min.x,max.x do
line[n]=line[n] and line[n]..spc or spc
end
n=n+1
end
end
for i=1,#line do
print(line[i])
end
end
find_min_max()
create_massive() -- probably this function works incorrect
print_drawing()
end
m={1,1,2,1,3,1,4,1,2,2,3,3,4,4} -- co-ordinates: even indexes of the array are y, others are x
draw(m) -- main function is called