Page 1 of 1

Problem with tables

Posted: Thu Sep 08, 2011 12:29 am
by NilPirate
Hello, I've been working on a little program for my end-of-year Computer Science project, and for some reason something in what I think is my table referencing isn't working, could anyone help me find out what's wrong?
Thanks!

Re: Problem with tables

Posted: Thu Sep 08, 2011 1:06 am
by vrld
Lua arrays are 1-indexed, as opposed to 0-indexed, so here's your problem. Also, it's better to use #worlddata instead of table.maxn(worlddata).

Re: Problem with tables

Posted: Thu Sep 08, 2011 1:07 am
by Rad3k
In Lua, tables indices start at 1, not 0, and this code tries to get worlddata[0] on first loop:

Code: Select all

for i = 0,table.maxn(worlddata) do
	b = worlddata[i]
	love.graphics.rectangle("fill",b[1],b[2],b[3],b[4])
end
A quick and dirty fix would be just to change 0 to 1 in this code, but there's a better alternative - it's simpler (and less error prone) to use ipairs function, like:

Code: Select all

for i, b in ipairs(worlddata) do
	love.graphics.rectangle("fill",b[1],b[2],b[3],b[4])
end
The added benefit is that you don't have to write "b = worlddata", because ipairs already does it.

Another hint - when you need some temporary variables, that are not used outside some function or loop, it's a good practice to declare them as locals.

Re: Problem with tables

Posted: Thu Sep 08, 2011 8:52 pm
by NilPirate
Thanks! Yeah, originally my b variable was local, but I removed it while trying to figure out how it was broken.