Page 1 of 1

[SOLVED] Three basic table questions

Posted: Mon Oct 01, 2012 8:23 pm
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

Re: Three basic table questions

Posted: Mon Oct 01, 2012 8:56 pm
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

Re: Three basic table questions

Posted: Mon Oct 01, 2012 9:09 pm
by nunix
Thank you!