Function within a function within a module won't work if I call it from main

So say I have a module called car.lua and within that module I have:

[lua]function new(params)
newCar = display.newImage(blah blah) – create a car object from image

… – car functions

function spawnCar(event)
– if a car has moved 15 pixels from its original position, spawn another one
end
end[/lua]

and in my main, I call:

[lua]Runtime:addEventListener(“enterFrame”, car.spawnCar)[/lua]

Which returns the error:

[lua]Runtime error
assertion failed!
stack traceback:
[C]: ?
[C]: in function ‘assert’
?: in function ‘getOrCreateTable’
?: in function ‘addEventListener’
?: in function ‘addEventListener’[/lua]

I know that doesn’t work because it’s inside new(), but I need it there because it needs access to newCar which is local, to compare the car coordinates to know when to spawn the next one.

How should I solve this? [import]uid: 106739 topic_id: 20385 reply_id: 320385[/import]

first I would call car.new()
then add your listener. of course before all that you need to require car.

Hope that helps [import]uid: 39088 topic_id: 20385 reply_id: 79704[/import]

Calling car.new creates a new car and seems irrelevant to this problem. Also, I have required car.lua already. [import]uid: 106739 topic_id: 20385 reply_id: 79705[/import]

I dont beleive you can access spawnCar with out calling new first since spawncar resides in new. At least in my project you cant. I have lots and lots of modules. [import]uid: 39088 topic_id: 20385 reply_id: 79715[/import]

car.lua must be like this:
[lua]local Public = {}

local funcion new(params)
local group = display.newGroup()

local car = display.newImag(group, blabla)

function group:newCar()
—code here
end

end
Public.foo1 = new

return Public[/lua]

then in your main file you can call it like you want [import]uid: 16142 topic_id: 20385 reply_id: 79717[/import]

Method Mobile is correct, until you call new the function spawnCar does not exist. On another note, from what you’ve said it seems like you are trying to implement closures, if that is the case what you have provided should look more like this:
Car.lua

function new(params)  
 local newCar = display.newImage(blah blah) -- create a car object from image  
   
 ... -- car functions  
   
 function newCar.spawnCar(event)  
 -- if a car has moved 15 pixels from its original position, spawn another one  
 end  
  
 return newCar  
end  

main.lua

local car1 = car.new({blah}) Runtime:addEventListener("enterFrame", car1.spawnCar) [import]uid: 100558 topic_id: 20385 reply_id: 79745[/import]