Jump to content




Looping Through A Table But Skipping The First Variable


  • You cannot reply to this topic
3 replies to this topic

#1 campicus

  • Members
  • 164 posts

Posted 15 October 2013 - 07:53 PM

Firstly, I am very new to using ipairs and tables in general, hopefully this is an easy question.

I have this table:

t = {[1]=1,[2]=2,[3]=3,}

I want to run this loop:

for i,v in ipairs(t) do
  print(t[i])
end

How can I run that loop without calling t[1]? basically, run the loop for every value in the table except the first one.

FYI: I did do this but it didn't work:

tArgs = {[1]=1,[2]="right",[3]="left"}

duration = tArgs[1]

sides = tArgs
table.remove(sides, 1)

but this changed the "tArgs" table as well :s

#2 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 15 October 2013 - 07:58 PM

Since the tables you're working with are numeric, all you have to do is skip the first entry:

for i, v in ipairs(t) do
  if i > 1 then
    --actual loop body
  end
end


#3 Yevano

  • Members
  • 376 posts
  • LocationUSA

Posted 15 October 2013 - 08:23 PM

View Postcampicus, on 15 October 2013 - 07:53 PM, said:

FYI: I did do this but it didn't work:

tArgs = {[1]=1,[2]="right",[3]="left"}

duration = tArgs[1]

sides = tArgs
table.remove(sides, 1)

but this changed the "tArgs" table as well :s

tArgs and sides refer to the same table. You're expecting them to copy the table. If you do have a reason to copy them, then you could run a loop like:

local tArgs = {[1]=1,[2]="right",[3]="left"}
local duration = tArgs[1]
local sides = { }

for i = 2, #tArgs do
	sides[i - 1] = tArgs[i]
end

This will copy all but the first element.

#4 campicus

  • Members
  • 164 posts

Posted 15 October 2013 - 08:26 PM

Thanks Lyqyd! That worked well (and was super easy). I now have another problem, that my "pulse" function is not looping. The status does not change from "on" to "off". ideas?
EDIT: Cheers Yevano, I thought that may have been the case (dammit lol)
Spoiler






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users