Nim语言索引越界问题求助:代码报错IndexError如何解决?
Fixing the Index Out of Bounds Error in Your Nim Code
Hey there! Let's break down why you're getting that index out of bounds error and how to fix it.
The Root Cause
Nim uses 0-indexed sequences—meaning the first element of a seq is at index 0, and the last valid index is always size - 1 (where size is the length of your sequence). Your code has a key mistake that violates this rule:
- Incorrect loop range: You're using
for i in 1..size, which makesigo all the way tosizeitself. But wheniequalssize, you're trying to accesstheMap[i]—a position that doesn't exist (since the sequence only goes up tosize - 1). - Unnecessary variable declaration: The line
var i: int = 0;is redundant because Nim'sforloop automatically creates the loop variable for you.
Corrected Code
Here's the fixed version of your code with explanations for each change:
proc makeMap(width: int, size: int): seq[int] = var theMap = newSeq[int](size) var playerPos: int = 249750 # Use 0..<size to cover all valid indices (0 to size-1) for i in 0..<size: if i < width: theMap[i] = 2 elif i == playerPos: theMap[i] = 1 else: theMap[i] = 0 return theMap var width = 500 var height = 500 var nsize: int = width * height var myMap = makeMap(width, nsize) echo "Map: ", myMap
Key Changes Explained
- Loop range adjustment:
0..<sizegenerates every integer from0up to (but not including)size, which perfectly matches the valid indices of your sequence. This eliminates the out-of-bounds access. - Removed redundant variable: We got rid of
var i: int = 0;since theforloop handles creatingifor us.
Quick Check
Your playerPos value (249750) is valid here: since width * height = 250000, the maximum valid index is 249999, so 249750 falls well within the valid range. Just keep this in mind if you ever adjust the width or height values later!
内容的提问来源于stack exchange,提问作者Arturo Contreras
相关产品推荐
相关产品推荐

