Redirecting/redefining print() for embedded Lua(为嵌入式 Lua 重定向/重新定义 print())
问题描述
我在我的 C++ 应用程序中嵌入了 Lua.我想重定向打印语句(或者可能只是重新定义打印函数?),以便我可以在其他地方显示计算的表达式.
I have embedded Lua in my C++ application. I want to redirect print statements (or maybe simply redefine the print function?), so that I can display the evaluated expression somewhere else.
执行此操作的最佳方法是什么:重定向或重新定义 print() 函数?
What is the best way to do this: redirect or redefining the print() function?
任何显示如何执行此操作的代码段/指向代码段的指针都将不胜感激.
Any snippets/pointers to snippets that show how to do this would be much appreciated.
推荐答案
你可以在C中重新定义print语句:
You can redefine the print statement in C:
static int l_my_print(lua_State* L) {
int nargs = lua_gettop(L);
for (int i=1; i <= nargs; i++) {
if (lua_isstring(L, i)) {
/* Pop the next arg using lua_tostring(L, i) and do your print */
}
else {
/* Do something with non-strings if you like */
}
}
return 0;
}
然后在全局表中注册:
static const struct luaL_Reg printlib [] = {
{"print", l_my_print},
{NULL, NULL} /* end of array */
};
extern int luaopen_luamylib(lua_State *L)
{
lua_getglobal(L, "_G");
// luaL_register(L, NULL, printlib); // for Lua versions < 5.2
luaL_setfuncs(L, printlib, 0); // for Lua versions 5.2 or greater
lua_pop(L, 1);
}
由于您使用的是 C++,因此您需要使用extern "C"" 来包含您的文件
Since you are using C++ you'll need to include your file using 'extern "C"'
这篇关于为嵌入式 Lua 重定向/重新定义 print()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为嵌入式 Lua 重定向/重新定义 print()


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07