You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在CC: Tweaked中用Lua实现Bresenham直线算法报错求助

CC: Tweaked 直线绘制模块错误修复

错误原因分析

报错pixels.lua:24: attempt to index local 'y1' (a number value)是因为代码里把函数调用的逗号写成了点:

pixels.drawPixel(x1, y1. monitor, color)

这里的y1. monitor会被Lua解析为“访问数字y1的monitor字段”,数字类型没有字段,所以触发索引错误。

除此之外,代码还有几处问题会导致功能异常:

  • 斜率计算优先级错误:slope = y2 - y1 / x2 - x1未加括号,Lua会先执行除法,结果完全不符合预期,应改为(y2 - y1)/(x2 - x1)
  • fillScreen函数未传入monitor参数,直接使用全局变量,调用时会出错
  • drawLine中y变量未初始化,当error未达到0.5时y为nil,调用drawPixel会报错
  • 仅处理x从x1到x2递增的情况,未考虑x2 < x1或斜率绝对值大于1的场景

修复后的完整代码

local pixels = {} 

function pixels.drawPixel(x, y, monitor, color)
    monitor.setCursorPos(x, y)
    monitor.setBackgroundColor(color)
    monitor.write(" ")
end 

function pixels.fillScreen(monitor, color)
    local x, y = monitor.getSize()
    for j = 1, y do
        for i = 1, x do
            pixels.drawPixel(i, j, monitor, color)
        end
    end
end 

function pixels.drawLine(x1, y1, x2, y2, monitor, color)
    -- 处理x1 > x2的情况,交换坐标统一方向
    if x1 > x2 then
        x1, x2 = x2, x1
        y1, y2 = y2, y1
    end

    local dx = x2 - x1
    local dy = y2 - y1
    local slope = dy / dx
    local error = 0
    local y = y1

    pixels.drawPixel(x1, y1, monitor, color)
    
    for x = x1 + 1, x2 do
        error = error + math.abs(slope)
        if error >= 0.5 then
            y = y + (dy > 0 and 1 or -1)
            error = error - 1
        end
        
        pixels.drawPixel(x, y, monitor, color)
    end 
end 

return pixels

额外说明

修复后的代码处理了x坐标递减的情况,同时根据dy的正负调整y的增减方向,基本实现了正确的直线绘制。如果需要更完整的Bresenham算法(支持斜率绝对值大于1的竖直线/陡线),还需要进一步判断dx和dy的大小,切换循环变量为y。

内容的提问来源于stack exchange,提问作者pizzalawl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 05:37:09