public
Last active

How to redirect the Lua "print" function in C/C++ to your own C/C++ function

  • Download Gist
redirectPrint.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include <iostream>
 
#include "lua.hpp"
//extern "C" {
//#include "lua.h"
//#include "lualib.h"
//#include "lauxlib.h"
//}
 
static int l_my_print(lua_State* L) {
int nargs = lua_gettop(L);
std::cout << "in my_print:";
for (int i=1; i <= nargs; ++i) {
std::cout << lua_tostring(L, i);
}
std::cout << std::endl;
 
return 0;
}
 
static const struct luaL_Reg printlib [] = {
{"print", l_my_print},
{NULL, NULL} /* end of array */
};
 
int main(void) {
lua_State* L = luaL_newstate();
luaL_openlibs(L);
lua_getglobal(L, "_G");
luaL_setfuncs(L, printlib, 0);
Lua_pop(L, 1);
luaL_dostring(L, "print(\"Hello from Lua\")");
lua_close(L);
return 0;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.