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

Lua/Love2D中for循环索引莫名超出上限问题求助


## 根源分析与解决方法
### 1. 核心问题
- **循环逻辑漏洞**:当前循环条件`for i = 1, vertexCount, 2`中,当`vertexCount`为偶数时,理论最后一次迭代`i`应为`vertexCount-1`,但实际出现`i=9`,说明循环上限在执行过程中被意外改变。
- **Lua`#`运算符的不确定性**:`#polygon`返回的是数组的"连续长度",如果`polygon`表存在隐藏索引空洞(比如创建时曾删除元素后再添加,或被其他代码意外修改表结构),`#`的返回值会随机波动,导致`vertexCount`在循环前后不一致。

### 2. 针对性修复
#### (1)修正循环边界,从逻辑上避免越界
将循环上限改为`vertexCount - 1`,确保每次迭代的`i+1`不会超出表长度:
```lua
for i = 1, vertexCount - 1, 2 do

(2)强制校验polygon合法性,规避#运算符的坑

在函数开头添加校验,确保polygon是连续的偶数长度数组:

Geom.isIntersectionSegmentPolygon = function(x, y, x2, y2, polygon)
  -- 新增:校验polygon合法性
  local len = #polygon
  -- 必须是偶数个坐标点
  if len % 2 ~= 0 then
      error("Invalid polygon: must have even number of coordinates")
  end
  -- 校验数组无空洞,确保所有索引连续且非nil
  for i = 1, len do
      if polygon[i] == nil then
          error("Invalid polygon: nil value at index " .. i)
      end
  end
  local vertexCount = len

  -- 原代码剩余部分...
end

(3)给polygon添加写保护,定位潜在修改

通过元表禁止修改polygon,一旦有代码试图修改会直接抛出错误:

-- 创建polygon时添加保护
local polygon = {x1, y1, x2, y2, ...}
setmetatable(polygon, {
    __newindex = function(_, idx)
        error("Attempt to modify polygon at index: " .. idx)
    end
})

3. 额外排查方向

检查Love2D的异步API(如资源加载回调、定时器)是否在后台修改了全局状态,或是否有其他共享变量意外影响了polygon表的结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 14:14:51