/branches/gsoc2009-ashishs99/Examples/lua/funcptr3/example.i

# · Swig · 69 lines · 42 code · 7 blank · 20 comment · 0 complexity · 99ce21ea9baf5c7c25b9c2d836f1cb58 MD5 · raw file

  1. /* File : example.i */
  2. /*
  3. This demonstrates how to pass a lua function, into some C code and then call it.
  4. There are two examples, the first is as a parameter, the second as a global variable.
  5. */
  6. %module example
  7. %{
  8. #include "example.h"
  9. %}
  10. /* the extra wrappers for lua functions, see SWIG/Lib/lua/lua_fnptr.i for more details */
  11. %include "lua_fnptr.i"
  12. /* these are a bunch of C functions which we want to be able to call from lua */
  13. extern int add(int,int);
  14. extern int sub(int,int);
  15. extern int mul(int,int);
  16. /* this function takes a lua function as a parameter and calls it.
  17. As this is takes a lua fn it needs lua code
  18. */
  19. %inline %{
  20. int callback(int a, int b, SWIGLUA_FN fn)
  21. {
  22. SWIGLUA_FN_GET(fn);
  23. lua_pushnumber(fn.L,a);
  24. lua_pushnumber(fn.L,b);
  25. lua_call(fn.L,2,1); /* 2 in, 1 out */
  26. return (int)luaL_checknumber(fn.L,-1);
  27. }
  28. %}
  29. /******************
  30. Second code uses a stored reference.
  31. *******************/
  32. %inline %{
  33. /* note: this is not so good to just have it as a raw ref
  34. people could set anything to this
  35. a better solution would to be to have a fn which wants a SWIGLUA_FN, then
  36. checks the type & converts to a SWIGLUA_REF.
  37. */
  38. SWIGLUA_REF the_func={0,0};
  39. void call_the_func(int a)
  40. {
  41. int i;
  42. if (the_func.L==0){
  43. printf("the_func is zero\n");
  44. return;
  45. }
  46. swiglua_ref_get(&the_func);
  47. if (!lua_isfunction(the_func.L,-1))
  48. {
  49. printf("the_func is not a function\n");
  50. return;
  51. }
  52. lua_pop(the_func.L,1); /* tidy stack */
  53. for(i=0;i<a;i++)
  54. {
  55. swiglua_ref_get(&the_func);
  56. lua_pushnumber(the_func.L,i);
  57. lua_call(the_func.L,1,0); /* 1 in, 0 out */
  58. }
  59. }
  60. %}