lua-users home
lua-l archive

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

Dear All,

I am doing a few experiments with Lua and calling Lua from C Programs. I am registering a C function with LUA, this C functions returns a integer value back to LUA.

What I have observed is that if I don't call openlibs - I don't get the value returned to the LUA function. From the debug logs (lua asserts)  - I can see that an error is printed like this "An attempt to print (nil) value."

Let me know if loading the base / any other library is mandatory to make a C Function call and get the return value back from the C function call to Lua.

Below is my C program and the corresponding LUA script.

Thanks and Regards

C Program

#include <stdio.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

/* gcc -o luaavg luaavg.c -I/usr/local/include -L/usr/local/lib -llua -lm -ldl */

/* the Lua interpreter */
lua_State* L;

static int average(lua_State *L)
        /* get number of arguments */
        int n = lua_gettop(L);
        double sum = 0;
        int i;

        /* loop through each argument */
        for (i = 1; i <= n; i++)
                /* total the arguments */
                sum += lua_tonumber(L, i);

        /* push the average */
        lua_pushnumber(L, sum / n);

        /* push the sum */
        lua_pushnumber(L, sum);

        /* return the number of results */
        return 2;

int main ( int argc, char *argv[] )
        /* initialize Lua */
        L = luaL_newstate();
        /* load Lua base libraries */

        /* register our function */
        lua_register(L, "average", average);

        /* run the script */
        luaL_dofile(L, "avg.lua");

        /* cleanup Lua */

        /* print */
        printf( "Press enter to exit..." );


        return 0;

Lua Program

avg, sum = average(10, 20, 30, 40, 50)
print("The average is ", avg)
print("The sum is ", sum)

avg, sum = average(1, 2, 3, 4, 5)
print("The average is ", avg)
print("The sum is ", sum)