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.
#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 */
luaL_openlibs(L);
/* register our function */
lua_register(L, "average", average);
/* run the script */
luaL_dofile(L, "avg.lua");
/* cleanup Lua */
lua_close(L);
/* print */
printf( "Press enter to exit..." );
getchar();
return 0;
}