How can I make a C function that I can call from Lua?

I would like to know how to make a C-function and be able to tell Lua about it, and then call it from Lua. I have all the Lua libraries installed on my Mac OSX 10.4 computer.

+4
source share
3 answers

Here's a great example of Lua-C integration here and here .

If you just need to export the function to the global namespace, then:

  • Declare a function (let's call it f ) with the signature lua_CFunction .
  • Call lua_register(L, "myfunc", f) , where L is the Lua state and the function = f .
  • Run the lua code. Then f will be available in the global namespace as myfunc .

If you intend to use a stock interpreter, you may want to create a library. This guy wrote an article for Lua Programming Gems that explains how to do this. Sources are available online.

+7
source

You can register functions using luaL_register

See examples and explanations in PiL

+2
source

My answer here contains a beautiful, short example on how to create a very simple game using C and Lua together. In my biased opinion, this is a great starting point.

+1
source

All Articles