[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Calling Lua from C - have I been doing it wrongly?
- From: roberto@... (Roberto Ierusalimschy)
- Date: Mon, 16 Oct 2006 11:37:53 -0200
> There is an example in the PIL book (Listing 24.1) along these lines
> (I have slightly simplified it):
>
> ---------------
> #include "lua.h"
> #include "lauxlib.h"
>
> char buff [] = "print 'hi'";
>
> int main (void)
> {
> lua_State * L = luaL_newstate ();
> luaL_openlibs (L);
> int error = luaL_loadbuffer(L, buff, strlen(buff), "line") ||
> lua_pcall(L, 0, 0, 0);
> return 0;
> } // end of main
> ---------------
>
> Isn't there a problem here? What if luaL_loadbuffer fails? For
> example, out of memory?
Unlike most other functions in the API, luaL_loadbuffer and lua_pcall
never raise an error. Even in the case of out-of-memory, they return
proper error codes.
(On the other hand, the previous call, to luaL_openlibs, may fail in
the system does not have enough memory. And luaL_newstate may return
NULL for the same reason. But these only happen if your program already
starts with less than ~20K of free memory.)
For a bullet-proof program, you should use lua_cpcall (as David Burgess
suggested). It also avoids the problem of an out-of-memory error when
calling lua_pushcfunction.
-- Roberto