It looks like you're new here. If you want to get involved, click one of these buttons!
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.
Thank you for your help,
Alex
Comments
Alex
you should only use "self" inside a class. This should work..
PS you were also missing an
end
statement after yourif
Thank you very much. I read your post about the "self" word, but I am still struggling with it)
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.
Why would this function not work?
It is intended to return the pod vector, which I will be using in the main tab
function Unit:pos()
return self.pos
end
Maybe you are calling it incorrectly
The problem lies somewhere in this line:
print(spacecraft[3]:pos())
I have previously initialized each object in he table.
That code looks all right, you'll need to post more code
I will, thank you for your feedback.
And the function itself
@alexNaumov - this is an interesting problem.
I think you may find it works if you change the
pos
function name in the Unit class, to something else, egposition
. That worked for me.The reason, I think, is that
self.pos
can refer to both the functionUnit:pos
and the class variableself.pos
, so you need to have different names.When you call
spacecraft[i]:pos()
, Codea actually callsspacecraft[i].pos(self)
, then it finds thatself.pos
is a vec2 and causes an error.You can't have a function named the same as your variable
You could use metatables to make it so that what you are doing works, or you could just rename one of them