Variable Parameters

This question is a little goofy and I’m not really sure how to explain it.

Below is a simple example of what I’m trying to accomplish.

[lua]

spaceShip = display.newCircle(50,50,50)

function move(object, axis, value)

     object.axis = object.axis + value

end

move(spaceShip, “y”, 10)

[/lua]

Thanks!

You can’t do that.  You are creating a new variable called “axis” not setting .y.  You  have to do:

function move( object, axis, value )      if axis == "y" then           object.y = object.y + value      else           object.x = object.x + value      end end

Rob

Alternatively if the field exists on the object you could do this:

function incr( object, fieldName, value ) if(object and object[fieldName]) then object[fieldName] = object[fieldName] + value end end

This assumes of course that the value in the field and the value in ‘value’ argument are numbers.

Ah yes I should have thought of that.  Thanks roaminggamer!

To make my sample code work I would have needed to write it like this.

[lua]

spaceShip = display.newCircle(50,50,50)

function move(object, axis, value)

     object[axis] = object[axis] + value

end

move(spaceShip, “y”, 10)

[/lua]

By the way, there is a more efficient way to do this specific example.

https://docs.coronalabs.com/daily/api/type/DisplayObject/translate.html

spaceShip:translate( 10, 0 ) -- Move +10 x; No change in y

You can’t do that.  You are creating a new variable called “axis” not setting .y.  You  have to do:

function move( object, axis, value )      if axis == "y" then           object.y = object.y + value      else           object.x = object.x + value      end end

Rob

Alternatively if the field exists on the object you could do this:

function incr( object, fieldName, value ) if(object and object[fieldName]) then object[fieldName] = object[fieldName] + value end end

This assumes of course that the value in the field and the value in ‘value’ argument are numbers.

Ah yes I should have thought of that.  Thanks roaminggamer!

To make my sample code work I would have needed to write it like this.

[lua]

spaceShip = display.newCircle(50,50,50)

function move(object, axis, value)

     object[axis] = object[axis] + value

end

move(spaceShip, “y”, 10)

[/lua]

By the way, there is a more efficient way to do this specific example.

https://docs.coronalabs.com/daily/api/type/DisplayObject/translate.html

spaceShip:translate( 10, 0 ) -- Move +10 x; No change in y