【发布时间】:2017-03-15 04:15:36
【问题描述】:
我面临的这个问题涉及两个部分:
-
将任意结构从 C 传递到 Lua 函数。例如,考虑以下 2 个结构:
struct Person{ int age; char *name; }; struct Paper{ int width; int height; char *color; };我希望能够通过一个简单的 C 函数将它们传递给 Lua,例如:
template<class T> void call(T t){ ... (pseudo-code) check t: if Person, lua_getglobal(L, "sendPerson") if Paper, lua_getglobal(L, "sendPaper") for each element in t, check its type if integer, lua_pushinteger(...) if char*, lua_pushstring(...) ... lua_pcall(...) } Person p = {33, "David"}; Paper A4 = {210, 297, "white"}; call(p); call(A4);2) 访问它。在 Lua 端,如何通过名称访问这些变量?
function sendPerson(p) print(p.age) print(p.name) end function sendPaper(p) print(p.width) print(p.height) print(p.color) end我知道我可以使用
setfield,但除非我可以在调用 Lua 函数的通用方法中调用它,否则我看不出它是怎么可能的。
更新:这是代码。例如,这里是 WM_LBUTTONDOWN 事件。这样,我需要有 2 个方法和 1 个结构来处理我发送给 lua 的消息:第一个创建线程的方法,第二个调用 lua 函数的方法,以及结构,以便我可以将它作为参数传递给线程功能。
struct LButtonEvent{
int x, y, k;
};
LuaScript *L = new LuaScript(FILENAME);
void _onLButtonDown(LPVOID arg)
{
LButtonEvent *b = (LButtonEvent*) arg;
lua_State *l = L->getState();
lua_getglobal(l, "onLButtonDown");
lua_newtable(l);
lua_pushinteger(l, b->x); lua_setfield(l, -2, "x");
lua_pushinteger(l, b->y); lua_setfield(l, -2, "y");
lua_pushinteger(l, b->k); lua_setfield(l, -2, "k");
lua_pcall(l, 1, 0, 0);
}
void LuaScript::onLButtonDown(LButtonEvent b)
{
// I want my window to continue proccessing messages. If lua script calls "sleep", the window freezes.
CreateThread(0, 0, (LPTHREAD_START_ROUTINE) _onLButtonDown, (LPVOID) &b, 0, 0);
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_LBUTTONDOWN:
LButtonEvent b;
b.x = (int)(short)LOWORD(lParam);
b.y = (int)(short)HIWORD(lParam);
b.k = wParam;
L->onLButtonDown(b);
break;
....
}
return 0;
}
【问题讨论】:
-
关于更新:你是对的,你必须定义很多东西。我真的无法进一步回答这个问题,因为我真的不知道窗口和回调机制。但是,在您的第一个示例中,您以伪代码显示您正在将一些相关数据传递给 lua。为什么不准确传递您需要的值?这样,您可以以正确的方式(使用相应的参数)定义 lua 函数,而不必通过表访问值。但是,我仍然觉得这可以更轻松地完成。但这在很大程度上取决于你的结构,我不知道。
-
我感觉你可以在你的 c++ 代码中使用某种继承,并为每个类调用一个适当的重载函数。
标签: c variables struct lua arguments