Page 1 of 1
Creating object Creator
Posted: Sun Nov 11, 2012 8:59 pm
by Krizzu
Hello World
I'd like to create simply Object creator with for loop:
for i=1,10 do
object.x=100
object.y=100
object.body=love.physics.newBody(world, object.x, object.y "dynamic")
object.shape=love.physics.newRectangleShape(21,21)
object.fixture=love.physics.newFixture(object.obj.body, object.obj.shape, 1)
end
But I got:
Attempt to index field "?" (a nil value)
So what's going on?
I came back to LUA and it's seems I forgot a little bit
Re: Creating object Creator
Posted: Sun Nov 11, 2012 9:00 pm
by Larsii30
The table "object" has to been created before puttings something into it.
[edit deleted: does not work like this because of the physic things.]
Re: Creating object Creator
Posted: Sun Nov 11, 2012 9:15 pm
by Krizzu
Yea, I created it earlier, just didn't posted it.
object={}
And problem is still ariving
#EDIT
Eh, stupid me >_<
In loop, you must make table in table, which is:
object={}
for i=1,10 do
object={}
object.x=100
object.y=100
object.body=love.physics.newBody(world, object.x, object.y, "dynamic")
object.shape=love.physics.newRectangleShape(21,21)
object.fixture=love.physics.newFixture(object.body, object.shape, 1)
end
Re: Creating object Creator
Posted: Mon Nov 12, 2012 12:22 pm
by spir
Krizzu wrote:Hello World
I'd like to create simply Object creator with for loop:
for i=1,10 do
object.x=100
object.y=100
object.body=love.physics.newBody(world, object.x, object.y "dynamic")
object.shape=love.physics.newRectangleShape(21,21)
object.fixture=love.physics.newFixture(object.obj.body, object.obj.shape, 1)
end
But I got:
Attempt to index field "?" (a nil value)
So what's going on?
I came back to LUA and it's seems I forgot a little bit
A function that creates tables (data structures) is usually called constructor or factory. What you want to do is probably something like this:
Code: Select all
make_objects = function ()
local objectS = {}
for i=1,10 do
-- create new object
local obj = {}
-- describe its contents
obj = {}
obj.x = 100
obj.y = 100
obj.body = love.physics.newBody(world, obj.x, obj.y, "dynamic")
obj.shape = love.physics.newRectangleShape(21,21)
obj.fixture = love.physics.newFixture(obj.body, obj.shape, 1)
-- define it as item #i in objectS
objectS[i] = obj
end
return objectS
end
Note: you should always call a table that represents a set of items (a collection) with a plural 's'. Unless there is an obvious name such as 'colony' for a set of ants or 'palette' for a set of colours (or 'staff' for a set of employees). Also, it is a good idea --to avoid mistakes or typos-- to use a shortcut name for items,
in a loop that processes items in a row (as I did with 'obj' above).
Denis
OT: Seems the forum does not permit all of BBCode? (I tried to use [s] for srike-through). See
http://en.wikipedia.org/wiki/BBCode
Re: Creating object Creator
Posted: Mon Nov 12, 2012 7:49 pm
by Lafolie
Code: Select all
t = {}
for x=1, 10 do
t[x] = {}
t[x].property = "value"
end