Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a lua C module for Lua 5.X

Tags:

c

lua

I'm trying to write a Lua module that works with Lua 5.0.x-5.4.x. Since every minor version seems to introduce and poorly documented changes to the C API that break backwards compatibility, I would like to know how I can achieve this with the least amount of conditional compilation based on Lua version.

E.g. here's something that should work for Lua 5.1 but not for later versions:

#define LUA_LIB
#include "lua.h"
#include "lauxlib.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}
};

LUALIB_API int luaopen_foo(lua_State *L)
{
  luaL_register(L, foolib);
  return 1;
}

How can I adapt this to work with Lua5.2 onwards? And maybe even make it robust against future API changes?

like image 386
Peter Avatar asked Jul 25 '26 19:07

Peter


1 Answers

The following piece of code should get you started:

#include <lua.h>
#include <lauxlib.h>
#include "compat-5.3.h"


static int foo(lua_State* L)
{
  lua_Integer a = luaL_checkinteger(L, 1);
  lua_Integer b = luaL_checkinteger(L, 2);
  lua_pushinteger(L, a + b);
  return 1;
}


static luaL_Reg const foolib[] = {
  { "foo", foo },
  { 0, 0 }
};


#ifndef FOO_API
#define FOO_API
#endif

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

It relies on the C-API port of the Compat-5.3 project, and compiles and runs on Lua 5.1 - 5.4. Compat-5.3 provides Lua 5.3 compatibility for Lua 5.1 and 5.2. All you need is the header and C source file. For single source file modules you can just include the header, for multi source file modules you should additionally define a preprocessor symbol and compile/link the compat-5.3.c file separately. See the README.md for details. There are plans to start a Compat-5.4 project (see this issue), but the Lua 5.4 C API is mostly compatible to Lua 5.3 anyway.

For Lua 5.0 support you are on your own, unfortunately.

like image 123
siffiejoe Avatar answered Jul 28 '26 08:07

siffiejoe