lua-users home
lua-l archive

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


I am trying to run a function from C code, but I am unable to do so.

Code:
#include <stdio.h>
#include "lua/lua.h"
#include "lua/lualib.h"
#include "lua/lauxlib.h"

int main() {
    lua_State * lc;
    lc = lua_open();
    if(lc == NULL) return 1;
    luaopen_base(lc);
    luaopen_table(lc);            /* opens the table library */
    luaopen_io(lc);               /* opens the I/O library */
    luaopen_string(lc);           /* opens the string lib. */
    luaopen_math(lc);             /* opens the math lib. */
    char *lua_script = "function f(x,y)\n return 145\n end";
    if(luaL_loadbuffer(lc, lua_script, strlen(lua_script), "line") != 0) { printf("ERRLoad\n"); return 3; }
    double x,y,z;

          /* push functions and arguments */
          lua_getglobal(lc, "f");  /* function to be called */
          lua_pushnumber(lc, x);   /* push 1st argument */
          lua_pushnumber(lc, y);   /* push 2nd argument */

          /* do the call (2 arguments, 1 result) */
          if (lua_pcall(lc, 2, 1, 0) != 0)
            printf("error running function `f': %s",
                     lua_tostring(lc, -1));

          /* retrieve result */
          if (!lua_isnumber(lc, -1))
            printf("function `f' must return a number");
          z = lua_tonumber(lc, -1);
      lua_pop(lc, 1);  /* pop returned value */
    lua_close(lc);
    return 0;
}

Error:
error running function `f': attempt to call a nil valuefunction `f' must return a number