Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax Change in lua 5.2 C api

Tags:

c

lua

I was trying to compile the example provided in the book Programming in Lua

But only works for lua 5.1, What are the steps to do it on 5.2?

This is the code I am using

#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;
}

After compiling with gcc test01.c -I/usr/include/lua5.2 -L/usr/lib/x86_64-linux-gnu -llua5.2 I get the following errors:

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

Thank you in advance.

like image 935
rocastocks Avatar asked Aug 11 '14 08:08

rocastocks


People also ask

What is lua_State?

The lua_State is basically a way to access what's going on in the Lua "box" during execution of your program and allows you to glue the two languages together.

What is Lua Userdata?

The lua_newuserdata function allocates a block of memory with the given size, pushes the corresponding userdatum on the stack, and returns the block address.

How do I know what version of Luajit I have?

From the lua docs: -v show version information. there doesn't seem to be just a lua -v in Debian, at least couldn't find it, need to give some liblua5. x -v to get the actual version.

What is a stack in Lua?

The Stack. Lua uses a virtual stack to pass values to and from C. Each element in this stack represents a Lua value ( nil , number, string, etc.). Whenever Lua calls C, the called function gets a new stack, which is independent of previous stacks and of stacks of C functions that are still active.


2 Answers

luaopen() is not used anymore, it's replaced by luaL_newstate, you can use luaL_newstate to create a state with a standard allocation function:

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

This API is changed since Lua 5.1

like image 147
Yu Hao Avatar answered Sep 23 '22 20:09

Yu Hao


Try:

lua_State *L = luaL_newstate();
like image 26
Baj Mile Avatar answered Sep 22 '22 20:09

Baj Mile