Hi guys
I wonder if anybody can help with this ...
I have a scene, and I have a function that I would like to reuse inside each scene (it sets up local variables and some basic gfx etc.)
is there a way of using the function in a way similar to below, which would make the variables setup local to the scenes init() function and not the original function? (I know about using self etc and passing that, but I would like to use local vars).
Stage01 = gideros.class(Sprite)
function Stage01:init()
setupStage()
print(num)
end
-- in a separate file
function setupStage
local player = "ninja"
local num = 20
end |
Thanks in advance for any help
Comments
however, if you insist on local then i'm not sure you can do it, as it goes against the meaning of 'local'. i thought that loadfile (EDIT: i meant loadstring) could be an ugly workaround, but according to docs https://www.lua.org/pil/8.html loadstring always compiles in a global enviroment so it is not exactly that its code is injected in the place where it is loaded (as i hoped so).
maybe people with more experience with lua have some ideas.
all in all i'd go with the self.player and self.num route, you anyway probably use these values in other functions of the class too and being self.* vs local * is not that huge speed penalty i guess, i never felt it in my apps.
another way would be to add all these values as parameters to the init function.
Likes: Ninjadoodle
Fragmenter - animated loop machine and IKONOMIKON - the memory game
Likes: Ninjadoodle
Thanks for the help To put it simply I would just like to inject a piece of reusable code into a scenes init function, and only have the code take effect once it has been injected.
This way I don't have to keep rewriting the same code in many scenes, and I can avoid using self.***
for example ...
Likes: Ninjadoodle
Why do you hate self?
If you just need to insert variables you could read them from a json file, if you need functions I am afraid that you would need to use self or at least one global function that returns everything you need.
However, it seems that it is not crazy to localize global functions
Likes: Ninjadoodle
Likes: Ninjadoodle
Thanks heaps for your input on this, I really appreciate it
I've decided to use self + a global function for my stage setup code, and everything is working well.
@antix - lol
Thanks again!
Likes: antix
It's a choice between having to retype the same code for a lot of levels VS using a global function and self, and not having to fix stuff across multiple files every time I make a change.
Let me know what you think
Thanks again!
Likes: Ninjadoodle, snooks, antix