It looks like you're new here. If you want to get involved, click one of these buttons!
players = {} players[1] = {} players[1]["money"] = 2 --this is my global var; vartest=Core.class(Sprite) function vartest:init(variable) self.refVar = variable print( "INIT:", self.refVar, players[1]["money"]) self:addEventListener(Event.MOUSE_DOWN, self.onMouseDown, self) end function vartest:onMouseDown(event) self.refVar = self.refVar+4 print( "MOUSE_DOWN:", self.refVar, players[1]["money"]) --those values (in my dreams) should be equal. end --[[ how could I pass via parameters the reference to my variable instead of its value? ]] local vartest = vartest.new(players[1]["money"]) stage:addChild(vartest) |
Comments
a simple way you can do that is
BTW: You can also access the
Author of Learn Lua for iOS Game Development from Apress ( http://www.apress.com/9781430246626 )
Cool Vizify Profile at https://www.vizify.com/oz-apps
I accepted your answer on my enthusiasm, but as I tried it, it gives me the same behaviour :-/ ..am I still missing something?
It seems that lua is copying the variable value rather than referencing to the variable itself, either if it's referenced from outside of the constructor.
You can copy/paste my example in a blank project to see it (not) working -of course if you have time to look for that
Thank you again
P.
So if you encapsulate your variable into a table and pass it, the table field should be modified by reference (from Lua Manual)
What is happening is that you are adding the variable to the instance of Core.class(Sprite) and since you are using the same names for the class and the instance, you are messing the Lua VM a lot.
the function vartest:init has to be the global function BUT the mouse handler has to be part of the instance,
change the names of the variables to cVartest for the class and vartest for the instance and then try to print them in both the init and onMouseDown functions to see the difference
with the functions as cVartest:init and cVartest:onMouseDown
print(self, vartest, cVartest) --> 0x10a0e6210, 0x10a0e6210, 0x10a0e5e10
Author of Learn Lua for iOS Game Development from Apress ( http://www.apress.com/9781430246626 )
Cool Vizify Profile at https://www.vizify.com/oz-apps
BUT, Lua tables are reference object to start with. E.g.
a={1,2,3}
means
1) allocate an anonymous table {1,2,3} in memory
2) Make "a" point to it.
If I do
b=a
Now, b is pointing to the same table as a. (a shallow copy). The actual value held by a and b is, eg, 0x0BADF00D a memory location. and that's what gets passed through to functions.
https://github.com/gideros/gideros
https://www.youtube.com/c/JohnBlackburn1975