1

I wrote the following C file (for lua 5.1) bar_src.c:

#include <lua5.1/lua.h>
#include <lua5.1/lauxlib.h>
#include <lua5.1/lualib.h>

static int foo(lua_State *L)
{
  int a = luaL_checknumber(L, 1);
  int b = luaL_checknumber(L, 2);

  lua_pushnumber(L, a + b);

  return 1;    
}

luaL_Reg foolib[] = {
  {"foo", foo},
  {NULL, NULL}
};

int luaopen_bar(lua_State *L)
{
  luaL_register(L, "bar", foolib);
  return 1;
}

And compiled it with: gcc -shared -fpic -o bar.so bar.c -llua5.1. However, whenever I try running require("bar") in lua, it instantly does segmentation fault (core dumped).

I wanted to try on another system, so I did the same thing on repl.it (which runs on Ubuntu 18.04) and everything worked perfectly, meaning my Linux configuration has an issue.

Edit: I found the core dump for the segfault in /var/lib/systemd/coredump, and loaded it into GDB with gdb $(which lua) /var/lib/systemd/coredump/core.lua.[file], and gdb said:

Core was generated by `lua'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x00005620820f3ad3 in lua_pushvalue ()
  • 1
    Have you tried inspecting where the error occurred by loading the core dump in gdb? https://stackoverflow.com/questions/8305866/how-do-i-analyze-a-programs-core-dump-file-with-gdb-when-it-has-command-line-pa – Gene Aug 17 '21 at 01:17
  • I managed to find the coredump file (on arch it is located in `/var/lib/systemd/coredump`). it said: `Program terminated with signal SIGSEGV, Segmentation fault. #0 0x00005620820f3ad3 in lua_pushvalue ()` – Ancient Straits Aug 17 '21 at 02:44

1 Answers1

0

The problem was that I was using the lua 5.4 interpreter, I should have run it with the lua5 .1 command.

In this example, I used the older version of Lua, Lua 5.1, but the arch package of Lua has 5.1, 5.2, 5.3, and the latest 5.4 installed. Although there isn't much documentation for 5.4, there is a reference manual. The compiler said that the function luaL_register was not in Lua 5.4, but I found a replacement called luaL_newlib() in the manual.

I changed my code to look like this:

#include <lua5.1/lua.h>
#include <lua5.1/lauxlib.h>
#include <lua5.1/lualib.h>

static int foo(lua_State *L)
{
  int a = luaL_checknumber(L, 1);
  int b = luaL_checknumber(L, 2);

  lua_pushnumber(L, a + b);

  return 1;    
}

luaL_Reg foolib[] = {
  {"foo", foo},
  {NULL, NULL}
};

int luaopen_bar(lua_State *L)
{
  luaL_newlib(L, foolib);
  return 1;
}

This code compiled perfectly amd when I required it, there were no segfaults.