Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua 5.2: Bindings andNative Extensions: lua_register() causes segfaults due to lack of LUA_GLOBALSINDEX

Tags:

c

lua

Lua tutorials all over the net show the use of lua_register() to expose the functions implemented in your extension DLL or so:

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

static int pushlua3(lua_State *L)
{
  lua_pushnumber(L, 3);
  return 1;
}

int luaopen_lua3pushbinder(lua_State *L) 
{
  lua_register(L,"pushlua3", pushlua3);
  return 0;
}

lua_register() is a macro and not a function, this is from the 5.2 manual:

http://www.lua.org/manual/5.2/manual.html#lua_register

[-0, +0, e]

void lua_register (lua_State *L,
               const char *name,
               lua_CFunction f);

Sets the C function f as the new value of global name. It is defined as a macro:

 #define lua_register(L,n,f) \
        (lua_pushcfunction(L, f), lua_setglobal(L, n))

if you use the functions separately, lua_pushcfunction is fine, but lua_setglobal crashes because it's trying to reference LUA_GLOBALSINDEX and that fails at runtime, not compile time.

So what is the right way to implement lua_register() now?

I would sort of have expected that when Lua moved to 5.2 and redid the concepts manifested with LUA_GLOBALSINDEX and thus lua_register() it would have been reasonable to change lua_register() so that it did it the 'new' way.

So, is there a header update that Ubuntu didn't pick up for lua5.2? should i have an include path that points to /usr/include/lua5.2 and then I wouldn't face this problem? I only have a Lua 5.1 include directory on my box.

tnx for any help you can provide.

like image 818
JohnU Avatar asked Nov 11 '22 21:11

JohnU


1 Answers

The answer is that on Ubuntu 13.04 the Ubuntu Software Center informed me of the existence of lua5.2 but did not inform me of the existence of liblua5.2-0-dev.

I used apt-get to find it based on the suggestion for lhf that I needed the 5.2 headers.

My lua script calling a native dll/so demo went off just fine as a result

like image 198
JohnU Avatar answered Nov 14 '22 23:11

JohnU