Hello,
I need a function that will receive a vector variable, and see whether it length is more, than some maxLength.
If yes, it will decrease the vector, so that its length is now maxLength. If no, it will return the vector back (with its original size).
function limit (v, max)
self.v = v
self.max = max
if self.v:len() > self.max then
self.v = self.v:normalize()
self.v = self.v*max
return self.v
end
Elsewhere in the program I write
vel = limit (vel, 10) -- 'vel' is a global parameter
The function doesn’t work, saying I am attempting to change a global variable.
The code in a class is used by all the objects you create with that class.
If, for example, the class has a position property, that will be different for all the objects you create with that class, then you need some way of storing position separately for each object, and being able to find it later.
Self does that. It simply means “whichever object is using the code at the moment”, and I think of it visually, as being like a room full of lockers, where each locker holds information for an object in the class, and self is the name on the locker.
So you might give instructions like “when people come into the locker room, get their id number, ID, and make them put their clothes in the locker labelled ID”.
In the same way I used ID as a placeholder for whatever the id number is, “self” is just a placeholder. It tells Codea to replace it with the address of the data for the current object using the code.
function setup()
number = 20
spacecraft = {}
for i = 1, number do
table.insert (spacecraft, Unit (math.random(100,200), math.random(200,300), math.random (1,8)))
print(spacecraft[i]:pos())
end
end
function draw()
background(40, 40, 50)
for i = 1, 20 do
spacecraft[i]:script()
end
end