1
votes

(Lua 5.2)

I am writing bindings from ncurses to Lua and I want to include some values other than functions. I am currently binding functions like this:

#define VERSION "0.1.0"

// Method implementation
static int example(lua_State* L){
    return 0;
}

// Register library using this array
static const luaL_Reg examplelib[] = {
    {"example", example},
    {NULL, NULL}
}

// Piece it all together
LUALIB_API int luaopen_libexample(lua_State* L){
    luaL_newlib(L, examplelib);
    lua_pushstring(L, VERSION);
    // Set global version string
    lua_setglobal(L, "_EXAMPLE_VERSION");
    return 1;
}

This yields a table with a couple functions (in this case, only one) and a global string value, but I want to put a number value in the library. So for example, right now, lib = require("libexample"); will return a table with one function, example, but I want it to also have a number, exampleNumber. How would I accomplish this?

Thank you

1

1 Answers

2
votes

Just push a number in the module table.

#include <lua.h>
#include <lauxlib.h>

static char const VERSION[] = "0.1.0";

// Method implementation
static int example(lua_State* L){
    return 0;
}

// Register library using this array
static const luaL_Reg examplelib[] = {
    {"example", example},
    {NULL, NULL}
};

// Piece it all together
LUAMOD_API int luaopen_libexample(lua_State* L){
    luaL_newlib(L, examplelib);

    // Set a number in the module table
    lua_pushnumber(L, 1729);
    lua_setfield(L, -2, "exampleNumber");

    // Set global version string
    lua_pushstring(L, VERSION);
    lua_setglobal(L, "_EXAMPLE_VERSION");

    return 1;
}

then compile with

gcc -I/usr/include/lua5.2 -shared -fPIC -o libexample.so test.c -llua5.2

and use it like

local ex = require"libexample"
print(ex.exampleNumber)