【问题标题】:Table is both nil and not nil at the same time表同时为 nil 和非 nil
【发布时间】:2021-09-11 22:49:44
【问题描述】:

由于某种原因,当我只访问我的主表时,这很好,但是当我尝试使用变量访问它时,不知何故 nil? 这是给出错误的函数:

function parseMtl(mtlFilePath, mtlTbl) -- Parses the mtl file at mtlFIlePath
    local step1 = {} -- Table to store the split lines

    local mtlID = 0 -- The ID of the material
    local mtlList = {} -- The list of materials
    local faceColors = {} -- The returned colors of the polygons
    local fC -- A test variable
    contents, size = love.filesystem.read(mtlFilePath, all) -- Read the .mtl file at mtlFilePath
    step1 = split(contents, "\n") -- Split the contents into step1 by the newline character
    for i=1,#step1 do
        if (starts(step1[i], "newmtl")) -- Create a new material
        then
            mtlID = mtlID + 1
            mtlName = split(step1[i], "%s")[2]
            table.insert(mtlList, {mtlName, mtlID})
        end
        if (starts(step1[i], "Kd")) -- If it's a color value, put value into the list of materials
        then
            
            R = split(step1[i], "%s")[2] * 255
            G = split(step1[i], "%s")[3] * 255
            B = split(step1[i], "%s")[4] * 255
            table.insert(mtlList[mtlID], {R, G, B})
        end
        for i=1,#mtlTbl do -- Convert the mtlTbl values into 'Vertex ID, Color' format
            fC = mtlList[mtlTbl[i][2]]
            table.insert(faceColors, {i, fC})
        end
    end
    return faceColors
end

做奇怪事情的部分是table.insert(faceColors, {i, fC}),当我将fC 放在表中时,它以某种方式返回nil,当我直接打印fC 值时它不是nil。我不知道它为什么会这样做..

【问题讨论】:

  • 你没有使用love2d吗?您的代码似乎正在使用其文件系统库love.filesystem.read(mtlFilePath, all)
  • @Nifim 是的,我正在使用love2d,我不确定是否应该指定它,因为基本 Lua 函数和我在这里使用的东西无关love2d.
  • 最好标记它,虽然它可能看起来是一个与环境无关的问题,但它可能不是。这些信息为您的问题提供了更多背景信息。
  • 有道理,我猜你只是标记了它?因为我没有把它放在那里。
  • 阅读一下,然后创建一个minimal reproducible example。这里没有足够的信息来解决您的问题。 starts 是如何定义的? split 是如何定义的? mtlTbls 是如何定义的?示例输入文件是什么样的?我怀疑上述函数之一没有按预期工作,或者输入与代码预期不完全匹配。如果你创建一个simple minimal reproducible example,使用一些虚拟输入,有同样的问题(不使用Love2d),你可能会自己弄清楚你做错了什么。

标签: lua love2d


【解决方案1】:

您是否尝试使用table.insert 的返回值?

table.insert 是无效的,所以它总是返回 nil。

您如何访问您的颜色数据?

您设置数据的方式,您可以通过以下方式访问它:

local faceColors = parseMtl(...)
for i = 1, #faceColors do
    print(faceColors[i][2])
end

【讨论】:

  • 我没有使用table.insert 的返回值,这不是我访问这些值的方式(至少是直接访问)。我将这些值放入主脚本中的另一个表中,与我的渲染函数一起使用。不过,它最终确实是等价的。
  • 考虑到您的问题的性质,您应该在问题中分享有关该问题的更多详细信息。不过,它会是这样的:local faceColors = outerTable[whateverKey]; for i = 1, #faceColors do ... end
猜你喜欢
  • 2015-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2019-01-12
  • 2016-07-20
相关资源
最近更新 更多