Hello,
I have a collection (main) with three objects childs (camera, curseur & galaxy :
- collection
** Camera
** Curseur
** Galaxy
Curseur and Galaxy have each a script.
In Galaxy script, I put a function (screen_to_world(x, y, z)). Yes, the One And Only.
In Curseur script, I’m calling it.
It’s working :
local action_x, action_y = screen_to_world(action.x, action.y, 9)
put in Curseur.script, and screen_to_world() put in Galaxy script, still give me flawlessly the good result.
I don’t understand : Shouldn’t it fail ?
I don’t complain, but I thought function were local to the script where they are ?
Functions are only local if you add the local
keyword in front of them. Did you do that with screen_to_world()
?
1 Like
No. I didn’t.
Function and Variable are the same thing, then ? Same scope rules ?
They are the same thing. These two are equivalent:
function foobar()
print("Hello")
end
foobar = function()
print("Hello")
end
Functions are values and they can be assigned to variables. In the above example there’s a variable named foobar
and the value assigned to the variable is a function which prints “Hello”.
1 Like
But how can I make sure a function can’t be called by another script ?
Put local
in front of it:
local function foobar()
print("Can't be called by another script")
end
Already tried that, but I have an error message as answer :
ERROR:SCRIPT: main/Curseur/Curseur.script:128: attempt to call global ‘Wheel_Zoom’ (a nil value)
The line 128 :
Wheel_Zoom(1, self)
The function (out of the lifecycle, in last position in the script) :
local function Wheel_Zoom(sens, self)
self.wheel = 0
end
Works flawlessly without the “local”, though.
Make sure you’re defining the local function before calling it, since the function doesn’t get hoisted.
1 Like
The reference to anything you create gets stored in the global Lua table, by default. This means it can be accessed directly, from anywhere. This is really really not a good idea. Always use the local keyword. If you want to use the same function in more than one place, define it in a Lua module. The more you limit scope the better; Lua is great for doing this.
2 Likes
I put the function Wheel_Zoom before all the others (but Init, because you never know), and it’s working with in Local now.
It’s weird, I though the engine would parse the code before executing it.
Thank you for your answers.
I haven’t worked with Lua before Defold, so I’m not an authority on the subject, but I believe this doesn’t have anything to do with the engine and is just a property of Lua the language:
Functions are just variables. You can’t access a variable before you define it, right?
print(name) -- this would just print "nil" since the variable hasn't been defined
local name = "Hunter"
I also don’t believe there’s anything special about init
- it’s just a lifecycle hook, a function that is called at some point in the game object’s lifecycle like all the others.
2 Likes