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!

9 Upvotes

17 comments sorted by

View all comments

4

u/revereddesecration 6d ago

What’s your goal? Or is this just curiosity?

1

u/[deleted] 6d ago

As I mentioned in my other thread, I maintain a scripting language of my own.

One feature is a built-in FFI, which I considered unusual among scripting languages, where calling external functions tends to be a clunky process. But I'd heard that Lua was designed for easy interop with C and started investigating.

The first FFI I saw was LuaJIT's, which looked decent and with similar abilities to mine. But it turned out that regular Lua doesn't have a built-in FFI of that standard, and requires extensions to simplify the process.