Lua 5.2 C API中的语法更改

5

我试图编译书籍《Lua程序设计》中提供的示例。

但是该示例仅适用于lua 5.1,在5.2上怎么做呢?

这是我使用的代码:

#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

int main (void) {
  char buff[256];
  int error;
  lua_State *L = lua_open();   /* opens Lua */
  luaL_openlibs(L);  
  while (fgets(buff, sizeof(buff), stdin) != NULL) {
    error = luaL_loadbuffer(L, buff, strlen(buff), "line") ||
      lua_pcall(L, 0, 0, 0);
    if (error) {
      fprintf(stderr, "%s", lua_tostring(L, -1));
      lua_pop(L, 1);  /* pop error message from the stack */
    }
  }
  lua_close(L);
  return 0;
}

使用 gcc test01.c -I/usr/include/lua5.2 -L/usr/lib/x86_64-linux-gnu -llua5.2 编译后,我得到了以下错误:

test01.c: In function ‘main’:
test01.c:10:18: warning: initialization makes pointer from integer without a cas
t [enabled by default]                                                         
   lua_State *L = lua_open();   /* opens Lua */
                  ^
/tmp/ccyPRlV3.o: In function `main':
test01.c:(.text+0x21): undefined reference to `lua_open'
collect2: error: ld returned 1 exit status

谢谢您的提前帮助。

显然,在5.1版本中已经移除了lua_open调用。请参阅5.1参考手册的“与之前版本不兼容”部分 - Some programmer dude
1
在Lua 5.2.2中,它们使用lua_State *L = lua_newstate();。 - Baj Mile
@BajMile luaL_newstate;看到为什么接口需要是不可变的重要性了吗?应该在开箱即用时提供兼容性API。 - Dmytro
2个回答

9

luaopen()已经不再使用,它被luaL_newstate取代,您可以使用luaL_newstate来创建一个带有标准分配函数的状态:

lua_State *L = luaL_newstate();    /* opens Lua */
luaL_openlibs(L);                  /* opens the standard libraries */

此 API 已更改 自 Lua 5.1 起


3

尝试:

lua_State *L = luaL_newstate();

谢谢,我会在升级到5.2.3时尝试它。 - rocastocks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接