重定向/为嵌入式的Lua重新定义的print() [英] Redirecting/redefining print() for embedded Lua

查看:1615
本文介绍了重定向/为嵌入式的Lua重新定义的print()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++应用程序嵌入式的Lua。我想重定向打印语句(或者干脆重新定义打印功能),这样我就可以在其他地方显示前评估pression。

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?

任何片段/指针段,介绍了如何做到这一点会更AP preciated。

Any snippets/pointers to snippets that show how to do this would be much appreciated.

推荐答案

您可以重新定义print语句在C:

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;
}

然后在全局表中注册它:

Then register it in the global table:

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);
  lua_pop(L, 1);
}

由于您使用C ++,你需要使用'的externC包括你的文件

Since you are using C++ you'll need to include your file using 'extern "C"'

这篇关于重定向/为嵌入式的Lua重新定义的print()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆