Tables and "for" statements

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
pgimeno
Party member
Posts: 3550
Joined: Sun Oct 18, 2015 2:58 pm

Re: Tables and "for" statements

Post by pgimeno »

Sounds like you need help about the basics of Lua. Here's a book:

https://www.lua.org/pil/contents.html

Scroll down to "Numeric FOR" (section 4.3.4) and "Generic FOR" (section 4.3.5).
sphyrth
Party member
Posts: 260
Joined: Mon Jul 07, 2014 11:04 am
Contact:

Re: Tables and "for" statements

Post by sphyrth »

Suppose this:

Code: Select all

my_table = { 'cat', 'dog', 'mouse', }
Untitled.png
Untitled.png (5.21 KiB) Viewed 5002 times
i returns the indexes of each item... namely 1 through 3.
v returns 'cat', 'dog', and 'mouse' for each cycle depending on their index.
User avatar
zorg
Party member
Posts: 3444
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: Tables and "for" statements

Post by zorg »

sphyrth wrote: Fri Sep 04, 2020 2:31 am Suppose this:

Code: Select all

my_table = { 'cat', 'dog', 'mouse', }
for i,v in pairs(my_table) do
  -- do stuff for each item's index and/or value
end
i returns the indexes of each item... namely 1 through 3.
v returns 'cat', 'dog', and 'mouse' for each cycle depending on their index.
A few things; for a table like that, with (implicit) numeric keys and no gaps, ipairs is way better, because it will be iterated on in order.
pairs has no definitive order, and traverses all keys, whatever they may be (except nil, you can't have that as a key).
Me and my stuff :3True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.
User avatar
Jeeper
Party member
Posts: 611
Joined: Tue Mar 12, 2013 7:11 pm
Contact:

Re: Tables and "for" statements

Post by Jeeper »

Resolution wrote: Thu Sep 03, 2020 5:54 am I'm having some difficulty understanding how these statements are defined.

Most of the tutorials I can find just tell you to do something like,

for i, v do

But, they don't tell you why and what that means, they tell you not to worry about it now. I can copy the code, and it works, but if I don't know what I'm defining it doesn't help me out at all.

Anybody got a simple breakdown of for statements?
If someone tells you to not worry and copy it, they are not teaching you anything.
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot] and 224 guests