Avraam Mavridis
Avraam Mavridis

Reputation: 8920

how to define a global function that has an event parameter in lua

Assume that I have the following function:

function onTilt( event )
    physics.setGravity( (-9.8*event.yGravity), (-9.8*event.xGravity) ) --Το σωστό
end

which will be used in many different lua files. I want to define it in an external file and then use require to this file so I will not repeat it in each lua file.

The problem is that this function is called like that when it is in the same file with the following (without passing an argument)

Runtime:addEventListener( "accelerometer", onTilt )

Can someone explain me how to define it in an external file and how to call then?

Upvotes: 1

Views: 290

Answers (1)

You can try this minimal external module layout:

-- external module - file named "mymodule.lua"
local M = {}

function M.onTilt( event )
    physics.setGravity( (-9.8*event.yGravity), (-9.8*event.xGravity) )
end

return M

Where you need to use that function you can write (assuming mymodule.lua is put in a directory on your Lua search path):

local mymodule = require 'mymodule'    

-- ... other code ...

Runtime:addEventListener( "accelerometer", mymodule.onTilt )

Upvotes: 3

Related Questions