将参数传递给我的Lua DLL函数。

如何将参数传递给 Lua DLL 函数?

我建立了一个简单的 Lua DLL 函数:

static int functionName(lua_State *L, int arg1, char arg2[])
{
printf("running my dll:\n");
printf("passing number: %d   passing string = %s",arg1,arg2);
return 0;
}

并在 lua 中使用它来运行该函数:

require "myTestDll";
myTestDll.functionName(1231544,"Hello World, I'm running my DLL.");

但结果是它打印了错误的数字,甚至与正确的字符串相去甚远。

原文链接 https://stackoverflow.com/questions/9985083

点赞
stackoverflow用户734069
stackoverflow用户734069

注册到 Lua 的函数必须始终具有相同的 C/C++ 签名: int FuncName(lua_State*); 它们所带的参数不能多也不能少。

传递给注册函数的 Lua 参数是 lua_State* 的一部分,它们是放置在 Lua 栈上的首个值。因此您可以调用 lua_gettop 来获取参数的数量。您可以使用通常的 Lua 栈函数从栈中取出参数。

例如,如果您想使您的函数有两个参数,其中第一个是数字而第二个是字符串,可以这样做:

int functionName(lua_State *L)
{
  int arg1 = 0;
  const char *arg2 = NULL;
  size_t arg2Len = 0; //Lua strings have an explicit length; they can contain null characters.

  if(lua_gettop(L) != 2)
  {
    lua_pushstring(L, "Must provide two parameters to this Lua function.");
    lua_error(L);
  }

  arg1 = luaL_checkinteger(L, 1);
  arg2 = luaL_checklstring(L, 2, &arg2Len);

  //Do stuff with arguments.
}
2012-04-02 23:16:56