在lua中加载C ++模块时出现“尝试为字符串值建立索引"错误 [英] 'Attempt to index a string value' error while loading a c++ module in lua
问题描述
我正在尝试使用lua用C ++编写的函数.下面给出的是cpp文件:
I'm trying to use a function written in C++ from lua. Given below is the cpp file:
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 ++编译了以上代码:
I compiled the above code by g++ using the following command:
g++ -shared -o mylib.so test.cpp -fPIC
我在lua解释器上遇到以下错误:
I'm getting the following error on the lua interpreter:
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的版本.
Please note that I can't upgrade the version of Lua due to some reasons.
推荐答案
luaL_register
的第二个参数是库名.您可以将其保留为 NULL
,但是如果这样做, luaL_register
将尝试将已注册的函数插入希望在堆栈顶部找到的表中(并在您的代码在堆栈顶部没有表).对于注册库的一般情况,最容易将您的库名称作为第二个参数传递.
The second argument to luaL_register
is the library name. 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). For the general case of registering a library, it's easiest to pass your library name as the second parameter.
请注意,LHF建议不这样做,因为它会自动将库的表放入全局表中,而库的用户可能只希望将其作为局部变量使用.另一种方法是在调用 luaL_register
(具有空名称)之前,使用 lua_newtable
创建自己的表.
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. The alternative is to create your own table with lua_newtable
before calling luaL_register
(with a null name).
这篇关于在lua中加载C ++模块时出现“尝试为字符串值建立索引"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!