|
Warning: this is an htmlized version!
The original is here, and the conversion rules are here. |
/*
* demo_luaClua.c: a demo of Lua->C->Lua in swig.
* Swig helps us with the "Lua->C" direction, but sometimes we want to
* make our C functions call functions written in Lua - the "C->Lua"
* part.
* By Edrx, 2006jul18
* Note: this is unfinished, untested, broken.
* Check the e-scripts instead:
* (find-es "swig" "making-L-accessible")
* (find-es "swig" "making-L-accessible-long")
* (find-es "swig" "single-source" "#ifdef SWIG")
*
* The only reason to have this thing in a file by itself is that
* Emacs's c-mode likes reals C files and doesn't like my ".e"s.
*
* (find-swigmanualw3m "SWIG.html")
* (find-swigmanualw3m "Typemaps.html")
* (find-swigmanualw3m "Typemaps.html#Typemaps_nn4")
* (find-swigmanualfile "")
* file:///home/edrx/usrc/swig-1.3.29/Doc/Manual/Typemaps.html
* file:///home/edrx/usrc/swig-1.3.29/Doc/Manual/Typemaps.html#Typemaps_mixed_default
*
* (find-swigfile "")
* (find-swigfile "Lib/lua/")
* (find-swigfile "Lib/lua/lua.swg")
* (find-swigfile "Lib/lua/luarun.swg")
* (find-swigfile "Lib/lua/typemaps.i")
* (find-swigsh "find | grep -i lua")
*/
#ifdef SWIG
%module C
%typemap(in) lua_State *L "$1 = L;"
%inline %{
extern int foo(char *str, int n, lua_State *L);
%}
#else /* Not SWIG */
/*
* (find-node "(cpp)The preprocessing language" "before and after the `#'")
* (find-lua50file "include/")
* (find-lua50file "include/lua.h" "#define LUA_GLOBALSINDEX")
* (find-luamanual-ff "pushing")
* (find-luamanualw3m+ "pushing")
* (find-luamanualw3m+ "debug.debug")
* (find-luamanualw3m+ "lua-to" "lua_tonumber converts the Lua value")
* (find-luamanualw3m+ "3.14" "lua_call")
* (find-fline "/tmp/mla/")
* (find-fline "/tmp/mla/mla_wrap.c" "_wrap_foo")
* (find-fline "/tmp/mla/mla_wrap.c" "_wrap_foo" "arg3 = L;")
* (find-swigfile "")
*/
#include "lua.h"
#include "lauxlib.h"
int foo(char *str, int n, lua_State *L) {
int subfoo_result;
printf("C.foo: depth at the beginning: %d\n", lua_gettop(L));
lua_pushstring(L, "subfoo"); /* function name */
lua_gettable(L, LUA_GLOBALSINDEX); /* function to be called */
lua_pushstring(L, str[0] ? str+1 : "empty"); /* 1st argument */
lua_pushnumber(L, n*10); /* 2nd argument */
lua_call(L, 2, 1); /* call function with 2 arguments and 1 result */
/* now convert the returned value to an int and return it (plus 5) */
subfoo_result = lua_tonumber(L, -1); /* index=-1 means top of stack */
lua_pop(L, 1); /* remove results from stack */
printf("C.foo: depth after lua_pop: %d\n", lua_gettop(L));
return subfoo_result + 5;
}
#endif /* Not SWIG */