在Windows上使用gcc 5.3.0编译Lua 5.2.4模块

我需要使用gcc 5.3.0在Windows上编译Lua 5.2.4模块。

在进行这个之前,我按照以下步骤构建了Lua 5.2.4:

gcc -c -DLUA_BUILD_AS_DLL *.c
ren lua.o lua.obj
ren luac.o luac.obj
ar rcs lua524-static.lib  *.o
gcc -shared -o lua524.dll -Wl,--out-implib,lua524.lib *.o
gcc lua.obj lua524.lib -o lua524.exe
gcc luac.obj lua524-static.lib -o luac524.exe
del *.o *.obj

我想要创建的动态库(.dll)是用以下语言编写的(让我们将其称为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,"最多只能输入1个参数");
       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);              /*         行(i) tabOUT n */
        lua_pushnumber(L,i);          /*       i 行(i) tabOUT n */
        for (j=1;j<=n;j++)
        {
            lua_pushnumber(L,j);      /*     j i 行(i) tabOUT n */
            if (j==i)
            {
                lua_pushnumber(L,1);
            }
            else                      /* 0/1 j i 行(i) tabOUT n */
            {
                lua_pushnumber(L,0);
            }
            /*  将0/1放入
                第j个位置的
                行(i)中 */
            lua_settable(L,-4);       /*       i 行(i) tabOUT n */
        }
        lua_insert(L,-2);             /*       行(i) i tabOUT n */

        /* 将行(i)插入
           到tabOUT的位
           置*/
        lua_settable(L,2);            /*                tabOUT n */
    }
    return 1;
}

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

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

此处所述,我按照以下方式构建以上代码:

gcc -O2 -c -DLUA_BUILD_AS_DLL -o LuaMath.o LuaMath.c
gcc -O -shared -o LuaMath.dll LuaMath.o -L. -llua524

当我运行以下Lua代码时:

require("LuaMath")
A=LuaMath.IdentityMatrix(2)

输出错误如下:

stdin:1: attempt to index global 'LuaMath' (a nil value)
stack traceback:
        stdin:1: in main chunk
        [C]: in ?

我做错了什么?

谢谢。

点赞
用户107090
用户107090

你的 C 代码是正确的。通常的 Lua 用法是

LuaMath=require("LuaMath")

如果你想把你的库加载到一个全局变量中。

如果你想要一个局部变量,使用

local LuaMath=require("LuaMath")
2017-05-19 18:56:21