简体   繁体   English

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

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

I'm trying to use a function written in C++ from lua. 我正在尝试使用lua用C ++编写的函数。 Given below is the cpp file: 以下是cpp文件:

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;
  }
}

I compiled the above code by g++ using the following command: 我使用以下命令通过g ++编译了以上代码:

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

I'm getting the following error on the lua interpreter: 我在lua解释器上遇到以下错误:

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]: ?

Please note that I can't upgrade the version of Lua due to some reasons. 请注意,由于某些原因,我无法升级Lua的版本。

The second argument to luaL_register is the library name. luaL_register的第二个参数是库名称。 You can leave it as NULL , but if you do, luaL_register will try to insert the registered functions into the table it expects to find on the top of the stack (and in your code there's no table on top of the stack). 您可以将其保留为NULL ,但是如果这样做, luaL_register将尝试将已注册的函数插入希望在堆栈顶部找到的表中(并且在您的代码中,堆栈顶部没有表)。 For the general case of registering a library, it's easiest to pass your library name as the second parameter. 对于注册库的一般情况,最简单的方法是将库名称作为第二个参数传递。

Note that LHF suggests not doing it that way, since it automatically puts the libary's table into the global table, whereas the user of the library might want to have it only as a local variable. 请注意,LHF建议要这样做,因为它会自动将库的表放入全局表中,而库的用户可能只希望将其作为局部变量使用。 The alternative is to create your own table with lua_newtable before calling luaL_register (with a null name). 另一种方法是在调用luaL_register (具有空名称)之前使用lua_newtable创建自己的表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM