Discord
Login
Community
DARK THEME

anyone know why it could be throwing me this error? (lua)

"[string "main"]:40: attempt to index a nil value (field '?'), in file "main" at line 40"

local cube = {
    { -1, -1, -1 },
    {  1, -1, -1 },
    {  1,  1, -1 },
    { -1,  1, -1 },
    { -1, -1,  1 },
    {  1, -1,  1 },
    {  1,  1,  1 },
    { -1,  1,  1 }
}

local rotationAngle = 0
local scale = 100
local centerX, centerY = 400, 300

function rotateY(x, y, z, angle)
    local rad = math.rad(angle)
    local cos = math.cos(rad)
    local sin = math.sin(rad)
    local newX = x * cos - z * sin
    local newZ = x * sin + z * cos
    return newX, y, newZ
end

function project(x, y, z, scale)
    local sx = x / (z + 5) * scale
    local sy = y / (z + 5) * scale
    return sx, sy
end

function drawCube(cube)
    local edges = {
        {0, 1}, {1, 2}, {2, 3}, {3, 0},
        {4, 5}, {5, 6}, {6, 7}, {7, 4},
        {0, 4}, {1, 5}, {2, 6}, {3, 7}
    }
    
    for _, edge in ipairs(edges) do
        local i1, i2 = edge[1], edge[2]
        local x1, y1, z1 = cube[i1][1], cube[i1][2], cube[i1][3]
        local x2, y2, z2 = cube[i2][1], cube[i2][2], cube[i2][3]
        x1, y1, z1 = rotateY(x1, y1, z1, rotationAngle)
        x2, y2, z2 = rotateY(x2, y2, z2, rotationAngle)
        local x1_2D, y1_2D = project(x1, y1, z1, scale)
        local x2_2D, y2_2D = project(x2, y2, z2, scale)
        x1_2D, y1_2D = x1_2D + centerX, y1_2D + centerY
        x2_2D, y2_2D = x2_2D + centerX, y2_2D + centerY
        screen:drawLine(x1_2D, y1_2D, x2_2D, y2_2D, "white")
    end
end

function draw()
    screen:clear()
    drawCube(cube)
    rotationAngle = rotationAngle + 1
    if rotationAngle >= 360 then
        rotationAngle = 0
    end
end

Edges has elements {0, 1} and {0, 4}. You store the 0 in i1 and use it as a table index (cube[i1][1]). But lua has 1-based indices, so cube[0] is nil.

thanks

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community