• Announcement: Lua.org now officially recommends this forum as a meeting place for the Lua community

Previous value in table (1 Viewer)

Herly Quijano

Newcomer
Joined
Mar 19, 2021
Messages
29
Reaction score
2
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?
 

stetre

Member
Rank: I
Joined
Jan 8, 2020
Messages
61
Reaction score
43
Location
Italy
Website
github.com
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
Joined
Mar 19, 2021
Messages
29
Reaction score
2
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

function AddToList(node)
    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

Member
Rank: I
Joined
Jan 8, 2020
Messages
61
Reaction score
43
Location
Italy
Website
github.com
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.
 
Top