【发布时间】:2020-12-04 09:43:13
【问题描述】:
所以我在使用 Lua 时遇到了一个奇怪的问题,我使用以下函数来设置、读取和写入名为 Cube 的全局 3D“数组”。然而似乎每次我在读取或写入这个“数组”时,数据只存储在函数使用的实例上,尽管 Cube 是一个全局变量,不能说我以前遇到过这个,很奇怪.
-- stole this one from: https://stackoverflow.com/questions/27976526/using-a-coordinate-pair-as-a-key-in-a-lua-table
-- basically the intended use is to store a 2d table of block information for the level the turtle is on
function setUpLevel()
local test = {_props = {}}
local mt = {}
local function coord2index(x, z)
return ((x-1) * xMax) + z
end
mt.__index = function(s, k)
if s._props[coord2index(k[1], k[2])] ~= nil then
return s._props[coord2index(k[1], k[2])]
end
end
mt.__newindex = function(s, k, v)
s._props[coord2index(k[1], k[2])] = v
end
mt.__call = function (t, k)
if type(k) == "table" then print "Table" end
end
setmetatable(test, mt)
return test
--test[{1,2}] = 5
end
function setupCube()
local cube = {}
cube[relY]=setUpLevel()
return cube
end
Cube = setupCube()
function readCubeData(x,y,z)
if (Cube[y]==nil) then
return nil
end
-- debug
return Cube[y][{x,z}]
end
function storeCubeData(x,y,z,data)
if (readCubeData(x,y,z)==nil) then
Cube[y]=setUpLevel()
end
Cube[y][{x,z}]=data
data= readCubeData(x,y,z)
print (x,",",y,",",z,":",readCubeData(x,y,z))
sleep(.5)
end
输出示例:
storeCubeData() 中的打印语句将提供正确的输出(顺序无关紧要,只是对应于 x、y、z 值的数据)
但是start()中的以下打印语句
function start()
detectAndStore()
print("=============")
sleep(1)
data= readCubeData(0,relY,1)
print (0,",",relY,",",1,":",readCubeData(0,relY,1))
sleep(.5)
data= readCubeData(-1,relY,0)
print (-1,",",relY,",",0,":",readCubeData(-1,relY,0))
sleep(.5)
data= readCubeData(0,y,-1)
print (0,",",relY,",",-1,":",readCubeData(0,relY,-1))
sleep(.5)
data= readCubeData(1,y,0)
print (1,",",relY,",",0,":",readCubeData(1,relY,0))
sleep(.5)
end
start()
这只是悲惨地不正确,x,y,z 值不指向正确的值,并且表格也不意味着在相同的 x,y,z 位置重复。我真的无法为我的生活弄清楚这一点
【问题讨论】:
-
试试
local function coord2index(x, z) return x..";"..z end
标签: lua