Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dll of Lua Module

Tags:

c

lua

I'm trying to write an external Lua module.

I work on Windows 8.1 and I use gcc as compiler.

My requirement is to build/compile everything all by myself without using pre-compiled files available online.

First of all, I build C source code of Lua 5.2.4 as follow:

  1. gcc -c *.c

  2. ren lua.o lua.obj

  3. ren luac.o luac.obj

  4. ar rcs luaX.X.X.lib *.o

  5. gcc -shared -o luaX.X.X.dll *.o

  6. gcc lua.c luaX.X.X.lib -o luaX.X.X.exe

  7. gcc luac.c luaX.X.X.lib -o luacX.X.X.exe

  8. del *.o *.obj

where X.X.X is the source code revision.

Once I created my .exe, I write the C code of my module (let's call it LuaMath):

#include<windows.h>
#include<math.h>
#include "lauxlib.h"
#include "lua.h"


static int IdentityMatrix(lua_State *L)
{
    int in = lua_gettop(L);
    if (in!=1)
    {
       lua_pushstring(L,"Maximum 1 argument");
       lua_error(L);
    }
    lua_Number n = lua_tonumber(L,1);
    lua_newtable(L);                  /*                 tabOUT n */
    int i,j;
    for (i=1;i<=n;i++)
    {
        lua_newtable(L);              /*         row(i) tabOUT n */
        lua_pushnumber(L,i);          /*       i row(i) tabOUT n */
        for (j=1;j<=n;j++)
        {
            lua_pushnumber(L,j);      /*     j i row(i) tabOUT n */
            if (j==i)
            {
                lua_pushnumber(L,1);
            }
            else                      /* 0/1 j i row(i) tabOUT n */
            {
                lua_pushnumber(L,0);
            }
            /*  Put 0/1 inside row(i) at j position */
            lua_settable(L,-4);       /*       i row(i) tabOUT n */
        }
        lua_insert(L,-2);             /*       row(i) i tabOUT n */

        /* Insert row(i) into position in tabOUT */
        lua_settable(L,2);            /*                tabOUT n */
    }
    return 1;
}


static const struct luaL_Reg LuaMath [] = {{"IdentityMatrix", IdentityMatrix},
                                           {            NULL,           NULL}};

int __declspec(dllexport) luaopen_LuaMath(lua_State *L)
{
    luaL_newlib(L,LuaMath);
    return 1;
}

then I compile it linking to dynamic library.dll as follow:

gcc -shared -L "<path where luaX.X.X.dll is>" -l "luaX.X.X" LuaMath.c

When I call the the module into Lua code as follow:

require("LuaMath")

the output is:

> require("LuaMath")
multiple Lua VMs detected
stack traceback:
        [C]: in ?
        [C]: in function 'require'
        stdin:1: in main chunk
        [C]: in ?
>

What do I do wrong?

Many thanks in advance.

like image 660
Azoun Avatar asked May 15 '17 13:05

Azoun


1 Answers

Do not link the Lua library with your DLL. That's what the error message is telling you.

like image 51
lhf Avatar answered Sep 17 '22 14:09

lhf