以下函数getTank()
有效(如果不用作打印fluidName
的函数)。当我返回值然后尝试在函数外部访问它们时会出现问题。结果是'attempt to concatenate string and nil'
在行mon2.write(returnedVariable)
处,例如在函数之外。
如果我只是执行以下操作:
for k,v in pairs(tableInfo) do amount=v.amount end
print(amount)
在函数之外,它给出了正确的值。
function getTank(tankPeriph)
-- This has been tested and works
local tableInfo = tankPeriph.getTankInfo("unknown")
local fluidRaw, fluidName, fluidAmount, fluidCapacity
for k,v in pairs(tableInfo) do
fluidRaw = v.rawName
fluidName = v.name
fluidAmount = v.amount
fluidCapacity = v.capacity
end
return fluidRaw, fluidName, fluidAmount, fluidCapacity
end
function dispTanks()
-- working on it
-- TANK 0
mon2.setCursorPos(rowPos, ironTank0Col)
mon2.clearLine()
local fluidRaw, fluidName, fluidAmount, fluidCapacity = getTank(irontank0)
mon2.write("Iron Tank 0 (" .. fluidName .. ") : " .. fluidAmount)
-- TANK 1
mon2.setCursorPos(rowPos, ironTank1Col)
mon2.clearLine()
local fluidRaw, fluidName, fluidAmount, fluidCapacity = getTank(irontank1)
mon2.write("Iron Tank 1 (" .. fluidName .. ") : " .. fluidAmount)
-- TANK 2
mon2.setCursorPos(rowPos, ironTank2Col)
mon2.clearLine()
local fluidRaw, fluidName, fluidAmount, fluidCapacity = getTank(irontank2)
mon2.write("Iron Tank 2 (" .. fluidName .. ") : " .. fluidAmount)
-- TANK 3
mon2.setCursorPos(rowPos, ironTank3Col)
mon2.clearLine()
local fluidRaw, fluidName, fluidAmount, fluidCapacity = getTank(irontank3)
mon2.write("Iron Tank 3 (" .. fluidName .. ") : " .. fluidAmount)
-- TANK 4
mon2.setCursorPos(rowPos, ironTank4Col)
mon2.clearLine()
local fluidRaw, fluidName, fluidAmount, fluidCapacity = getTank(irontank4)
mon2.write("Iron Tank 4 (" .. fluidName .. ") : " .. fluidAmount)
end
答案 0 :(得分:1)
function getTank(tankPeriph)
-- This has been tested and works
local tableInfo = tankPeriph.getTankInfo("unknown") -- Local to the getTank function.
for k,v in pairs(tableInfo) do
local fluidRaw = v.rawName -- local to this for loop
local fluidName = v.name -- local to this for loop
local fluidAmount = v.amount -- local to this for loop
local fluidCapacity = v.capacity -- local to this for loop
end
return fluidRaw, fluidName, fluidAmount, fluidCapacity -- Returning the values of global variables (which are nil).
end
正如我上面编辑的代码段中所示,您的本地人不在您认为的位置本地,并且您没有正确地从您的函数返回其值。将这些变量的局部声明移到for循环之外(如果需要的话,将赋值保留在for循环中,尽管我无法想象你这样做,因为你只得到循环中的最后一个值)和你的功能应“工作”。
答案 1 :(得分:1)
" local"限定符将范围限制为阻塞或块,因此getTank()循环中的locals限定为循环;在循环外,他们的价值观会丢失。因此,当getTank返回时,它返回的变量尚未在函数范围内定义,因此它们都是零。有关有用示例,请参阅http://www.lua.org/manual/5.1/manual.html#2.6。
但是,由于这似乎无法解决您的问题,我打赌您还有一个额外的问题,即local tableInfo
是空表,这意味着tankPeriph.getTankInfo("unknown")
返回空表(不是{{ 1}},但是nil
)。