Problem with tables

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
NilPirate
Prole
Posts: 5
Joined: Wed Sep 07, 2011 12:38 am

Problem with tables

Post 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!
Attachments
Try.love
(488 Bytes) Downloaded 133 times
User avatar
vrld
Party member
Posts: 917
Joined: Sun Apr 04, 2010 9:14 pm
Location: Germany
Contact:

Re: Problem with tables

Post 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).
I have come here to chew bubblegum and kick ass... and I'm all out of bubblegum.

hump | HC | SUIT | moonshine
Rad3k
Citizen
Posts: 69
Joined: Mon Aug 08, 2011 12:28 pm

Re: Problem with tables

Post 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.
NilPirate
Prole
Posts: 5
Joined: Wed Sep 07, 2011 12:38 am

Re: Problem with tables

Post by NilPirate »

Thanks! Yeah, originally my b variable was local, but I removed it while trying to figure out how it was broken.
Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 9 guests