gpt4 book ai didi

c++ - 在 lua 中重新定义打印函数时遇到问题

转载 作者:行者123 更新时间:2023-11-30 02:03:08 27 4
gpt4 key购买 nike

我正在尝试重新定义打印功能,如 this question 中所述.这是我的代码:

extern "C"{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}

#include <iostream>

using namespace std;

lua_State* L;

static int l_my_print(lua_State* L) {
int nargs = lua_gettop(L);

for (int i=1; i <= nargs; i++) {
if (lua_isstring(L, i)) {
cout << "!!!" << lua_tostring(L, i) << "!!!" << endl;
}
}

return 0;
}

static const struct luaL_Reg printlib [] = {
{"print", l_my_print},
{NULL, NULL} /* end of array */
};

extern int luaopen_luamylib(lua_State *L)
{
lua_getglobal(L, "_G");
luaL_register(L, NULL, printlib);
lua_pop(L, 1);
}


int main(){
L = luaL_newstate();
luaL_openlibs(L);
luaopen_luamylib(L);

luaL_dostring(L, "print(\"hello\")");

lua_close(L);

return 0;
}

当我尝试编译代码时,我得到:

$ g++ -I/usr/include/lua5.2 -o embed test.cpp -Wall -Wextra -llua5.2
test.cpp:28:1: error: elements of array ‘const luaL_reg printlib []’ have incomplete type
test.cpp:28:1: error: storage size of ‘printlib’ isn’t known
test.cpp: In function ‘int luaopen_luamylib(lua_State*)’:
test.cpp:33:34: error: ‘luaL_register’ was not declared in this scope
test.cpp:35:1: warning: no return statement in function returning non-void [-Wreturn-type]

谁能解释这里发生了什么?我是不是错过了图书馆之类的东西?

更新

有人指出该结构称为luaL_Reg,而不是luaL_reg。这解决了我的第一个问题:

$ g++ -I/usr/include/lua5.2 -o embed test.cpp -Wall -Wextra -llua5.2
test.cpp: In function ‘int luaopen_luamylib(lua_State*)’:
test.cpp:33:34: error: ‘luaL_register’ was not declared in this scope
test.cpp:35:1: warning: no return statement in function returning non-void [-Wreturn-type]

最佳答案

第一个错误:是luaL_Reg,不是luaL_reg

第二个错误:luaL_register 已弃用(在 Lua 5.2 中),并且仅在包含 Lua header 之前定义了 LUA_COMPAT_MODULE 时才可用。您应该改用 luaL_setfuncs。

关于c++ - 在 lua 中重新定义打印函数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12390684/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com