lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

If he wants to store the callbacks (as most often is the case with them) then the sample won't do.

To Ashwin: the trick lies in using the Lua registry (try looking for that in manual, list archive, wiki..) to tie a Lua item (the function) to a unique integer (that'll be the function handle, sort of).

To point you to a working sample, I'd say LuaX GTK+ module would serve well, although that uses gluax linkage macros, but the underlying principles are the same. Other people might point you to sources that do the registry by plain Lua C API.

hope this helps, -ak

26.2.2005 kello 03:50, Ashwin Hirschi kirjoitti:

I'm a novice here. I got a problem that I want to binding a c function with callback (function pointer) to lua.The function is first-class type in lua but it does not the same in c. Have a look of the source:

  // code in c
  void repeat(int time,int (*call)())
     int i;
    for (i=0;i<time;i++) call();

  -- code in lua
  function sayhello() print("Hello!\n") end

  repeat(10,sayhello)  -- print "Hello!" 10 times

You could try something like this [untested!] fragment:

	int my_silly_repeat(lua_State *L)
		int repeat = lua_tonumber(L, 1);
		int i;

		for (i = 0; i < repeat; ++i)
			lua_pushvalue(L, 2);
			lua_call(L, 0, 0);

		return 0;

	lua_register(L, "repeat", my_silly_repeat);

Note that I changed the signature of the repeat function to allow it to be called directly from Lua.

no signature is a signature.