Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
Change variable of for statement inside for function — Gideros Forum

Change variable of for statement inside for function

myrain25myrain25 Member
edited March 2014 in General questions
how can i change the variable inside the the statement

for i=1, 10 do
print(i)
i = 9
end

why i can't change "i" variable on that for declaration
because that function always execute for function for 10 times..

Comments

  • if you want to exit the loop, try using break instead. You can also try to use things like
    if i==3 then break end
    .

    For loops in Lua are different than C or many other language loops.
    twitter: @ozapps | http://www.oz-apps.com | http://howto.oz-apps.com | http://reviewme.oz-apps.com
    Author of Learn Lua for iOS Game Development from Apress ( http://www.apress.com/9781430246626 )
    Cool Vizify Profile at https://www.vizify.com/oz-apps
  • Hi @myrain25 you have to be careful with this, check these little codes:
    ---------------
    --case 1
    ---------------
    a={...}
    for i=1, 10 do
      a[i]=i
    end
     
    count=1
    for i=1,#a do
      i=nil
      print(i,a[i],a[count])
      count = count + 1
    end
     
    --[[
     got:
    -----------------------
    i       a[i]  a[count]
    -----------------------
    nil	nil	1
    nil	nil	2
    nil	nil	3
    nil	nil	4
    nil	nil	5
    nil	nil	6
    nil	nil	7
    nil	nil	8
    nil	nil	9
    nil	nil	10
    -----------------------
    ]]
     
     
    ---------------
    --case 2
    ---------------
    a={...}
    for i=1, 10 do
      a[i]=i
    end
     
    count=1
    for k,v in pairs(a) do
      v="e"
      k=nil
      print(k,v,a[k],a[count])
      count = count + 1
    end
     
    --[[
     got:
    -----------------------------
    k      v      a[k]  a[count]
    -----------------------------
    nil	e	nil	1
    nil	e	nil	2
    nil	e	nil	3
    nil	e	nil	4
    nil	e	nil	5
    nil	e	nil	6
    nil	e	nil	7
    nil	e	nil	8
    nil	e	nil	9
    nil	e	nil	10
    -----------------------------
    ]]
    This can give you a headache when you work with Box2D in destroying objects :-S

    Likes: ar2rsawseen

    +1 -1 (+1 / -0 )Share on Facebook
  • atilimatilim Maintainer
    edited March 2014
    Copy paste from the book 'Programming in Lua':

    You should never change the value of the control variable: the effect of
    such changes is unpredictable. If you want to end a for loop before its normal
    termination, use break.

Sign In or Register to comment.