[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Simple Function Call From C language
- From: Sean Conner <sean@...>
- Date: Mon, 23 Jun 2014 23:42:22 -0400
It was thus said that the Great Austin Einter once stated:
> Hi
> Thanks a lot. Referring your links I could do a small test program. However
> I am not able to get the output of lua function in C code. Here is my
> example code. Please let me know, how to collect the lua function output in
> C code. After I call lua_loadstring, I want to print function output in
> Code.., please let me know how to do it...
#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lualib.h>
#include <lualib.h>
const char *c_function = "function fact(n) if n == 0 then return 1 else return n * fact(n-1) end end"
int main(void)
{
lua_State *L;
int r;
L = luaL_newstate();
luaL_openlibs(L); /* open all built-in Lua libraries */
/*------------------------------------------------------------------------
; the following two lines are basically luaL_dostring(). The first line
; compiles the given Lua code into Lua bytecode and returns the result on
; the Lua stack (not to be confused with the C stack---they are
; different). For the example above, the resulting code needs to be
; executed to defien the fact() function. Since luaL_loadstring() returns
; the compiled code on the Lua stack, we can simply call lua_pcall() to
; execute it.
;
; You might think that the function fact() will be defined at this point,
; but no, all that's been done by luaL_loadstring() is to generate the
; code that will define the fact() function.
;------------------------------------------------------------------------*/
luaL_loadstring(L,c_function);
lua_pcall(L,0,0,0);
/*-----------------------------------------------------------------------
; now that we have fact() defined, we can now call it. This just follows
; the example given for the description of lua_call() in the manual.
;----------------------------------------------------------------------*/
lua_getglobal(L,"fact"); /* this is our function, defined globally */
lua_pushinteger(L,4); /* this call fact(4) */
lua_call(L,1,1); /* call fact, with one argument, and expect one result */
r = luaL_checkinteger(L,-1); /* the top of the Lua stack should contain our result */
printf("Factorial: %d",r);
lua_close(L);
return EXIT_SUCCESS;
}
-spc