lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Laurent FAILLIE <l_faillie@yahoo.com> writes:

> Hello,
> I'm looking for a way to find out a function from it's name.
> I understood from the documentation that function are handled as
> "normal" object, so with my test code, I'm expecting to find it in
> global variable table.So I'm calling lua_getglobal() on the function
> name but it fails and returns a NIL.
>
> I did this little test code .
> --- Test.lua ---function UPSBatCharge( topic, val )
>     print(topic, val);
> end
> ---
> ---- FindFunc.c ---#include <stdio.h>

[...]

> void main( void ){
>     L = lua_open();
>     luaL_openlibs(L);
>     atexit(clean_lua);
>
>     int err;
>     if(( err = luaL_loadfile(L, "Test.lua") )){
>         fprintf(stderr, "*F*  %s\n", lua_tostring(L, -1));
>         exit(EXIT_FAILURE);
>     }
>
>     puts("File loaded");
>
>     findUserFunc("UPSBatCharge");
>     
>     exit(EXIT_SUCCESS);
> }---

luaL_loadfile loads the file and returns the contents (a chunk) as an
executable function on the stack.  It doesn't actually execute the file.
After the loadfile call, you need to execute it before it will create
the UPSBatCharge function in the globals table.  You probably want to
add something like:

  if ((err = lua_pcall(L, 0, 0, 0)) != LUA_OK) {
    ...
  }

afterward.

-- 
Michael Welsh Duggan
(mwd@cert.org)