Reputation: 91
In the following code, the value of self.player.x is assigned to self.x is assigned at init and tweaked a little bit to the left or right when the state is entered. The PlayerPilotState then manipulates self.player.x every frame and my expectation is that self.x would update along with it. Items such as the tilemap, which are assigned to player as def.tilemap when the player is instantiated, do update as the map changes. How do I ensure that variables such as self.x will update themselves as well? I know that I can update that variable under update every frame, but it seems ineloquent and since I'm fairly new to coding, I don't understand why the player.tilemap does update whereas this variable doesn't. Thank you!
function PlayerPilotState:init(pilot, passenger)
self.player = pilot
self.passenger = passenger
self.animation = Animation {
frames = {2, 3, 2, 8},
interval = 0.1
}
self.player.currentAnimation = self.animation
-- x value at middle of players to make collisions more readable
-- and scalable (for left/right pilot/passenger cases)
self.x = self.player.x
end
function PlayerPilotState:enter(params)
-- determine which side passenger is riding on
self.ridingSide = params.ridingSide
if self.ridingSide == 'left' then
self.x = self.player.x - 1/2 * self.player.width
else
self.x = self.player.x + 1/2 * self.player.width
end
end
Upvotes: 1
Views: 398
Reputation: 89
This is a common misconception for people coming from non-scripted languages. Note that self.x and self.player.x are numbers so when you use assignment:
assert(type(self.player.x) == "number")
self.x = self.player.x -- copy
you are making a copy of that number. On the other hand when dealing with tables or userdata objects then assignment works by making a reference:
assert(type(self.player) == "table")
self.ref = self.player -- reference
Generally speaking you can't really have one number synchronized in the way you have described. It wouldn't be efficient either because you will have to make a redundant "copy" of that value in memory.
This is a question of encapsulation and how/where your data is stored. If you are not sure how to redesign your code remember that "values that change together, belong together". Good luck!
Upvotes: 2