在 Lua 中,使用变量访问表时,表既是 nil,又不是 nil

出于某种原因,当我仅访问主表时,一切都正常,但是当我尝试使用变量访问它时,它却是 nil? 以下是出现错误的函数:

function parseMtl(mtlFilePath, mtlTbl) -- 解析 mtlFilePath 中的 mtl 文件
    local step1 = {} -- 存储分割行的表

    local mtlID = 0 -- 材料的 ID
    local mtlList = {} -- 材料的列表
    local faceColors = {} -- 多边形的返回颜色
    local fC -- 测试变量
    contents, size = love.filesystem.read(mtlFilePath, all) -- 读取 mtlFilePath 中的 .mtl 文件
    step1 = split(contents, "\n") -- 将内容按换行符分为 step1
    for i=1,#step1 do
        if (starts(step1[i], "newmtl")) -- 创建新材料
        then
            mtlID = mtlID + 1
            mtlName = split(step1[i], "%s")[2]
            table.insert(mtlList, {mtlName, mtlID})
        end
        if (starts(step1[i], "Kd")) -- 如果它是颜色值,则将值放入材料列表
        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 -- 将 mtlTbl 值转换为 '顶点 ID,颜色' 格式
            fC = mtlList[mtlTbl[i][2]]
            table.insert(faceColors, {i, fC})
        end
    end
    return faceColors
end

出问题的部分是 table.insert(faceColors, {i, fC})。当我将 fC 放入表中时,它会返回 nil,但是我直接打印 fC 值时,它并不是 nil。我不知道为什么会这样。

点赞
用户9769594
用户9769594

你是否想要使用 table.insert 的返回值?

table.insert 是一个无返回值的函数,所以它总是返回 nil。

你是如何访问你的颜色数据的?

按照你设置的数据方式,你可以这样访问它:

local faceColors = parseMtl(...)
for i = 1, #faceColors do
    print(faceColors[i][2])
end
2021-07-04 09:33:21