Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Lua function

Tags:

c

api

lua

I would like to handle the following code in Lua and C:

Let's say that I have C function named Foo that is bound to Lua. I call it like following in Lua script:

Foo(15, "bar", function(z) return 2 * z + 1 end)

On the C side, I retrieve the arguments and I can store the number and string in my structure. But what data type would I need to store the anonymous function? And how can I call it later?

like image 570
Jerry Avatar asked Jun 22 '11 23:06

Jerry


1 Answers

You can't store a Lua function as a C data type, anymore than you can store a Lua table as a C data type.

What you can do is use the registry to store this value. The registry is a globally-available table to all C users for storing data. It's often a good idea to pick a single key for all of your code and put a table at that key. This table would contain the values you want to preserve. This will help reduce conflicts from other C code using the registry.

like image 189
Nicol Bolas Avatar answered Sep 30 '22 14:09

Nicol Bolas