Cycling through a Lua able in reverse.

Posted by Bobble on Wed 09 Sep 2009 03:14 AM — 3 posts, 24,484 views.

Canada #0
Greets everyone.

I was wondering if anyone knew of a way to cycle through a lua table starting with the last element and then proceeding down to the first.

The reason I ask is I am creating a table using "GetCommandList" and cycling through it using a for .. in .. do loop. However this creates a situation where the it starts with the most recent command, the next most recent etc. I want it to start with the least recent, the next least recent and so on.

Does anyone have an idea of how to do this. I'm imagining this will be pretty simple, but it escapes me right now.
USA #1
If the table is an array (that is, it has numeric indices, not arbitrary keys) you can do the following:


local t = get_the_table
for i = #t, 1, -1 do
  elem = t[i]
  -- do something with elem
end
Amended on Wed 09 Sep 2009 03:56 AM by David Haley
Canada #2
Hi David,

That seems to work perfectly. Thanks a bunch.

Take care!