Jump to content

Lua nested for loop


Rick
 Share

Recommended Posts

I need another pair of eyes. The selected code creates a 2D array. You can tell from the right side that r = 12 and c = 5, yet after the loop is finished you can also see on the right that there are only 4 col's instead of 5 but there are 12 rows in the 2D array.

 

If I print out col while it's looping it only prints 1 - 4 so it's like it's not inclusive to the upper bound but it should be and the row loop is.

 

I must be missing something obvious here.

 

 

https://dl.dropboxusercontent.com/u/1293842/for_loop.png

Link to comment
Share on other sites

I know the debugger says c=5 and r=12 but have you tried adding a print before the loop for r and c? The reason I ask is because I ran equivalent code and the results look fine. It would be good to know exactly what lua sees, not the degger. Ran on a standard lua interpreter but that shouldn't matter.

 


c = 5
r = 12
map = {}

for row=1, r do
   map[row] = {}
   for col=1, c do
       map[row][col] = "r"..row.."c"..col
   end
end

for row=1, r do
   str = ""
   for col=1, c do
       str = str..map[row][col].." "
   end
   print(str)
end

 

Results:


C:\Users\Blah\Desktop>lua.exe test.lua
r1c1 r1c2 r1c3 r1c4 r1c5
r2c1 r2c2 r2c3 r2c4 r2c5
r3c1 r3c2 r3c3 r3c4 r3c5
r4c1 r4c2 r4c3 r4c4 r4c5
r5c1 r5c2 r5c3 r5c4 r5c5
r6c1 r6c2 r6c3 r6c4 r6c5
r7c1 r7c2 r7c3 r7c4 r7c5
r8c1 r8c2 r8c3 r8c4 r8c5
r9c1 r9c2 r9c3 r9c4 r9c5
r10c1 r10c2 r10c3 r10c4 r10c5
r11c1 r11c2 r11c3 r11c4 r11c5
r12c1 r12c2 r12c3 r12c4 r12c5

 

Another thing I thought of, I'm not sure what happens if you have a global variable c in addition to the function argument c. All the more reason to print it out and see what it grabs for a value for c.

  • Upvote 1
Link to comment
Share on other sites

Ah, c is equal to 4.999999! I'll round up. Damn debugger rounding! Thank you sir for the eyes and ideas. I should have printed that before. That's what I get for trusting the debugger.

Glad to help! Imo this is bug report worthy. The debugger should never manipulate the data before presenting it to the user, could send the user on a wild goose chase.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...