I'm having a brain fart. Why is this erroring?

 function localGroup:addItem(item)  
 local i  
 for i = 1, maxItems do  
 print(i) -- prints 1 through 6 (maxItems = 6)  
 if items[i] == nil then  
 items[i] = item  
 db:exec([[REPLACE INTO inventory (slot, itemId, description, quantity, inuse, icon, width, height, location) VALUES (]] .. i .. [[,"]] .. items[i].id .. [[","]] .. items[i].name .. [[","]] .. "1" .. [[","]] .. "1" .. [[","]] .. items[i].availableIcon .. [[","]] .. items[i].width .. [[","]] .. items[i].height .. [[","]] .. "pack" ..[[");]])  
 break;  
 end  
 end  
 print(i) -- prints "nil"  
 print(maxItems)  
 if i \> maxItems then return false end -- errors here because its nil  
 return true  
 end  

i should be “6” or less when it his that print statement.

Any ideas?
[import]uid: 19626 topic_id: 16706 reply_id: 316706[/import]

Hi Rob,

Wouldn`t be at line 6 “~=” instead of the actual “==” youre using?
Regards, [import]uid: 89165 topic_id: 16706 reply_id: 62542[/import]

But that wouldn’t affect why “i” is nil after the loop is done.

I have rewritten the whole if block anyway and worked around the problem by setting a “j” variable to track where I’m at when I break from the loop…

Hack, Dirty Hack [import]uid: 19626 topic_id: 16706 reply_id: 62551[/import]

Sorry Rob,

So I am out of being a help for you by this time…
PS: Sure you`ll get it btw! =] [import]uid: 89165 topic_id: 16706 reply_id: 62553[/import]

From http://www.lua.org/pil/4.3.4.html

“the control variable is a local variable automatically declared by the for statement and is visible only inside the loop. A typical mistake is to assume that the variable still exists after the loop ends”

In other words, the ‘i’ of your for loop is a different local variable than the local’i’ you declared above it, so the ‘i’ you are printing is not the same ‘i’ of the loop.

The upshot is you don’t need to (and shouldn’t) declare the control variables used in a for loop.

[import]uid: 9422 topic_id: 16706 reply_id: 62562[/import]

Thanks @XenonBL that in a “Lua is weird” way, makes a lot of sense. Though I’m pretty sure I’ve depended on that in the past.

In a way I’m glad that do that for us, its too easy to not localize that variable and it would be horrible with “i” being global if you depend on it to be in any state that you control.

[import]uid: 19626 topic_id: 16706 reply_id: 62565[/import]

Wow, @XenonBL, that’s good to know. I’ve always declared every variable local (unless I wanted it to be global).

I tried the following and it confirms it. And now I know how to check a variable like this one.

[lua]local maxItems = 6;
local i
for i = 1, maxItems do
print(i) – prints 1 through 6 (maxItems = 6)
end
print(i)
print(maxItems)

– terminal output is:
1
2
3
4
5
6
nil
6[/lua] [import]uid: 67217 topic_id: 16706 reply_id: 62566[/import]