2012-09-12 38 views
1

我试图按照this question中所述重新定义打印功能。这里是我的代码:在lua中重新定义打印功能时出现问题

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] 

谁能解释这到底是怎么发生的?我错过了一个图书馆或什么?

UPDATE

有人指出,该结构被称为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] 
+0

前两个错误听起来像是你缺少定义'struct luaL_reg'的头文件。 –

回答

4

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

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

+0

修复了第一个错误。第二个呢? – ewok