2

My application is able to push a function in a Todo list by using a code like : function test() print("coucou") end

todo:pushtask( test )  -- First push
todo:pushtask( test )  -- Second push

Internally, the todo list is a C table of integer where I push a reference to the passed function took from :

int func = luaL_ref(L, LUA_REGISTRYINDEX);

But how can I detect if I'm pushing the same function ? As per my test, luaL_ref returning do different references even if the same function is pushed (let's say ref #1 and #2) How can I check if #1 and #2 are references to the same function ?

Thanks

Laurent

1 Answers1

1

Functions can be directly compared. To see if you have the same function you need to compare it against the other functions you already have.

luaL_ref does not do that comparison for you (nor should it).

If you want to do this you should keep, in addition to the luaL_ref (or possibly in place of) reference, a lua table with the pushed functions as the keys. This will then let you look up the new function in the table and determine (at hash table access costs instead of list traversal costs) whether that function has been added before or not.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • Thanks for your reply. But, all the TODO list processing is done in C : is it a simple way to do it directly from C code ? – destroyedlolo Nov 12 '15 at 15:11
  • You can do that from `C` just fine. You just need to keep the table in lua (but can manage it with `C` code). You *could* avoid the table and just loop over every item in the references table every time if you wanted to instead (but I **really** don't suggest it). – Etan Reisner Nov 12 '15 at 15:23
  • Unfortunately, I need to loop : a function maybe called only once or many times depending on the context. This todo list is driving events arriving to a GUI : for some of them, each instances are meaningfull (arrival of a data), some are not (request to update the GUI with fresh data that can be only once). And even for "arrival of data", we can considere only the last one in some circonstances (i.e., when its window is in background). – destroyedlolo Nov 12 '15 at 15:50
  • What I will do is to have a table [Func]=>ref on which I will lookup for existing reference before pushing. Consequentely, functions will alway keep the same reference. With only references, looping in my small table will be fast. – destroyedlolo Nov 12 '15 at 15:50
  • You need a loop when you *run* the todo list. You *don't* need a loop when you *add* to the todo list. That's my point. And yes, a table with function keys was the whole point here (in terms of not adding the same table to the list more than once)... Unless was the question here how to keep only one *reference* to any given function but still allow the function to be added to the list multiple times? – Etan Reisner Nov 12 '15 at 15:55