在lua中加载C模块时出现”尝试为字符串值建立索引”错误

'Attempt to index a string value' error while loading a c++ module in lua

我正在尝试使用lua中用C编写的函数。下面给出的是cpp文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
extern"C"
{
#include"lua.h"
#include"lauxlib.h"
#include"lualib.h"
}

static int  add_5(lua_State *L)
{
  double d = lua_tonumber(L, 1); /* get argument */
  d=d+5;
  lua_pushnumber(L, d); /* push result */
  return 1; /* number of results */
}

static const struct luaL_Reg mylib [] =
{
  {"add_5", add_5},
  {NULL, NULL} /* sentinel */
};

extern"C"
{
  int luaopen_mylib (lua_State *L)
  {
    //luaL_newlib(L, mylib);
    luaL_register(L, NULL, mylib);
    return 1;
  }
}

我使用以下命令通过g编译了以上代码:

1
g++ -shared -o mylib.so test.cpp -fPIC

我在lua解释器上遇到以下错误:

1
2
3
4
5
6
7
8
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> local temp = require"mylib"
attempt to index a string value
stack traceback:
        [C]: ?
        [C]: in function 'require'
        stdin:1: in main chunk
        [C]: ?

请注意,由于某些原因,我无法升级Lua的版本。


luaL_register的第二个参数是库名称。您可以将其保留为NULL,但是如果这样做,luaL_register将尝试将注册的函数插入希望在堆栈顶部找到的表中(并且在您的代码中,堆栈顶部没有表) )。对于注册库的一般情况,最简单的方法是将您的库名作为第二个参数传递。

请注意,LHF建议不要这样做,因为它会自动将库的表放入全局表中,而库的用户可能只希望将其作为局部变量使用。另一种方法是在调用luaL_register(具有空名称)之前使用lua_newtable创建自己的表。