• Benefits of List-Style Tables
    2 replies, posted
Value-indexed tables are a commonly-neglected technique in Lua: local tbl = {[1] = "a",[2] = "b",[3] = "c"} --this is a normal sequential table. --Checking if a value is in a normal table: function table.HasValue(tbl,value) --O(n) worst-case complexity for k,v in pairs(tbl)do if v == value then return true end end return false end local list = {["a"]=true, ["b"]=true, ["c"]=true} --this is a value-indexed version of that table. --Checking if a value is in a value-indexed table: function ListHasValue(tbl,value) --O(1) worst-case complexity return tbl[value] end We'll call them Lists (unless there's another word for them already). They're incredibly useful! The idea is that by using the actual value we intend to store in the table as the key itself, we can retrieve and remove it from the table much easier and faster. This has many uses: Good for when the order of data saved is unimportant and each value is unique within the table. Creating a table in which the same value can't exist more than once. Rapidly checking whether a value is stored in a table without the use of iteration (seen above). But we can take it one step further with 2D Lists: --A 2D sequential table holding players' friends as {guy=player, friends={their friends}} local friendTbl = { {guy=Entity(1), friends={Entity(2), Entity(3)}}, {guy=Entity(2), friends={Entity(1)}}, {guy=Entity(3),friends={Entity(1)}} } function TwoPlayersAreFriends(ply,ply2) for k,v in pairs(friendTbl)do if v.guy == ply then for k2,v2 in pairs(v.friends)do if v2 == ply2 then return true end end return false end end return false end --And this is a 2D list which holds the same data as above. local friendList = { [Entity(1)] = {Entity(2)=true, Entity(3)=true}, [Entity(2)] = {Entity(1)=true}, [Entity(3)] = {Entity(1)=true} } --Checking if a value is in a value-indexed table: function TwoPlayersAreFriends(ply,ply2) return friendList[ply][ply2] end Look at how much faster and simpler that is! If you wanted to, you could even replace `true` in the list with some kind of data. This makes the list into a dictionary. So remember: Any time you need to save distinct data in an unordered table, opt to use a List instead!
This is more similar to a Set, than a List. A List is an ordered collection of elements, typically with heavy cost for lookup. A List can also contain duplicates of the same value. A Set is generally unordered, has constant or log lookup time, and cannot contain duplicate values. It's a useful technique, though I wouldn't call it neglected - I use it myself frequently as well as a lot of my other friends. It's just the Lua's version of a Set, anyone who knows their fundamental data structures should be able to recognize that tables can be used that way.
lol rip syntax
Sorry, you need to Log In to post a reply to this thread.