# Previous value in table (1 Viewer)

#### Herly Quijano

##### Newcomer
As well as exists the function "next" to get the next value in a table, is there an equivalent to the previous value if I set the index?

#### Herly Quijano

##### Newcomer
I tried something like this, its ok?
Lua:
``````[email protected] t table
[email protected] i integer if is nil this will return the last value
[email protected] any,any
function prev(t,i)
if t then
if not i then return #t,t[#t] end
local k1,v1
for k,v in pairs(t) do
if v==i then return k1,v1 end
k1,v1=k,v
end
end
return nil
end``````

#### stetre

##### MemberRank: I
It's... meh. This is basic computer science: the operations you want to perform on your data suggest the data structure to use. Here you are using a plain table as if it were a linked list (which in a sense it is), but if you need the 'prev' operation, a doubly-linked list is more apt.

#### Herly Quijano

##### Newcomer
If the solution is use a linked list then I know what to do, I knew how to do one.

#### Herly Quijano

##### Newcomer
If you wanna know this is the method I used, just I didn't think I will need it in Lua, but I think is too basic, can you tell me if is fine?
Lua:
``````local Next={[0]=0}
local Prev={[0]=0}

function InsertToList(node,replace)
Next[node]=replace
Prev[node]=Prev[replace]
Next[Prev[node]]=node
Prev[replace]=node
end

InsertToList(node,0)
end

function RemoveFromList(node)
Next[Prev[node]]=Next[node]
Prev[Next[node]]=Prev[node]
end

function Iteration()
local node=Next[0]
while node~=0 do
--Do stuff
node=Next[node]
end
end``````

#### stetre

##### MemberRank: I
This should work.

As a general note, Lua tables are very versatile data structures which are good enough for many purposes, but at times you'll find that other kinds of data structures are better suited to the problem at hand. This case is one of them: using a plain table you need to traverse the list each time you want to reach the node that precedes a given one, which is very inefficient, especially if the list is long and the operation is performed often. With a doubly linked list, instead, accessing the prev of a given node is trivial: given node, the preceding element (if any) is just Prev[node].

There are other - arguably cleaner - ways to implement data structures in Lua, using metatables and metamethods. I don't have time right know but as soon as I find it I'll post an example.