Trouble with runtime errors

I’m having trouble with Lua. Below is my code:

function newBean()  
 newBean = display.newImage( "image.png" );  
 newBean.x = display.contentWidth\*0.5  
 newBean.y = -100  
 newBean.myName = "bean1"  
 physics.addBody( newBean, { density=0.9, friction=0.3, bounce=0} )  
  
end  
  
function moveTest(event)  
 local vx,vy = bean1:getLinearVelocity()  
 print (vx,vy)  
end  
Runtime:addEventListener( "enterFrame", moveTest )  

When I try to refer back to “bean1” in the second function I get a runtime error that this is a nil value. How can I refer back to objects created in other functions in order to report on their status later on? [import]uid: 31694 topic_id: 6484 reply_id: 306484[/import]

In the first function you are creating a global object, its name is “newBean” not “bean1”, it simply has a property called “myName” with the value of “bean1”.

If you wanted to access the bean in the move test function you would want to change it to this:

  
function moveTest(event)  
 local vx,vy = newBean:getLinearVelocity()  
 print (vx,vy)  
end  
  

However this would not work for more than one object as you are always storing the new image in the same global variable. What you want to use is return values in your newBean function and then store them off in a table, something like this.

[code]

function newBean()
local newBean = display.newImage( “image.png” );
newBean.x = display.contentWidth*0.5
newBean.y = -100
newBean.myName = “bean1”
physics.addBody( newBean, { density=0.9, friction=0.3, bounce=0} )

return newBean
end

local beans = {}

for i = 1, 5, 1 do
beans[i] = newBean()
end

function moveTest(event)
local vx,vy = beans[1]:getLinearVelocity()
print (vx,vy)
end
Runtime:addEventListener( “enterFrame”, moveTest )

[/code] [import]uid: 5833 topic_id: 6484 reply_id: 22471[/import]