Re: Please help me
[
Date Prev][
Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re: Please help me
- From: Bradley Smith <gmane@...>
- Date: 2008年1月01日 22:25:36 -0800
Abhinav Lele wrote:
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; }
/*
* luaL_loadbuffer pushes the compiled script as a
* Lua function on top of the stack. The function
* must be executed to have any effect on the Lua state.
*/
if (lua_pcall(lc, 0, 0, 0) != 0) {
printf("error running script: %s\n",
lua_tostring(lc, -1));
return 1;
}
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