You do not need to call the function by yourself, every time you press a key love.keypress is being called automatically. When you release the key love.keyreleased will be called.
If you define a function, without word local, it will always be globally visible, meaning if you define a function on any of the lua-files you make, and then require it, it will be globally available from any other files.
If you define a local function, it will be only visible inside that file and only after you have declared it. For example if you need to use function that calls other function that calls back to yours, you need to define them before using them. Basically this means that you're splitting something like recursive function into several functions.
Not very good example, but example regardless:
Code: Select all
--f1() -- cannot be called here because f1 isn't declared yet, will give an error
local f2 -- defining f2, so that the variable is visible into function f1
local function f1(a)
print("f1 called with:", a)
if a then return end
f2(1)
end
f2 = function(a)
print("f2 called with:", a)
f1(a)
end
f1()
On the other hand if you create global functions, they can have cross calls without any problem, and they can be called from any other file, which you might want to prevent for most cases.
Code: Select all
function f3(a)
print("f3 called with:", a)
if a then return end
f4(1)
end
f4 = function(a)
print("f4 called with:", a)
f3(a)
end
f3()
Basically this is kind of the reason why up to my understanding C and C++ use separate header files. Also how I understand Lua, which probably isn't the case, lua only executes the code in file only once when first time required. This is something I bumped into couple of days ago, when I had kind of like data in lua files, then I changed the data, and wanted to reset the data by new require. This didn't really work, so I had to do copy of the table from the require and use the copy, then copy the table again when resetting.
For example if otherfile.lua looks like this:
Code: Select all
print("required file otherfile")
function f5()
print("f5 called")
end
return {}
And main file:
Code: Select all
--f5() -- cannot call f5 from here, because the lua doesn't know its existence
local r1 = require 'otherfile'
local r2 = require 'otherfile'
f5() -- can be called from here, because it was declared in otherfile.lua
r1.x = 3
print( r2.x )
You can notice that r1 and r2 are actually same tables. So chanigng r1 also changes r2. Also you can notice that you can call functions defined in other file, as long as you have first required the file, as long as the functions are globally defined, not local functions.
Hopefully this answer was even slightly helpful.