Problems loading a lua function in c

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Problems loading a lua function in c

Simen Haugen

Hi.

I'm having problems loading lua functions in c. I'm using version 5.1
When running the program below, this line in luaV_gettable will return a blank res.
const TValue *res = luaH_get(h, key); /* do a primitive get */

luaH_get will call luaH_getstr, and the in the line
Node *n = hashstr(t, key);
hashstr function returns a blank node, so the first call to gnext will return 0, and the function will return a nil lua object.

I've tested it on cygwin and windows, and I get the same result (no result :/ ).

Does anyone know whats wrong?

/* test.c */
#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

int main()
{
 int result;
 lua_State *L;

 L = luaL_newstate();
 luaL_openlibs(L);

 result = luaL_loadfile(L, "foobar.lua"); /* result == 0, so this works ok. */

 lua_getfield(L, LUA_GLOBALSINDEX, "itworks"); /* pushes a nil value to the stack instead of my function*/

 if (lua_pcall(L, 0, 0, 0) != 0)
   printf("%s\n", lua_tostring(L, -1)); /* unable to call a nil value */

 lua_close(L);
 return 0;
}

-- foobar.lua
function itworks () print("it finally works") end


-Simen


Reply | Threaded
Open this post in threaded view
|

Re: Problems loading a lua function in c

Luiz Henrique de Figueiredo
This appears to the be #1 FAQ lately: lua_loadfile loads but *does not*
execute a Lua program. Use luaL_dofile instead. Perhaps this needs to be
clear in the manual.

In your case, call lua_pcall before lua_getfield and all will be well.
--lhf
Reply | Threaded
Open this post in threaded view
|

Re: Problems loading a lua function in c

Alex Queiroz
In reply to this post by Simen Haugen
Hallo,

On 3/24/06, Simen Haugen <[hidden email]> wrote:
>
>  Does anyone know whats wrong?
>

     Loading a chunk doesn't automatically execute it. You must use
lua_call() for that.

--
-alex
http://www.ventonegro.org/
Reply | Threaded
Open this post in threaded view
|

Re: Problems loading a lua function in c

Simen Haugen
In reply to this post by Simen Haugen
Thanks a lot. It solved my problems.
The manual is not very clear on that subject (that you have to call lua_pcall after loading a file). I cant find that information in the reference manual.

-Simen

On Fri, 24 Mar 2006 15:47 , Luiz Henrique de Figueiredo <[hidden email]> sent:

This appears to the be #1 FAQ lately: lua_loadfile loads but *does not*
execute a Lua program. Use luaL_dofile instead. Perhaps this needs to be
clear in the manual.

In your case, call lua_pcall before lua_getfield and all will be well.
--lhf