[SOLVED] Three basic table questions

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
nunix
Prole
Posts: 28
Joined: Fri Jan 30, 2009 4:38 am

[SOLVED] Three basic table questions

Post by nunix »

1: I've used the search function! I've found interesting results but none quite what I'm looking for.
2: Likewise both the love2d wiki tutorials and the Lua reference manual and tutorials (and I have a hardcopy of the 5.1 Progamming in Lua book to boot)
3: I'm sure I am overthinking this and making it way more difficult than it actually is.

(These examples are from a love2d tutorial)

Here is a table:

Code: Select all

function love.load()
  MyGlobalTable = { 
    { 'Stuff inside a sub-table', 'More stuff inside a sub-table' },
    { 'Stuff inside the second sub-table', 'Even more stuff' }
  }
end
Here is a generic for loop:

Code: Select all

function love.draw()
  for i,subtable in ipairs(MyGlobalTable) do
    for j,elem in ipairs(subtable) do
      love.graphics.print(elem, 100 * i, 50 * j)
    end
  end
end
1: Why does ipairs work? thought ipairs was only for numbers, but these are strings.

2: If i wanted to read the whole table, but only print 'Even more stuff', how would I do that?

3: Right now, it will display like this:

Code: Select all

Stuff inside a sub-table         Stuff inside a second sub-table
More stuff inside a sub-table    Even more stuff
How would I make it display like this (as it is written in the table):

Code: Select all

Stuff inside a sub-table                More stuff inside a sub-table
Stuff inside a second sub-table         Even  more stuff
Last edited by nunix on Mon Oct 01, 2012 9:09 pm, edited 1 time in total.
User avatar
bartbes
Sex machine
Posts: 4946
Joined: Fri Aug 29, 2008 10:35 am
Location: The Netherlands
Contact:

Re: Three basic table questions

Post by bartbes »

nunix wrote: 1: Why does ipairs work? thought ipairs was only for numbers, but these are strings.
Because that table definition is equal to:

Code: Select all

function love.load()
  MyGlobalTable = { 
    [1] = { [1] = 'Stuff inside a sub-table', [2] = 'More stuff inside a sub-table' },
    [2] = { [1] = 'Stuff inside the second sub-table', [2] = 'Even more stuff' }
  }
end
nunix wrote: 2: If i wanted to read the whole table, but only print 'Even more stuff', how would I do that?
MyGlobalTable[2][2]
nunix wrote:3: How would I make it display like this

Code: Select all

function love.draw()
  for i,subtable in ipairs(MyGlobalTable) do
    for j,elem in ipairs(subtable) do
      love.graphics.print(elem, 100 * j, 50 * i)
    end
  end
end
nunix
Prole
Posts: 28
Joined: Fri Jan 30, 2009 4:38 am

Re: Three basic table questions

Post by nunix »

Thank you!
Post Reply

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 163 guests