Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
How to redirect the Lua "print" function in C/C++ to your own C/C++ function
#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();
lua_getglobal(L, "_G");
luaL_setfuncs(L, printlib, 0);
Lua_pop(L, 1);
luaL_dostring(L, "print(\"Hello from Lua\")");
return 0;

lua.hpp not found
how can i solve this

If you don't have lua.hpp, remove that line and uncomment the imports right below it. If you are using a c compiler (not c++) then you can also remove the extern c declarations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment