Lua Academy · Lesson

Calling C Functions via FFI

Invoke libc and custom shared library functions from Lua with zero overhead.

Lesson 2 of 413 steps

Calling C Functions via FFI is a free Lua Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.

Direct C Function Calls

Once declared with ffi.cdef, C functions are called exactly like Lua functions through the library object. Arguments and return values are automatically converted.

local ffi = require("ffi")
ffi.cdef[[ double sin(double x); ]]
local m = ffi.load("m")
print(m.sin(math.pi / 2))  -- 1.0

Type Conversion

Lua numbers become C doubles by default. The FFI converts to the declared C parameter type automatically. Booleans become 0/1. Strings become const char*.

Calling printf

printf is a variadic C function. Call it via ffi.C.printf with format strings and arguments.

ffi.cdef[[ int printf(const char *fmt, ...); ]]
ffi.C.printf("Sum: %d\n", 42)

Return Value Handling

C return values are automatically converted to Lua types. Integers become Lua numbers, char* become lightuserdata (use ffi.string to convert).

ffi.cdef[[ char *getenv(const char *name); ]]
local ptr = ffi.C.getenv("HOME")
if ptr ~= nil then
  print(ffi.string(ptr))
end

ffi.string

ffi.string(ptr, len) converts a char* pointer to a Lua string. Without len, it reads until a null byte.

Error Handling

C functions return error codes or set errno. Check return values explicitly. Access errno via ffi.errno().

ffi.cdef[[ int open(const char *path, int flags); ]]
local fd = ffi.C.open("missing.txt", 0)
if fd < 0 then
  print("Error:", ffi.errno())
end

Struct Arguments

Pass C structs by value or pointer. Create them with ffi.new.

ffi.cdef[[
  typedef struct { int x, y; } Point;
  void printPoint(Point p);
]]
local p = ffi.new("Point", {x=3, y=4})
lib.printPoint(p)

Pointer Arguments

Pass output pointers for functions that return multiple values through pointer parameters.

ffi.cdef[[
  void minmax(double *arr, int n, double *min, double *max);
]]
local arr = ffi.new("double[5]", {5,2,8,1,9})
local mn, mx = ffi.new("double[1]"), ffi.new("double[1]")
lib.minmax(arr, 5, mn, mx)
print(mn[0], mx[0])

FFI Call Performance

FFI calls to C functions have near-zero overhead — much faster than Lua-to-C calls via the traditional C API. The JIT can often inline the call entirely.

Variadic Functions

Variadic C functions (...) must be called with correct types. Pass explicit type casts if needed to avoid ambiguity.

ffi.C.printf("%d %f\n", ffi.cast("int", 42), ffi.cast("double", 3.14))

Safety Practices

Always check pointer return values for NULL. Never pass a freed or out-of-scope pointer. Use ffi.gc to attach finalizers to C allocations.

FFI Call Question

How does the FFI handle converting a Lua string to a C const char*?

Recap: Calling C via FFI

Call C functions through the library object just like Lua functions. The FFI handles type conversion. Use ffi.string for char* returns, ffi.errno() for errors, and ffi.new for struct/array arguments.

Free to start

Learn Lua with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
40
Lessons
159

Frequently Asked Questions

Is the “Calling C Functions via FFI” lesson free?

Yes — any 3 lessons of the Lua Academy learning path, including “Calling C Functions via FFI”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.

What will I learn in “Calling C Functions via FFI”?

Invoke libc and custom shared library functions from Lua with zero overhead. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Calling C Functions via FFI” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. FFI Basics: ffi.cdef and ffi.load
  2. Calling C Functions via FFI
  3. Pointers, Structs, and Arrays in FFI
  4. Callbacks: Passing Lua Functions to C
← Back to Lua Academy