Table Preferences

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
User avatar
Lap
Party member
Posts: 256
Joined: Fri Apr 30, 2010 3:46 pm

Table Preferences

Post by Lap »

I've tend to use something like:

Code: Select all

tbl = {}
tbl.Bread = true
tbl.Milk = true

if tbl.Bread then
print("We got some bread")
end
However, almost everyone else I see tends to do

Code: Select all

tbl = {}
table.insert(tbl,'bread')
table.insert(tbl,'milk')

if table.HasValue(tbl,'bread') then
print("We got some bread")
end
Is there a reason I shouldn't be using my current method for indexes of unique values?
User avatar
kikito
Inner party member
Posts: 3153
Joined: Sat Oct 03, 2009 5:22 pm
Location: Madrid, Spain
Contact:

Re: Table Preferences

Post by kikito »

By using table.insert the table is indexed by continuous integers (1,2,3, etc).

This makes possible to iterate over the table with ipairs instead of pairs, so iterating over the table is more efficient.

It is also possible to automatically calculate the table length with #tbl.

Integers also take a little bit less memory - but not much more.

So table.insert is better with tables that are going to be iterated over a lot, and where the keys don't "matter" (so you can use numbers). Typically these are "lists of elements": lists of enemies, items, tiles on a map... that sort of thing. On these lists you normally don't know exactly how many elements you will have.

On the other hand, for us humans it is much easier to understand if you say tbl.body instead of tbl[2], for example.

On the efficiency department, table.insert is a function; It's slower than doing tbl.key = value.

So tbl.key = value is better when the table isn't going to be parsed over with a loop, or the keys have a "meaning" for the programmer. These are typically "object-like"; the element returned by tbl.key is "a property" of tbl, not an element on a list. On this kind of tables you know exactly how many keys you will have, and each has one name.

In your example I'd use table.key.
When I write def I mean function.
User avatar
bartbes
Sex machine
Posts: 4946
Joined: Fri Aug 29, 2008 10:35 am
Location: The Netherlands
Contact:

Re: Table Preferences

Post by bartbes »

Oh, and as I pointed out in IRC the table.insert way supports duplicates.
User avatar
Robin
The Omniscient
Posts: 6506
Joined: Fri Feb 20, 2009 4:29 pm
Location: The Netherlands
Contact:

Re: Table Preferences

Post by Robin »

Also, table.HasValue() doesn't exist -- you'll have to write it yourself.
Help us help you: attach a .love.
User avatar
Lap
Party member
Posts: 256
Joined: Fri Apr 30, 2010 3:46 pm

Re: Table Preferences

Post by Lap »

Robin wrote:Also, table.HasValue() doesn't exist -- you'll have to write it yourself.
Speaking of which... viewtopic.php?f=3&t=1637
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot] and 0 guests