Warning: this is an htmlized version!
The original is here, and the conversion rules are here. |
/* * tlbridge.c - a Tcl/Tk<->Lua bridge. * By Eduardo Ochs <eduardoochs@gmail.com> * Version: 2007mar06 * http://angg.twu.net/LUA/tlbridge.c * http://angg.twu.net/LUA/tlbridge.c.html * (find-es "lua5" "tlbridge.c") * (find-angg "LUA/lua50init.lua" "loadtcl") */ #include <stdio.h> #include <tcl.h> #include <lua.h> #include <lauxlib.h> /* interpreters */ lua_State *TLBridge_L; Tcl_Interp *TLBridge_T; /* Tcl -> Lua, fake preliminary version, used for tests */ int TLBridge_call_lua0(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { int i; for (i=1; i<argc; ++i) printf("arg %d: \"%s\"\n", i, argv[i]); return TCL_OK; } /* Tcl -> Lua * Example of use: * lua print 22 {foo bar} * this calls the global Lua function called "print" * with arguments "22" and "foo bar". * The value returned to Tcl is always the frist value returned by the * Lua function, converted to a string with lua_tostring; so this * returns "nil" (yes, as a string!...). */ int TLBridge_call_lua(ClientData clientData, Tcl_Interp *interp, int argc, const char *argv[]) { lua_State *L = TLBridge_L; int i; // // (find-luamanualw3m "#lua_call") lua_getfield(L, LUA_GLOBALSINDEX, argv[1]); // push first arg as a function for (i=2; i<argc; ++i) // for each one of the other args lua_pushstring(L, argv[i]); // push it as a string lua_call(L, argc - 2, 1); // call - expect one result // // Now return a string result to Tcl... // (find-man "3tcl Tcl_SetResult" "THE TCL_FREEPROC ARGUMENT" "TCL_VOLATILE") Tcl_SetResult(interp, lua_tostring(L, 1), TCL_VOLATILE); // // We're always returning TCL_OK at this moment... // What should we do when the call to Lua triggers an error? // Right now we just expect the user to be super-careful... // (find-man "3tcl Tcl_Eval" "TCL_OK") return TCL_OK; } /* Lua -> Tcl * Example of use: * tcl("expr 22+33") * returns "55". * Note that this function is meant to be called * */ int TLBridge_call_tcl(lua_State *L) { if (!TLBridge_L) TLBridge_L = L; if (!TLBridge_T) { TLBridge_T = Tcl_CreateInterp(); Tcl_CreateCommand(TLBridge_T, "lua0", TLBridge_call_lua0, (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL); Tcl_CreateCommand(TLBridge_T, "lua", TLBridge_call_lua, (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL); } Tcl_Eval(TLBridge_T, luaL_checklstring(L, 1, NULL)); lua_pushstring(L, Tcl_GetStringResult(TLBridge_T)); return 1; } /* initalization. * Usage: * tcl = require "tlbridge" * print(tcl("expr 22+33")) -> "55" */ LUALIB_API int luaopen_tlbridge (lua_State *L) { lua_pushcfunction(L, TLBridge_call_tcl); return 1; }