Mark Hula
Mark Hula

Reputation: 313

Corona Lua call external function

I have block_basic.lua that I want to call another function in touch_input.lua

block_basic.lua does:

local screen_touch = require( "touch_input")
local onScreenTouch = screen_touch.onScreenTouch

local function touched( event )
-- 'self' parameter exists via the ':' in function definition

print(onScreenTouch, screen_touch, event)

end

From what I am seeing event seems to be correct (a table), screen_touch is also correct. But the function (screen_touch.onScreenTouch) is always nil and I don't know why

In touch_input.lua I simply have:

local function onScreenTouch( event )
-- no 'self' parameter

etc. etc.

Why is it nil? Why can't I call it?

Upvotes: 1

Views: 851

Answers (2)

vovahost
vovahost

Reputation: 36069

Here is how your files should be:

touch_input.lua:

local M = {}

M.onScreenTouch = function( event )
    --some code here
end

return M

block_basic.lua:

local screen_touch = require( "touch_input")

local onScreenTouch = screen_touch.onScreenTouch


print(onScreenTouch, screen_touch, event)

I tested it. It works 100%.

More info:
http://www.coronalabs.com/blog/2012/08/28/how-external-modules-work-in-corona/
http://www.coronalabs.com/blog/2011/09/05/a-better-approach-to-external-modules/
http://developer.coronalabs.com/content/modules
http://www.coronalabs.com/blog/2011/07/06/using-external-modules-in-corona/

Upvotes: 1

Paul Kulchenko
Paul Kulchenko

Reputation: 26794

You don't show what you return in touch_input.lua, but if you expect the first two lines of your script to work, it needs to be something like this:

local function onScreenTouch( event )
...
return {
  onScreenTouch = onScreenTouch
}

Since you don't get a run-time error on line 2, you may be returning a table already, but you need to make sure that onScreenTouch field of that table points to onScreenTouch function.

Upvotes: 1

Related Questions