【发布时间】:2017-05-19 18:32:13
【问题描述】:
我需要用 gcc 5.3.0 编译一个 Lua 5.2.4 模块。在 Windows 上。
在此之前,我按以下步骤构建 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,"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}};
LUA_API int luaopen_LuaMath(lua_State *L)
{
luaL_newlib(L,LuaMath);
return 1;
}
如here 所述,我将上述代码构建如下:
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 ?
我做错了什么?
提前致谢
【问题讨论】:
-
在
luaopen_LuaMath中你应该添加一行代码来将创建的库表保存在全局环境中(当然,它的名称“LuaMath”必须作为字符串提供)。