running a function only once

General discussion about LÖVE, Lua, game development, puns, and unicorns.
User avatar
Inny
Party member
Posts: 652
Joined: Fri Jan 30, 2009 3:41 am
Location: New York

Re: running a function only once

Post by Inny »

Roland_Yonaba wrote:
Inny wrote:This will run the function every time it's called with the arguments from the first call. This doesn't "only run the function once".
Well, that was intended. Moses was kind of inspired by Underscore.js library, at first, where _.once is implemented as a function for lazy initialization. Hence the actual Lua implementation. I do admit the name _.once is a bit misleading, though. :)
In the version you linked, _.once is a partial application of the function _.before with "times" equal to 2

Code: Select all

 _.before = function(times, func) {
  var memo;
  return function() {
    if (--times > 0) {
      memo = func.apply(this, arguments);
    }
    else func = null;
    return memo;
  };
};
The actual function is only executed once, when times == 1, and then the reference is nulled so that the function could be garbage collected. It never executed the function again, and only the return value is retained permanently. In your case, yeah, __.once is misnamed. I'm not sure what a proper rename would be, since yours appears to be a partial application with all parameters filled. I don't think such a thing has a name.
User avatar
Roland_Yonaba
Inner party member
Posts: 1563
Joined: Tue Jun 21, 2011 6:08 pm
Location: Ouagadougou (Burkina Faso)
Contact:

Re: running a function only once

Post by Roland_Yonaba »

Inny wrote:In your case, yeah, __.once is misnamed. I'm not sure what a proper rename would be, since yours appears to be a partial application with all parameters filled. I don't think such a thing has a name.
That is perfectly right.
I'll fix that as soon as possible :)
User avatar
Zilarrezko
Party member
Posts: 345
Joined: Mon Dec 10, 2012 5:50 am
Location: Oregon

Re: running a function only once

Post by Zilarrezko »

If you guys are talking about literally. Only do the function once per game startup, then isn't a coroutine a candidate? literally taking a function as a parameter and running it, but once run the coroutine is dead. (Sorry if I'm misunderstanding).
Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 0 guests