Search code examples
clualuaclua-5.3

Lua C function call returns nil


I wrote a simple C plugin for Lua:

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

static int bar (lua_State *L) {
  double arg1 = luaL_checknumber(L, 1);
  double arg2 = luaL_checknumber(L, 2);
  lua_Number res = arg1 + arg2;
  lua_pushnumber(L, res);
  return 1;
}

int luaopen_foo (lua_State *L) {
  static const struct luaL_Reg foo [] = {
    {"bar", bar},
    {NULL, NULL}
  };
  lua_newtable(L);
  luaL_setfuncs(L, foo, 0);
  lua_setglobal(L, "foo");
  return 1;
}

The code is compiled successfully with this GCC command:

gcc -W -Wall -g -fPIC -shared -I/usr/include/lua5.3 -o foobar.so foobar.c

In a Lua 5.3 REPL, I'm able to find and import the module successfully as well, but the returned value of the function call is always nil:

root@b1898c1cc270:/# lua5.3
Lua 5.3.3  Copyright (C) 1994-2016 Lua.org, PUC-Rio
> local foo = require "foo"
> local res = foo.bar(3.0, 6.0)
> res
nil

No errors are thrown and since I'm able to printf the result in the C code before returning the value, I know the code is called and the result calculated successfully.

Any ideas?

Edit1: By not using local variables I get this stack trace instead of a nil value:

root@d7340c919be4:/# lua5.3
Lua 5.3.3  Copyright (C) 1994-2016 Lua.org, PUC-Rio
> foo = require "foo"
> res = foo.bar(3.0, 6.0)
stdin:1: attempt to call a nil value (field 'bar')
stack traceback:
    stdin:1: in main chunk
    [C]: in ?

Solution

  • luaL_setfuncs just registers your functions into a table.

    Instead, use luaL_newlib. It creates a new table and registers your functions there. Then you need to push the table on to lua stack.

    luaL_newlib (L, foo);
    return 1;