Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
Split code to multiple files? — Gideros Forum

Split code to multiple files?

test29test29 Member
edited July 2016 in General questions
Is it possible to split code to multiple files?

Example:

I have scene with logic for one level and it starts to be unreadable (too many functions). I can move function to new file (for example Scene:Score) but then I can't access local variables from main scene (i don't want to send that variables when calling function and complicate more things).

I mean, is it possible to have parts of code in multiple files and then when executed it behaves like that all that parts are one file (something like #include in c)?

Sorry for my english, I hope you can undrestand what I'm trying to ask.
«1

Comments

  • antixantix Member
    edited July 2016
    Checkout this little example..
    Game = Core.class()
    function Game:init()
      GAME = self -- Create a global variable for other classes to access
      self.score = 0
    end
     
    Thing = Core.class()
    function Thing:init()
      self.game = GAME -- Save in internal pointer to the game class
    end
     
    function Thing:printScore()
      local game = self.game -- Access and use variables from the game class
      print(game.score)
    end
    Using global variables is an easy way to pass references of one class to another. In this example the Thing class can use ANY variable inside the game class.

    I'm not saying this is the best way to accomplish this but it's what I use and I think it's fantastic.
  • n1cken1cke Maintainer
    edited July 2016
    That's interesting question. I made a function similar to C #include as alternative to global variables and for fun :)
    include = function(...)
    	local chunks = {}
    	local locs = {}
    	for i,filename in ipairs{...} do
    		local file, err = io.open(filename..".lua", "rb")
    		if err then error(err, 2) end
    		local data = file:read("*a")
    		local loc = 1
    		for k,v in data:gmatch("\n") do loc = loc + 1 end
    		locs[i] = loc
    		file:close()
    		chunks[i] = data
    	end
    	local code = table.concat(chunks, "\n;")
    	local func, err = loadstring(code)
    	if err then
    		local line = tonumber(err:match(":(%d+):"))
    		local acc = 0
    		for i,loc in ipairs(locs) do
    			if acc < line and line <= acc + loc then
    				local desc = err:match(":%d+:(.+)")
    				local n = line - acc
    				print(({...})[i]..".lua:"..n..":"..desc)
    				print("in 'include' call of")
    				error("", 2)
    			end
    			acc = acc + loc
    		end
    	end
    	func()
    end
    Each chunk should be 'Excluded from execution' in Gideros Studio (right click on chunk and select this menu item) because it will be loaded by 'include' function itself.
    Usage example:
    include("chunk1", "chunk2", "chunk3")
    It concatenates all chunks into one source file and executes it. My function also handles error messages well so if your chunk has error it will show you exact line of code in it:
    chunk2.lua:6: unexpected symbol near '-'
    in 'include' call of
    main.lua:33: 
    stack traceback:
    	main.lua:25: in function 'include'
    	main.lua:33: in main chunk
    Note that my function is different from C '#include' and you need to use it in separate file, not inside a chunk.

    I also attached full example as Gideros project.

    FIXED: chunk concatenation.
    zip
    zip
    Include.zip
    2K

    Likes: pie

    +1 -1 (+1 / -0 )Share on Facebook
  • test29test29 Member
    Thanks for answers.

    I found that self. variables from scene are passed to all lua files that have code for that scene:

    a.lua

    function Game:init()
    self.a = 5
    end

    b.lua

    function Game:Test()
    print(self.a)
    end

    Question: Are self. variables same as local, are they destroyed when scene closes?
  • SinisterSoftSinisterSoft Maintainer
    yes, but maybe not immediately depending on garbage collection.
    Coder, video game industry veteran (since the '80s, ❤'s assembler), arrested - never convicted hacker (in the '90s), dad of five, he/him (if that even matters!).
    https://deluxepixel.com
  • piepie Member
    edited July 2016
    Self.variables are properties of the class/object whose self is.
    In your example: a is a property of Game class.
    b.lua contains a method which extends Game class - it prints out its property a.

    Properties are destroyed when their owner (object) is destroyed (scenes are Sprite objects, so the answer to your last question is yes) but they are not the same as local vars which are removed as soon as possibile (and are the fastest to access).

    I'd say that properties "stay between" global and local vars because you can access them as long as you can access their "object" (Game, using your example).

    local g=Game.new ()

    g:Test ()
    Is the same of
    print(g.a)


    If you consider any object as a table (it is in lua) a is just an entry of Game table.
    Game[a] = self.a (where self is Game)

    The only issue I can think of, about splitting code from the same class, is about code dependency: you will have to make sure that every "chunk" of the same class is loaded in the correct order. I believe that loading b.lua before a.lua would return an error. :)

  • antixantix Member
    @test29 Just a thought.. Are you using Gideros Studio as your editor? ZeroBrane Studio works with Gideros and has a neat outline pane which makes it a lot easier to move about large code files. In the attached picture you can see it hi lighted in green. You just click one of those links and you zoom straight to the function.

    It would be great if Gideros Studio had stuff like this.
    ZBStudio.png
    1258 x 1040 - 159K

    Likes: n1cke

    +1 -1 (+1 / -0 )Share on Facebook
  • n1cken1cke Maintainer
    @antix, yes, could be handy. Currently best option for Gideros Studio is to use "Ctrl+Alt+L" and "Ctrl+Alt+T" for quick navigation (Edit->Fold/Unfold).

    Likes: antix

    +1 -1 (+1 / -0 )Share on Facebook
  • test29test29 Member
    @antix Yes, I'm using Gideros Studio. I will try ZeroBrane.
  • n1cken1cke Maintainer
    @antix, is Zerobrane Studio works well with Gideros already? It had a bug: no error message if any Gideros C-function crashed. For example,
    stage:addChild("I will crush your game")
    silently closes your app in ZeroBrane.
  • antixantix Member
    ZB Studio is a lot better than maybe when you tried it last. Your line of code produces the following error in ZB Studio..
    main.lua:115: bad argument #1 to 'addChild' (Sprite expected, got string)
    stack traceback:
    main.lua:115: in main chunk
  • n1cken1cke Maintainer
    @antix, I checked ZBS again. I downloaded fresh 1.3 version and still cannot see any errors. Check this slightly modified StarField example:
    require("mobdebug").start()
     
    w=application:getContentWidth()
    h=application:getContentHeight()
    application:setBackgroundColor(0)
     
    stars=Particles.new()
    stars:setPosition(w/2,h/2)
    stage:addChild(stars)
     
    function gameLoop(e)
    	stars:addParticles({{x=0,y=0,size=5,ttl=200,speedX=math.random()-0.5,speedY=math.random()-0.5,decay=1.04}})
    end
     
    stage:addEventListener(Event.ENTER_FRAME,gameLoop)
     
    stage:addChild("I will crush your game")
    I attached the screenshot. Do you use something else in your code to get error messages work?
    ZBS.png
    1275 x 701 - 83K
    ZBS.png 82.9K
  • simwhisimwhi Member
    edited July 2016
    @antix I don't get any error messages when using ZBS either. Which version are you using?
  • antixantix Member
    edited July 2016
    Ahh okay guys, sorry. Mine does the same as yours. As soon as you close the player, the error message pops into the console. Apologies if I caused confusion :)

    Under the "Project" menu, did you set "Lua Interpreter" to "Gideros"?

    I'm still on 1.2 but will upgrade to 1,.3 right now, cheers @n1cke :)
  • simwhisimwhi Member
    I can't get it to work in v1.3.
  • antixantix Member
    @simwhi, These instructions..

    -Add require("mobdebug").start() line to your main.lua script.
    -Select Gideros as an interpreter in ZeroBrane Studio going to Program | Lua Interpreters | Gideros. In addition to enabling debugging, it will also turn on auto-complete for Gideros API calls. If the Gideros player executable is in a default location (/Applications on OSX or C:\Program Files or D:\Program Files on Windows) or in one of the folders listed in PATH, it will be found by the IDE. If the executable is in a different location, you may need to specify this location in cfg/user.lua file (see cfg/user-sample.lua for details on how this is done).

    That's from this page.. http://notebook.kulchenko.com/zerobrane/gideros-debugging-with-zerobrane-studio-ide

    Still no luck?
  • simwhisimwhi Member
    @antix Still no luck. I have all the above settings and I can debug in ZBS. I use it all the time, but no error messages. Strange!! I have to swap back to the Gideros IDE to get any error messages.

    I remember reading somewhere on the forum some time ago that ZBS will support Gideros error messages in an up and coming version. This feature would improve workflow enormously.
  • antixantix Member
    @simwhi it's very odd because it just works for me. Is it working for you @n1cke?
  • n1cken1cke Maintainer
    @antix, errors are still not working. When I close Gideros Player after an error (as you suggested), it gives me only standard "Program completed in 5.45 seconds (pid: 1234)." and nothing more. Can you attach a screenshot with error message in ZBS?
  • @simwhi, do you use the latest development version of zbs (downloaded from github?). that may help.
  • antixantix Member
    Here is a screen dump of what ZeroBrane Studio looks like once an error has occurred in my code. If you have set the interpreter and the path to Gideros is set then I can;t understand why it's not working.

    Maybe @paulclinger can help, he is the creator of ZB Studio.
    ZB Error Output.png
    1263 x 1040 - 126K
  • @n1cke, @simwhi: @keszegh is correct as the showing of errors was added after v1.30 was released, so that's probably why you don't see it in your testing. You need to use the current development version from the master branch or wait for the next release, which should be out this summer.

    @antix, thank you for the ping.

    Likes: n1cke

    +1 -1 (+1 / -0 )Share on Facebook
  • Another option to get the error reporting is to just copy the Gideros interpreter to the "interpreters" folder in ZeroBrane Studio, as it includes all the changes needed to support it.

    Likes: n1cke

    +1 -1 (+1 / -0 )Share on Facebook
  • @paulclinger, maybe for the new version of zbs you should update the gideros api auto-complete file, there are many new functions etc.
  • @keszegh: good idea; is the list here (http://docs.giderosmobile.com/reference/autocomplete.php) up-to-date for auto-complete?

    Likes: antix

    +1 -1 (+1 / -0 )Share on Facebook
  • antixantix Member
    @keszegh, very good idea :)
  • n1cken1cke Maintainer
    edited July 2016
    @paulclinger, yes, that list is up-to-date (because it has latest utf8 library).
    Errors work in development version in all modes (Execute, Debug, Scratchpad), but you need to press "Stop" button to see them (can it be improved?). Also Gideros Studio has to be closed or it will redirect all errors to itself and you will see nothing.
  • > @paulclinger, yes, that list is up-to-date (because it has latest utf8 library).

    ok, I'll use it to update the list in ZBS then.

    > Errors work in development version in all modes (Execute, Debug, Scratchpad), but you need to press "Stop" button to see them (can it be improved?).

    Probably can't do much about it, as the output from `gdrbridge getlog` can only be read after the error is thrown, but since the player continues to run, the IDE doesn't know that the error happened. When you "stop" the application, the IDE reads the error from "gdrbridge" and shows it in the Output panel.
  • antixantix Member
    When you are using ZBStudio you only ever open Gideros Studio to add resources to a project anyway.
  • I pushed changes to ZBS repository that include Gideros API updated for 2016.06. Give it a try and let me know if you notice any issues with it. Paul

    Likes: pie, n1cke, antix

    +1 -1 (+3 / -0 )Share on Facebook
Sign In or Register to comment.