Skip to main content
GameDev.net gamedev.net
🔒 Locked

Lua Callbacks in C

Started by HyperHacker Nov 23, 2009 at 10:47 PM 2 replies 3.4k views
Original Post
HyperHacker
HyperHacker
I'm writing a program that uses Lua, and I've hit a snag. I want to pass a Lua function to a C function as a callback. Like: someCFunction(function(foo) print(foo) end) Then at some point the script calls another C function, which calls the callback passed above. However I don't see a way to retrieve functions passed as parameters in C. I can call it when it's still on the stack, but I need to retrieve it and store it to call later. Is this possible?
---------------------------------dofile('sig.lua')
Ximmer
Ximmer
I think you have 2 options,

#1 Pass the name of the function and store that for a later:

lua_pushstring(L, callback_function_name);
lua_getglobal(L, -1);

#2 Save the function on the stack to a temporary unique global and save the name of that global in your event or what have you
ddn3
ddn3
This page should help. Bascialy it's like what Ximmer suggested, but since this situation occurs so often, Lua has a built in functionality to address it.

http://www.lua.org/pil/27.3.1.html
http://bigbucketsoftware.com/2006/03/15/lua-and-the-registry/

Lua has a registry table for storing away Lua side objects which can then be referenced again from the Lua side using just a key.

-ddn
HyperHacker
HyperHacker
Thanks, that looks like it'll do.
---------------------------------dofile('sig.lua')

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.