C ++和Lua与参数的集成(...)(Lua 5.1)

用户名

我目前正在尝试将函数从C ++传递给Lua。问题在于此函数的参数为​​(int,int,char *,...)。我也很新使用Lua。

因此,我从lua堆栈中获得了所有参数,并将相关的(...)放入向量中。现在怎么办?

这是有问题的代码:

static int L_PrintDebug(lua_State *state)
{
MVC_View * theView = MVC_View::GetInstance(MVC_Model::GetInstace());

int n = lua_gettop(state);

// check if number of arguments is less than 3
// then we stop as not enough parameters
if(n < 3)
{
    std::cout << "Error: printDebug(number,number, char *, ... )" << std::endl;
    lua_error(state);
}

// gets parameter
int x = lua_tointeger(state, 1);
int y = lua_tointeger(state, 2);
char * words = (char*) lua_tostring(state, 3);

//Get the rest of the arguments.
std::vector<float> Numbers;
for(int i = 4;i != n; i++)
{
    if(lua_type(state,i) == LUA_TNUMBER)
    {
        float theNumber = lua_tonumber(state,i);
        Numbers.push_back(theNumber);
    }
}

// call C++ function
//This is where I'm stuck.
theView->Printw(x,y,words);
}

这是PrintW函数:

void MVC_View::Printw (float x, float y, const char* format, ...) 
{ 
glRasterPos2f(x,y);
char text[256];
va_list ap;
if(format==NULL)
    return;
va_start(ap,format);
    vsprintf_s(text,format,ap);
va_end(ap);

glPushAttrib(GL_LIST_BIT);
    glListBase(m_base-32);
    glCallLists(strlen(text),GL_UNSIGNED_BYTE,text);
glPopAttrib();

 } 

这是我将其传递到Lua状态的地方。

m_theModel->theInterface.Pushfunction("PrintOnScreen",L_PrintDebug);

我希望能够在Lua中这样称呼它,

PrintOnScreen(10, 100, "Camera 2 Pos: %f %f %f", Camx, Camy, Camz)

要么

PrintOnScreen(10,100, "FPS: %f", fps)
约翰·奥姆

问题似乎是您需要使用va列表调用函数,但是您正在向量中构造参数,并且没有合理的方法在运行时处理va_list。

我建议使您的print函数采用任意一组参数,并按顺序显示它们(有点像C ++的链cout),而完全不用使用va_list

您可以通过遍历参数并根据参数的类型将其追加到缓冲区中来实现此目的。如果您只处理文本和浮点,则这很简单。例如(注意:我尚未对此进行测试):

char text[256]; /* Be careful! Buffer overflow potential for not checking lengths of sprintf and not using snprintf */
char *buf = &text[0]; /* start buf at beginning of text */
int x = lua_tointeger(state, 1);
int y = lua_tointeger(state, 2);
for (int i = 3, i < n; i++) {
    if (lua_type(state,i) == LUA_TNUMBER) {
         sprintf(buf, "%f", lua_tonumber(state,i));
    } else if (lua_type(state,i) == LUA_TSTRING) {
         sprintf(buf, "%s", lua_tostring(state,i));
    } else {
         // ERROR SOMEHOW
    }
    buf += strlen(buf); /* Move the end of buf for more appending
}
/* At this point, we've filled in text by walking through it with our buf pointer, and we have a complete string */
glPushAttrib(GL_LIST_BIT);
glListBase(m_base-32);
glCallLists(strlen(text),GL_UNSIGNED_BYTE,text);
glPopAttrib();

然后,您可以像这样调用Lua:

PrintOnScreen(10, 100, "Camera 2 Pos: ", Camx, " ", Camy, " ", Camz)

要么

PrintOnScreen(10,100,"FPS: ", fps)

对于需要用空格分隔的数字列表,这不太方便,但我认为更容易编写代码。

再次注意,上面的示例代码未经测试,并且可能包含一次性错误或其他错误。特别是,您应该添加边界检查并使用snprintf而不是sprintf。或者,使用c ++字符串流进行构造。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章