lua-users home
lua-l archive

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

Hi everyone,

I am currently working on an Inline::Lua module for Perl and I need some
help on triggering lua functions from C when those functions make use of
lua's shipped library. I did a rather thorough scan through the mailing
list archive, but apparently this issue hasn't yet been brought up.

Anyway, this is how the Perl/Lua code looks like:

    use Inline 'Lua';

    print bla(1);

    function bla(a) 
        return a*2

Running the above yields:

error: [string "_INLINED_LUA"]:2: attempt to index global `io' (a nil value)

Now for the C-code backing this up: There are essentially two parts
involved. One that is compiling the Lua code:

    compile (lua, code)
            lua_State *lua;
            SV *code;
            STRLEN len;
            char *codestr = SvPV(code, len);
            int status;

            status = lua_dobuffer(lua, codestr, len, "_INLINED_LUA");
            switch(status) {
                case 0:
                case LUA_ERRSYNTAX:
                    croak("Syntax error in function '%s'", name);

and then the function that eventually calls the Lua function:

    call (lua, name, nargs, ...) 
            lua_State *lua;
            char *name;
            int nargs;        /* number of arguments the function expects at least */
            int i, status; 
            int actual_args = 0;

            items -= 3;        /* special var being the number of items on
                                * the Perl stack */
            lua_getglobal(lua, name);

            /* push arguments (also does the necessary conversion 
             * from Perl to Lua types */
            for (i = 0; i < items; i++, nargs--, actual_args++) {
                push_val(lua, ST(i+3));

            /* if less arguments were passed than mentioned in the
             * lua function prototype, pad with 'nil' */
            for (i = nargs; i > 0; nargs--, actual_args++) 
                push_val(lua, &PL_sv_undef);

            status = lua_pcall(lua, actual_args, LUA_MULTRET, 0);
            if (status != 0) 
                croak("error: %s\n", lua_tostring(lua, -1));
            /* test a single return value */
            fprintf(stderr, "result: %s\n", lua_tostring(lua, -1));

The above works as long as I use none of the functions/methods provided
in the lua library so this:

    function bla(a)
        return a*2


Now, how do I go about this? I read in lua-5.0.2's manual (under
"Changes in the Libraries") that library functions are apparently no
longer global. I don't yet understand enough of Lua to know whether this
is what's biting me.

In short: how can my Lua functions use the Lua library when those are
called from C? Quite obviously, there's something rotten in my C code
which I don't yet see.