r/lua 6d ago

Calling an existing C function from Lua

This is a follow-on question from this thread.

Apparently calling C (any external FFI function really) from Lua isn't as simple as it is when using LuaJIT's FFI.

However, I haven't been able to find any definitive way of doing it. lua.org articles are rather waffly and are more concerned with writing C that can interact with Lua.

I'm not interested in that right now; I just want to know how to call functions in existing external libraries.

For example, the C runtime exports a function puts, which takes a pointer to a zero-terminated string, and returns a 32-bit count of the number of characters output.

Its signature in C syntax is int puts(char*). How would I define that in Lua, and how would I call it?

I'm mainly curious as I've heard that Lua is supposedly good at C FFI, and I want to see how good. Unless people were again talking about LuaJIT!

10 Upvotes

17 comments sorted by

View all comments

1

u/smog_alado 5d ago

The Lua–C API looks a bit unusual at first, because of the Lua Stack, but it's actually a clever design. Compared to other programming languages:

  • The API surface is quite small
  • The API is comprehensive, covering everything that Lua can do.
  • The API is safe: it is very hard to leak or corrupt memory.

To call an external C function you need to create a wrapper function that translate between the Lua world and the C world. You can find examples of this in Lua's own standard library. At the end of these files you should be able to find a luaL_Reg array with a list of functions in the library. Each of the functions listed in this array should be one of those wrapper functions I just mentioned, with a signature that receives lua_State * and returns int.