I would like to know how to make a C-function and be able to tell Lua about it, then call it from Lua. I have all the Lua Libraries installed on my Mac OSX 10.4 computer.
Asked
Active
Viewed 7,720 times
3 Answers
7
There's an excellent example of Lua-C integration here and here.
If you just need to export a function into the global namespace, then:
- Declare the function (let's call it
f
) with signaturelua_CFunction
. - Call
lua_register(L, "myfunc", f)
, with L being the Lua state, and function =f
. - Run the lua code. Then
f
will be available in the global namespace asmyfunc
.
If you're going to use the stock interpreter then you might want to make a library. This guy wrote an article for Lua Programming Gems that explains how to do it. The sources are available online.

Pablo A. Costesich
- 728
- 4
- 14
-
Where in the lua-5.x.x file should I put this? should it be a .c file? – SHa Nov 17 '10 at 02:00
-
Wait, are you using the stock interpreter code or embedding lua in your own app? – Pablo A. Costesich Nov 17 '10 at 13:08
3
You can register functions using luaL_register
Look at some examples and explanation in PiL

Doug Currie
- 40,708
- 1
- 95
- 119
2
My answer here includes a nice, short example about making a very simple game using C and Lua together. In my biased opinion, it's a great starting point.

Community
- 1
- 1

Mark Rushakoff
- 249,864
- 45
- 407
- 398