Page 1 of 1

Please help a Lua newb?

Posted: Sun Jan 03, 2010 8:25 pm
by Fourex
So, just got started with Love, (and programming in general) so I don't know all that much about how Lua works. I'm experimenting with tables, and have run into a problem when trying to repeat something for each argument in a table. I'm trying to replicate what I have done in part A with part B, but make it a repeating function(and 50 pixels lower), rather than writing each line out. When I run this, I get the error "main.lua:19: bad argument #1 to 'print' (string expected, got nil)"
Something tells me this is a simple fix, but I can't find it. Can anyone help? Thanks in advance!

Code: Select all

a = {1,1,2,3,5,8,13}

x = 0

function love.draw()

	     --***part A:***
	love.graphics.print(a[1], 100, 100)
	love.graphics.print(a[2], 110, 100)
	love.graphics.print(a[3], 120, 100)
	love.graphics.print(a[4], 130, 100)
	love.graphics.print(a[5], 140, 100)
	love.graphics.print(a[6], 150, 100)
	love.graphics.print(a[7], 160, 100)
	
        --***part B:***
	repeat
		x = x+1
		love.graphics.print(a[x], (100+(x*10-10)), 150)
	until x == 7

end

Re: Please help a Lua newb?

Posted: Sun Jan 03, 2010 8:30 pm
by bartbes
Because x is set to 0 only once, so in the second frame it will be higher, however, the usual lua solution is:

Code: Select all

for i, v in ipairs(a) do
    love.graphics.print(v, 100+(x-1)*10, 150)
end

Re: Please help a Lua newb?

Posted: Sun Jan 03, 2010 8:36 pm
by Fourex
bartbes wrote:Because x is set to 0 only once, so in the second frame it will be higher, however, the usual lua solution is:

Code: Select all

for i, v in ipairs(a) do
    love.graphics.print(v, 100+(x-1)*10, 150)
end
So, that sorta works. I don't get an error, but all the numbers are on top of one another. And I don't understand at all what the parts of this code are, or how they work. Does this have a name so I can look it up?

Re: Please help a Lua newb?

Posted: Sun Jan 03, 2010 8:50 pm
by bartbes
Ah, I messed up the x in the x calculation should be i, then it works.
If you want details on ipairs, check out http://www.lua.org/pil/4.3.5.html

Re: Please help a Lua newb?

Posted: Sun Jan 03, 2010 9:00 pm
by Fourex
Thanks! Now the code works, and I understand slightly more about ipairs.