C++;和带有参数的Lua集成(…)(Lua 5.1) 我目前正试图把一个函数从C++传递给Lua。问题是这个函数有一个参数(int,int,char*,…)。我对使用Lua也很陌生
所以我从lua堆栈中得到了所有参数,并将相关的(…)参数放入一个向量中。现在怎么办 以下是相关代码:C++;和带有参数的Lua集成(…)(Lua 5.1) 我目前正试图把一个函数从C++传递给Lua。问题是这个函数有一个参数(int,int,char*,…)。我对使用Lua也很陌生,c++,lua,lua-api,C++,Lua,Lua Api,所以我从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
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);
}
这就是我将它传递到Lua州的地方
m_theModel->theInterface.Pushfunction("PrintOnScreen",L_PrintDebug);
我希望能用Lua这样称呼它
PrintOnScreen(10, 100, "Camera 2 Pos: %f %f %f", Camx, Camy, Camz)
或
问题似乎是您需要使用va列表调用函数,但是您正在向量中构造参数,并且没有合理的方法来处理在运行时构造va_列表的问题 我建议让您的print函数接受任意一组参数,并按顺序显示它们(有点像C++的
cout
),然后完全忘记使用va_list
您可以通过迭代参数并根据参数类型将其附加到缓冲区来实现这一点。如果您只处理文本和浮点,这相当简单。例如(注意:我没有测试过这个):
或
对于需要用空格分隔的数字列表来说,这稍微不太方便,但我认为更容易编码
再次注意,上面的示例代码未经测试,可能包含一个接一个的错误或其他bug。尤其应该添加边界检查,并使用snprintf而不是sprintf。或者,使用C++ StrugSuffor进行构建。接近我的答案:)非常感谢!
PrintOnScreen(10, 100, "Camera 2 Pos: %f %f %f", Camx, Camy, Camz)
PrintOnScreen(10,100, "FPS: %f", fps)
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();
PrintOnScreen(10, 100, "Camera 2 Pos: ", Camx, " ", Camy, " ", Camz)
PrintOnScreen(10,100,"FPS: ", fps)