As was foretold, we've added advertisements to the forums! If you have questions, or if you encounter any bugs, please visit this thread: https://forums.penny-arcade.com/discussion/240191/forum-advertisement-faq-and-reports-thread/
We're funding a new Acquisitions Incorporated series on Kickstarter right now! Check it out at https://www.kickstarter.com/projects/pennyarcade/acquisitions-incorporated-the-series-2

PA Programming Thread - The Best Servers Are The Ones You Don't Use

1141517192063

Posts

  • Joe KJoe K Registered User regular
    edited November 2010
    GnomeTank wrote: »
    Infidel wrote: »
    urahonky wrote: »
    Sigh... Just when I thought I got it to work... The global variables aren't working after the GDownloadUrl function. I went and put the output() function after the for-loop.. I get the data I'm looking for, but it stops the map from being created. I put the output() after the Gdownloadurl function and it says "undefined".

    That is because the code is inside that callback function (the anonymous function passed to GDownloadUrl)

    So if you put code immediately after it, the variables haven't been touched yet, since the callback is still waiting. This is AJAX for ya.

    Like I said, everything is about events, you're going to need to read up on what is going on here in general I think.

    Also, jQuery. Learn jQuery.

    If you are every doing any kind of AJAX, jQuery is immensely useful to learn. It helps you work around a lot of the stupid idiosyncrasies in dealing with AJAX, as well as giving you a really consistent way to access the DOM throughout your scripts.

    I use to use Prototype, because it's what ships with Rails, but I've switched all my RoR projects over to use jQuery and haven't looked back.

    if you'r mucking about with any browser DOM, jQuery puts the stupidity of the DOM away for you.

    Joe K on
  • AnteCantelopeAnteCantelope Registered User regular
    edited November 2010
    When using arrays in Java, how do you deal with arrays whose length isn't known until during runtime? Previously I've always just made an array that was longer than I needed, but now I'm trying to make an array of objects, and when I try to do loops with something like array.objectMethod I get null pointer exceptions when it gets to the extra array entries.
    My thoughts are:
    I could use some sort of if(array has contents), but I don't know how to check for contents. I've tried if(array != null), but that didn't seem to work.
    I could use a linked list, but I know nothing about them. Would linked list work for this? Can you have a list of objects?

    AnteCantelope on
  • Smug DucklingSmug Duckling Registered User regular
    edited November 2010
    bowen wrote: »
    Ahh dictionaries. The best datastructure.

    Are dictionaries like HashMaps in Java?

    'cause I love me some uh them there HashMaps.

    "How do you -"

    "Hash table."

    Smug Duckling on
    smugduckling,pc,days.png
  • Smug DucklingSmug Duckling Registered User regular
    edited November 2010
    I did some work in Python today. I was generating meshes for a 3D graphics project. Got some pretty neat results:

    badassj.png

    It's cel shaded (and I'm working on the shadow aliasing, don't worry. :P ).

    Smug Duckling on
    smugduckling,pc,days.png
  • InfidelInfidel Heretic Registered User regular
    edited November 2010
    When using arrays in Java, how do you deal with arrays whose length isn't known until during runtime? Previously I've always just made an array that was longer than I needed, but now I'm trying to make an array of objects, and when I try to do loops with something like array.objectMethod I get null pointer exceptions when it gets to the extra array entries.
    My thoughts are:
    I could use some sort of if(array has contents), but I don't know how to check for contents. I've tried if(array != null), but that didn't seem to work.
    I could use a linked list, but I know nothing about them. Would linked list work for this? Can you have a list of objects?

    Vectors.

    Infidel on
    OrokosPA.png
  • AnteCantelopeAnteCantelope Registered User regular
    edited November 2010
    Infidel wrote: »
    When using arrays in Java, how do you deal with arrays whose length isn't known until during runtime? Previously I've always just made an array that was longer than I needed, but now I'm trying to make an array of objects, and when I try to do loops with something like array.objectMethod I get null pointer exceptions when it gets to the extra array entries.
    My thoughts are:
    I could use some sort of if(array has contents), but I don't know how to check for contents. I've tried if(array != null), but that didn't seem to work.
    I could use a linked list, but I know nothing about them. Would linked list work for this? Can you have a list of objects?

    Vectors.

    Thanks, but I have even less idea about vectors and really don't want to try learning yet another new thing right now. I had a look at that page and honestly I have no idea what it means.

    Edit: Fuck it, I've broken all of my arrays now, so I've given vectors a try, but can you explain to me why it seems to store everything as 'Objects', forgetting the specific classes? I put all of my 'Course' objects into a vector, and then I tried to put them into an array of Courses, just because I know how to deal with courses so I thought it would be easier, but it says that it can't put type 'Object' into an array of type 'Course'.

    AnteCantelope on
  • InfidelInfidel Heretic Registered User regular
    edited November 2010
    Infidel wrote: »
    When using arrays in Java, how do you deal with arrays whose length isn't known until during runtime? Previously I've always just made an array that was longer than I needed, but now I'm trying to make an array of objects, and when I try to do loops with something like array.objectMethod I get null pointer exceptions when it gets to the extra array entries.
    My thoughts are:
    I could use some sort of if(array has contents), but I don't know how to check for contents. I've tried if(array != null), but that didn't seem to work.
    I could use a linked list, but I know nothing about them. Would linked list work for this? Can you have a list of objects?

    Vectors.

    Thanks, but I have even less idea about vectors and really don't want to try learning yet another new thing right now. I had a look at that page and honestly I have no idea what it means.

    Well what are you doing exactly that you have to make an array that's too large?

    Infidel on
    OrokosPA.png
  • AnteCantelopeAnteCantelope Registered User regular
    edited November 2010
    Why is it that every time I ask for help in here, the help people offer doesn't stop my program from breaking, so I get really frustrated, pore over every line of code, and then discover I've done something incredibly stupid? Last time it was because my code was working fine but I'd never made it output the results, and this time it's because I've got a for(int i = o; i < length; i++) loop, and for some fucking retarded reason I've put an i++ inside the loop too.
    Sorry for wasting everyone's time.

    AnteCantelope on
  • TincheTinche No dog food for Victor tonight. Registered User regular
    edited November 2010
    You can also consider ArrayLists (vectors are synchronized, arraylists aren't, there are some differences in the way they manage their capacity, but pretty similar).

    Try handling your lists and vectors using the List interface, that can give you the freedom later on to switch your container implementation more easily (like switching from an arraylist to a linked list if it turns out, for example, that you don't need O(1) random access (because you, for example, always iterate the whole list) but fast element removal from the middle of the list).

    In practice, this means doing:

    List<Course> courseList = new ArrayList<Course>();

    instead of

    ArrayList<Course> courseList = new ArrayList<Course>();

    Then, later on, you can change the first line to:

    List<Course> courseList = new LinkedList<Course>();

    Tinche on
    We're marooned on a small island, in an endless sea,
    Confined to a tiny spit of sand, unable to escape,
    But tonight, it's heavy stuff.
  • kdrudykdrudy Registered User regular
    edited November 2010
    Infidel wrote: »
    When using arrays in Java, how do you deal with arrays whose length isn't known until during runtime? Previously I've always just made an array that was longer than I needed, but now I'm trying to make an array of objects, and when I try to do loops with something like array.objectMethod I get null pointer exceptions when it gets to the extra array entries.
    My thoughts are:
    I could use some sort of if(array has contents), but I don't know how to check for contents. I've tried if(array != null), but that didn't seem to work.
    I could use a linked list, but I know nothing about them. Would linked list work for this? Can you have a list of objects?

    Vectors.

    Thanks, but I have even less idea about vectors and really don't want to try learning yet another new thing right now. I had a look at that page and honestly I have no idea what it means.

    Edit: Fuck it, I've broken all of my arrays now, so I've given vectors a try, but can you explain to me why it seems to store everything as 'Objects', forgetting the specific classes? I put all of my 'Course' objects into a vector, and then I tried to put them into an array of Courses, just because I know how to deal with courses so I thought it would be easier, but it says that it can't put type 'Object' into an array of type 'Course'.

    To answer your question, with Vectors you can do one of two things. You can type the Vector by putting the type after Vector when you initialize it:
    Vector<Course> courses = new Vector<Course>();
    
    or you can cast the object coming out of the Vector like so:
    Course course = (Course) courses.elementAt(0);
    

    Vectors exist to store whatever you want to throw in them and don't restrict your size so that is why they default to Objects. They realized sometimes you want specific objects in a data structure like this so they added the ability to type them like in my first example. If you know everything you put in the Vector is going to be of that one type that is the way to go. In practice that is usually what you will be doing with them.

    kdrudy on
    tvsfrank.jpg
  • VThornheartVThornheart Registered User regular
    edited November 2010
    So I've been working on a new website for the Cookie Brigade... doing it up in ASP.NET MVC 3... and this morning I realized there was probably a set of WordPress plugins that would do everything I'm creating from scratch, and I could just go download them and tweak the visual themes and I'd be done.

    It was true.

    Strangely, I don't feel elation about it... I instead feel a strange mix of relief and sadness, as it will be done in days now instead of weeks, but I don't feel like I will have actually *made* it.

    Do you guys know what I mean? I'm sure as fellow programmers, you've probably run into this before... the uncomfortable urge, against better judgement, to do it yourself just to say that you did it (or perhaps to prove to yourself that you *could* do it? I'm still not sure quite what this emotion is I'm feeling that compels me to pretend that I never saw those WordPress plugins...).

    Anyways, I'm going to go the WordPress route and ignore the voices in my head telling me that it'd be more fun/more satisfying to do it myself from scratch... but I figured I'd share this experience to see if other developers frequently run into similar situations and emotions or if merely I have some kind of developer equivalent of OCD.

    VThornheart on
    3DS Friend Code: 1950-8938-9095
  • Jimmy KingJimmy King Registered User regular
    edited November 2010
    Every time I do something with a web framework like Django, Pylons, Mason, etc. I get that same feeling. Especially when it's something that was going to be fairly small anyway. I feel so lazy for not having written my own db abstraction and classes and whatnot.

    I'm going back and forth right now about how to write my XMPP server in Python. Do I do it all from the ground up (well, I'll probably use an XMPP lib rather than writing my own XMPP parser) or do I use Twisted? I glanced over the twisted docs and it felt like using Twisted is removing 90% of what makes doing this sort of stuff fun for me.

    Jimmy King on
  • VThornheartVThornheart Registered User regular
    edited November 2010
    lol, I understand completely what you mean Jimmy! =)

    I guess the recommended course of action will have to really be based on what you want to get out of it. If you're writing an XMPP server for educational or fun purposes, I personally think that rolling your own is great (though others may disagree, and it may be that same voice in my head telling me to write the Cookie Brigade website from scratch =) ).

    If it's for some kind of deadline or important task, well... that's where it gets hard. Logically it would make sense to use what will remove the most work... but I can understand the implementation being most of the fun, and I deeply empathize with that sentiment. =)

    So what's it for? Is it for a casual experimentation project? Something for work? For a project that has a pending deadline? For a person or group of people who need it as soon as possible?

    It's funny, when I was a kid some developers that were friends of my Dad told me that there really isn't "programming" in their field anymore, it's stitching together things that other people have made until it's done. That was probably 15 years ago that they told me that... and now having been in the real workforce for a couple of years, I'm beginning to realize that it's both true and mildly depressing. =)

    VThornheart on
    3DS Friend Code: 1950-8938-9095
  • Jimmy KingJimmy King Registered User regular
    edited November 2010
    Oh, it's purely for fun and general skill set bulding. I feel like my skills are stagnating and I'm somewhat pigeonholed into "perl web back end developer" stuff, which is a pretty terrible role to be stuck in what with Perl dying off like it has and me likely looking for work again in the next 6 months or so (I'm the last of about 30 developers left at my company playing at developer, dba, and sys admin).

    I've been doing some Android dev (I work in the mobile industry anyway, so it seems like a good thing to do) and recently started messing with Python as a replacement for Perl. For my next Android app I decided to do an XMPP client and then I'll probably do a server in Python to go with it and possibly a desktop client also using Python.

    The comment about not really programming anymore somewhat makes sense, but I don't fully agree with it. Sure, there's a lot of using other people's libraries, but aside from doing very simple stuff with a framework, there's still usually plenty of logic and whatnot to be thought out. It's definitely frequently higher level, just like using Perl or Python as opposed to C, but on a project of any size there's still plenty of "real programming" going on. Plus someone is out there doing "real programming" and writing those libraries that are being stitched together and there will always be a need for people doing that.

    Jimmy King on
  • HallowedFaithHallowedFaith Call me Cloud. Registered User regular
    edited November 2010
    I spent days investigating various frameworks that offered all these "amazing" sollutions and in the end, I realized that not only do I NEED to write my stuff from scratch, but at the end of the day I am relying on a framework that will change and grow and maybe not even exist in the future, and who knows how it might be to tweak this or add/remove that.

    I support those projects of course, but for me, it is just better to sit down with a piece of paper, figure out what I want my stuff to do, and then start writing.

    HallowedFaith on
    I'm making video games. DesignBy.Cloud
  • Jimmy KingJimmy King Registered User regular
    edited November 2010
    Yeah, I've definitely run into issues with having a framework not be able to do something I needed, even when it was something that seemed like it should be perfectly reasonable. Django got me on that most recently.

    I had some objects where it was like Main Object -> Multiple Sub-Objects -> Multiple Sub-Sub-Objects. The main object could have a varying number of sub objects and the sub objects could each have a varying number of sub-sub objects. Django's automagic form creation just could not deal with that at all. It was able to add sub objects ok if those did not also have the sub-sub objects, but even that was handled kind of stupid. It was also able to have sub objects and sub-sub objects, but that was a total pain in the ass. Combine the two together and it just did not work at all and I wasted probably 10 hours on failing at something I could have just done on my own without a framework pretty easily.

    That was pretty disappointing because it should have been so quick and easy. I can do that nonsense writing the cgi on my own, but it's so tedious and dull to do that I will quite clearly go to nearly any length to avoid doing it.

    Jimmy King on
  • SaerisSaeris Borb Enthusiast flapflapflapflapRegistered User regular
    edited November 2010
    bowen wrote: »
    Ahh dictionaries. The best datastructure.

    Are dictionaries like HashMaps in Java?

    'cause I love me some uh them there HashMaps.

    "How do you -"

    "Hash table."

    This is probably the best part of Lua. Its only data structure is a hash table. It's even pretty efficient for use as an array, since the VM transparently maintains both a hash table and an array behind the scenes, storing sequential-from-1 indexes in the array portion.

    If you're ever bored one day, take a look at the hashing algorithm in Lua's source. It's pretty neat. From the source:
    /*
    ** Hash uses a mix of chained scatter table with Brent's variation.
    ** A main invariant of these tables is that, if an element is not
    ** in its main position (i.e. the `original' position that its hash gives
    ** to it), then the colliding element is in its own main position.
    ** Hence even when the load factor reaches 100%, performance remains good.
    */

    Saeris on
    borb_sig.png
  • HallowedFaithHallowedFaith Call me Cloud. Registered User regular
    edited November 2010
    Nevermind, just looked further into the development restrictions of even simulating running code and it's a no go.

    Welp, there goes that idea. ;)

    HallowedFaith on
    I'm making video games. DesignBy.Cloud
  • Smug DucklingSmug Duckling Registered User regular
    edited November 2010
    Woo, got nice antialiasing on my cel shaded objects (relative to my last attempt anyway):

    badass2.png

    Smug Duckling on
    smugduckling,pc,days.png
  • Monkey Ball WarriorMonkey Ball Warrior A collection of mediocre hats Seattle, WARegistered User regular
    edited November 2010
    Very pretty. Though red is cooler.

    Concerning Lua, I read up on it yesterday, because I was considering starting to use the programming skills I have learned this quarter to some sort of use writing a WoW addon or something, and I guess it doesn't support OOP? Wikipedia seems to imply you can get around this using some sort of meta-table or something, but I have to say, I like OOP, and it seems weird to have an interpreted language that doesn't support it natively.

    Monkey Ball Warrior on
    "I resent the entire notion of a body as an ante and then raise you a generalized dissatisfaction with physicality itself" -- Tycho
  • KakodaimonosKakodaimonos Code fondler Helping the 1% get richerRegistered User regular
    edited November 2010
    It is a bit of work to set up virtual addressing tables and other ephemera needed to support OOP. And it's easy to do it poorly and get a huge performance hit in the language.

    Kakodaimonos on
  • Monkey Ball WarriorMonkey Ball Warrior A collection of mediocre hats Seattle, WARegistered User regular
    edited November 2010
    Structured / Procedural it is then.

    I will probably still do it though.

    Monkey Ball Warrior on
    "I resent the entire notion of a body as an ante and then raise you a generalized dissatisfaction with physicality itself" -- Tycho
  • InfidelInfidel Heretic Registered User regular
    edited November 2010
    Structured / Procedural it is then.

    I will probably still do it though.

    If you're doing WoW addons you won't be that concerned, it's mostly event based and you don't need OOP really.

    Simple and lightweight is key for addons.

    Infidel on
    OrokosPA.png
  • AnteCantelopeAnteCantelope Registered User regular
    edited November 2010
    Infidel wrote: »
    When using arrays in Java, how do you deal with arrays whose length isn't known until during runtime? Previously I've always just made an array that was longer than I needed, but now I'm trying to make an array of objects, and when I try to do loops with something like array.objectMethod I get null pointer exceptions when it gets to the extra array entries.
    My thoughts are:
    I could use some sort of if(array has contents), but I don't know how to check for contents. I've tried if(array != null), but that didn't seem to work.
    I could use a linked list, but I know nothing about them. Would linked list work for this? Can you have a list of objects?

    Vectors.

    Thanks for the vectors hint. I'm probably breaking some convention or another, but I've now got lines like

    if(student.getEnrolment().elementAt(i).getEnrolledCourse().getCourseCode().compareTo(courseCode) == 0)

    and even though it's not pretty, it's working the way I want it to. Loving vectors right now.

    AnteCantelope on
  • InfidelInfidel Heretic Registered User regular
    edited November 2010
    Infidel wrote: »
    When using arrays in Java, how do you deal with arrays whose length isn't known until during runtime? Previously I've always just made an array that was longer than I needed, but now I'm trying to make an array of objects, and when I try to do loops with something like array.objectMethod I get null pointer exceptions when it gets to the extra array entries.
    My thoughts are:
    I could use some sort of if(array has contents), but I don't know how to check for contents. I've tried if(array != null), but that didn't seem to work.
    I could use a linked list, but I know nothing about them. Would linked list work for this? Can you have a list of objects?

    Vectors.

    Thanks for the vectors hint. I'm probably breaking some convention or another, but I've now got lines like

    if(student.getEnrolment().elementAt(i).getEnrolledCourse().getCourseCode().compareTo(courseCode) == 0)

    and even though it's not pretty, it's working the way I want it to. Loving vectors right now.

    Yeah, that is all correct I'm sure, to pretty things up you may want to break things down just to keep it readable and maintainable.

    Just things like
    Course course = student.getEnrolment().elementAt(i).getEnrolledCourse();
    if (course.getCourseCode().compareTo(courseCode) == 0) {
    ...
    

    sometimes more typing is good, less eye-glazy. :D

    Infidel on
    OrokosPA.png
  • JasconiusJasconius sword criminal mad onlineRegistered User regular
    edited November 2010
    Funny, I was just coming here to ask about OOP LUA

    I am having a bitch of a time getting it going and for some reason my tables seen to be getting garbage collected or something... I don't know. It's a big PITA.

    Objective-C has made me weak.

    Jasconius on
  • VThornheartVThornheart Registered User regular
    edited November 2010
    Wow Duckling, that's looking good! Nice!

    VThornheart on
    3DS Friend Code: 1950-8938-9095
  • SaerisSaeris Borb Enthusiast flapflapflapflapRegistered User regular
    edited November 2010
    Lua has just enough in the language that you can implement almost every object-oriented concept. Closures are very powerful. You have to write things like inheritance yourself, but that's actually not too hard (each class would just provide a list of method names to inherit). You'd really want to be familiar with the language before you tried to force OOP onto it, though.

    Jasc, perhaps you could post some code?

    Saeris on
    borb_sig.png
  • JasconiusJasconius sword criminal mad onlineRegistered User regular
    edited November 2010
    Saeris wrote: »
    Lua has just enough in the language that you can implement almost every object-oriented concept. Closures are very powerful. You have to write things like inheritance yourself, but that's actually not too hard (each class would just provide a list of method names to inherit). You'd really want to be familiar with the language before you tried to force OOP onto it, though.

    Jasc, perhaps you could post some code?

    OK so I am LUA retarded, so there's some ham-handedness in here but the code is as follows:
    House = {}
    House_mt = { __index = House }
    
    require("house_segment")
    
    function House:create()
        local new_inst = {}
        setmetatable(new_inst, House_mt)
    	
    	new_inst.house_segments = {}
    	
    	new_inst.obstacle = Obstacle:create()
    	
    	math.randomseed(os.time())
    	
    	local color_index = math.random(1,3)
    	
    	new_inst.house_segments[1] = HouseSegment:createRoof(color_index)
    	new_inst.house_segments[2] = HouseSegment:createRoof(color_index)
    	new_inst.house_segments[3] = HouseSegment:createRoof(color_index)
    	
    	new_inst.obstacle.xModifier = math.random(-110, 110)
    	
        return new_inst
    end
    
    function House:animateHorizontally(targetX, speed)
    	
    	transition.to(self.house_segments[1], {time = speed, x = targetX - self.house_segments[2].width})
    	transition.to(self.house_segments[2], {time = speed, x = targetX})
    	transition.to(self.house_segments[3], {time = speed, x = targetX + self.house_segments[2].width})
    	transition.to(self.obstacle, {time = speed, x = targetX + self.obstacle.xModifier, onComplete = self.animationComplete})
    	
    end
    
    function House:animationComplete()
    	
    	if self.house_segments then
    	
    		for i = 1,3 do
    			self.house_segments[i]:removeSelf()
    		end
    	
    		self.obstacle:removeSelf()
    	
    		self = nil
    	
    	end
    	
    end
    

    OK so. House object gets created by main.lua and stored into a global array (I think?) and then animateHorizontally is called on the object shortly thereafter.

    The last transition has a complete event handler which calls animationComplete()

    However no matter what, by the time this event fires, every property of the object seems to have become nil

    So that if self.house_segments then line never returns true

    I have no idea why. I guess it's getting swept up... or somehow the function reference in animateHorizontally() is incorrect.

    Thoughts?

    Jasconius on
  • PhyphorPhyphor Building Planet Busters Tasting FruitRegistered User regular
    edited November 2010
    onComplete = self.animationComplete only saves a reference to the function definition, not the object. Since it's defined as a member function with self and all that, how are you calling it, given that you don't pass self to transition.to?

    Phyphor on
  • JasconiusJasconius sword criminal mad onlineRegistered User regular
    edited November 2010
    Excellent question: I have no idea.

    I've been working all day so I'm fried. If you have an idea on how to make it work, that would be helpful. Other than that I'll get back on it on Sunday

    Jasconius on
  • SaerisSaeris Borb Enthusiast flapflapflapflapRegistered User regular
    edited November 2010
    I'm going to guess animationComplete() is being called with the wrong self somehow, like Phyphor said. That would make it seem like all of the House's properties have gone to nil. I'd have to see the code that actually calls onComplete() to know for sure, though.

    That's one of the tricky things about Lua: there is no implicit "self" or "this" parameter in method calls. The declaration "function Class:Method()" is just syntactic sugar for "function Class.Method(self)". It doesn't actually instruct the language to always pass self to that method; you still have to do that yourself. You either have to call it with the "obj:Method()" syntax (with a : instead of a .), or explicitly pass in a value for self. Sorry if I'm reiterating what you already know.

    Saeris on
    borb_sig.png
  • DusdaDusda is ashamed of this post SLC, UTRegistered User regular
    edited November 2010
    I'm totally jealous of everyone who is using ASP.NET MVC 3 and the new Razor view engine. I won't be able to use them until my next project.

    Really looking forward to not having to see tag soup ever again.

    Dusda on
    and this sig. and this twitch stream.
  • JasconiusJasconius sword criminal mad onlineRegistered User regular
    edited November 2010
    Saeris wrote: »
    I'm going to guess animationComplete() is being called with the wrong self somehow, like Phyphor said. That would make it seem like all of the House's properties have gone to nil. I'd have to see the code that actually calls onComplete() to know for sure, though.

    That's one of the tricky things about Lua: there is no implicit "self" or "this" parameter in method calls. The declaration "function Class:Method()" is just syntactic sugar for "function Class.Method(self)". It doesn't actually instruct the language to always pass self to that method; you still have to do that yourself. You either have to call it with the "obj:Method()" syntax (with a : instead of a .), or explicitly pass in a value for self. Sorry if I'm reiterating what you already know.

    That makes sense. I just don't know how to do it in a prim and proper way.

    I have a Plan B solution where I will just store all these objects in a global array and then constantly loop through to check what needs to be cleaned up.

    Not pretty, but it suits my purposes and this is my first try.

    Jasconius on
  • SaerisSaeris Borb Enthusiast flapflapflapflapRegistered User regular
    edited November 2010
    There are two ways to handle method callbacks in Lua.
    In either case, you're changing this line:
    transition.to(self.obstacle, {time = speed, x = targetX + self.obstacle.xModifier, onComplete = self.animationComplete})
    

    In the first method, you'd give the code performing the callback the proper self value. In your example, this would change that line to
    transition.to(self.obstacle, {time = speed, x = targetX + self.obstacle.xModifier, obj = self, onComplete = self.animationComplete})
    
    and then have it call onComplete as info.onComplete(info.obj), where info is that table.

    In the second method, you'd just use a closure to capture the proper self value. In your example, this would change that line to
    transition.to(self.obstacle, {time = speed, x = targetX + self.obstacle.xModifier, onComplete = (function() self:animationComplete() end)})
    
    and then the code doing the callback doesn't need to be changed. The closure is referencing the self value that existed when it was created; there's nothing special about the variable name "self" here. You could just as easily do
    local obj = self
    local param = 1
    transition.to(self.obstacle, {time = speed, x = targetX + self.obstacle.xModifier, onComplete = (function() obj:animationComplete(param) end)})
    

    Either way is fine. The latter might be less complex. Closures are very lightweight, so there's no concern over memory use. Tables are 40 bytes plus another 40 bytes per key/value pair, whereas closures are 28 bytes plus 32 bytes for each distinct upvalue (captured local variable).

    Saeris on
    borb_sig.png
  • JasconiusJasconius sword criminal mad onlineRegistered User regular
    edited November 2010
    Ooooohhh. The second one appears to work and I like it very much.

    I shall slaughter a thousand goats in your honor.

    Jasconius on
  • InfidelInfidel Heretic Registered User regular
    edited November 2010
    Doing callbacks with anonymous functions and closures is the better way in languages anyways. :D

    Doing a lot of them in Javascript lately. D:

    Infidel on
    OrokosPA.png
  • JasconiusJasconius sword criminal mad onlineRegistered User regular
    edited November 2010
    Oh yes this is making my life so much easier.

    It is solving many of my problems

    Jasconius on
  • halkunhalkun Registered User regular
    edited November 2010
    First a warning, I ask all the more seasoned programmers not to get a shotgun and hunt me down the the horrific scum I am for using a "goto" statement in Perl. It was the only solution I can think of.

    I'm doing database stuff and would like the program to silently wait if there was an error (It loops every 5 seconds, so I want it to just try again.)

    here's the meat of the loop
    for (;;)
    {
    
    START:
    
    # now connect and get a database handle
    $dbh = DBI->connect($dsn, $user, $pass)
         or goto START;    #PLEASE DON'T HURT ME!!!!
    
    $sth = $dbh->prepare
            ('select id, UNIX_TIMESTAMP(last_active) from machine_state ;');
    
    $sth -> execute;
    
    while(@row = $sth->fetchrow_array())
    {
            $current_time = time;
            if (($row[1] != 0))
            {
                    if ($current_time > ($row[1]+45))
                    {turn_off($row[0]);}
            }
    }
    
    sleep(5);
    
    }
    

    The problem is this spits out errors something fierce when I turn off the database. I was kind of hoping for it just to silently fail and wait for the database to come back online again.

    Is there a better way?

    halkun on
    dA03mgx.png
  • MKRMKR Registered User regular
    edited November 2010
    die()

    You probably shouldn't be using goto if you don't know about die. :P

    It's like going after malloc() before you know anything about memory.

    I haven't done perl in ages, but none of that looks right. Someone with more perl-fu will have to help.

    MKR on
This discussion has been closed.