1

(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

AlgoRythm
  • 158
  • 10

1 Answers1

2

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)
Henri Menke
  • 10,705
  • 1
  • 24
  • 42
  • Thank you! can you explain why I need -2 in lua_setfield? The Lua manual is a bit confusing for a beginner with the API – AlgoRythm Oct 02 '17 at 01:54
  • 1
    @AlgoRythm The `luaL_newlib` creates a table for the module and pushes it onto the stack. At that point its index is -1. Then you push the number 1729 onto the stack which has then the index -1 and pushes the module table down to -2. The function `lua_setfield` pops the upmost value of the stack (-1) and puts it into the table located at the index specified by the second argument with the name in the third argument. – Henri Menke Oct 02 '17 at 03:44