epics-modules / lua

Lua Scripting Record for EPICS
https://epics-modules.github.io/lua/
7 stars 4 forks source link

Added static library registration function #7

Closed keenanlang closed 6 years ago

keenanlang commented 6 years ago

This updates the luaEpics files to allow users to register a lua module within code that will be statically linked into the final application.

The function luaRegisterLibrary takes in a name for the library and a function with the signature:
int (*lua_CFunction) (lua_State *L);

When the lua shell is run, all functions currently registered are run. If those functions push a value onto the stack, the top value is given the name of the library. So, using lua's newlib function, you can bind functions like so:

static int l_bar( lua_State *L )
{
    lua_pushstring(L, "Hello, World");
    return 1;
}

int luaopen_foo( lua_State *L )
{
    static const luaL_Reg foo[] = {
        { "bar", l_bar },
        { NULL, NULL }
    };

    luaL_newlib( L, foo );
    return 1;
}

Then, if you later run the luaRegisterLibrary function:

luaRegisterLibrary("foo", luaopen_foo);

you'll be able to run foo.bar() within the lua shell and it will return the value "Hello, World".

Recommended use of the luaRegisterLibrary function is to add it into a dbd registrar function like so:

foo.cpp

static void testRegister(void)
{
    luaRegisterLibrary("test", luaopen_test);
}

epicsExportRegistrar(testRegister);

foo.dbd

registrar(testRegister)

Then, the libraries will automatically register when you load the IOC's dbd file.