Question

I want to add a requireable module solely from the C API.

--lua.lua
local c_module = require("c_module")
c_module.doWork()

What API functions do I have to use to make this possible?

Was it helpful?

Solution

When loading a shared library with require, Lua looks for a a function named luaopen_<name> where <name> is the module name with the dots replaced with underscores (so require "foo.bar" will look for luaopen_foo_bar, but hyphens get special treatment; see the Lua manual).

This function should be a regular lua_CFunction; that is, it takes a lua_State* as an argument and returns an int. require calls this function with the package name as an argument, and the value you return from the function is what require stores and returns.

Here's an example for a module named foo:

static int bar(lua_State* L) {
    // ...
}

int luaopen_foo(lua_State* L) {
    lua_newtable(L); // Create package table

    // Push and assign each function
    lua_pushcfunction(L, &bar);
    lua_setfield(L, -2, "bar");

    // ...

    // Return package table
    return 1;
}

(This is for Lua 5.1, though the equivalent code for 5.2 should be very similar, if not the same. Also be sure that the luaopen_ function is exported from the shared library.)

The full behavior of the C loader can be found here: http://www.lua.org/manual/5.1/manual.html#pdf-package.loaders

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top