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

标签 c++ lua

我正在尝试使用 lua 中用 C++ 编写的函数。下面给出的是 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;
  }
}

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

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

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

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

最佳答案

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

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

关于c++ - 在 lua 中加载 C++ 模块时出现“尝试索引字符串值”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57290650/

相关文章:

c++ - std::condition_variable::wait with predicate

c++ - 如何在 SIGSEGV 之后销毁在 main() 中创建的对象

c++ - 奇怪的 C++ std::string 行为......我该如何解决这个问题?

c++ - 尝试从 C 加载 penlight lua 模块

lua - 如何使用Nodemcu(Lua)进行多个串口通信

lua - 垃圾收集和字符串到字符串函数的内存

c++ - 我在 BST 中的删除功能甚至不起作用

c++ - 寻找更好的C++类工厂

linux - Windows 上的 LUAROCKS 奇怪地安装 rocks

从 Lua 调用 C 函数