简体   繁体   English

与C ++ DLL一起使用Lua

[英]using lua with c++ dll

I started using C++ dll with lua together. 我开始与lua一起使用C ++ dll。 It's very hard to start. 很难开始。 I need help to work with tables. 我需要帮助来处理表格。 I do the following in my C++ code: 我在C ++代码中执行以下操作:

static int forLua_AddTwoNumbers(lua_State *L) {
    double d1 = luaL_checknumber(L, 1);
    double d2 = luaL_checknumber(L, 2);
    lua_pushnumber(L, d1 + d2);
    return(1); 
}

and call this function in lua: 并在lua中调用此函数:

r = runfast.AddTwoNumbers(2, 5)

It works. 有用。 How can I do the same with a table like this: 我如何用这样的表做同样的事情:

lua table t={1=20, 2=30, 3=40}

I'm assuming that you're asking how to add up all the values in an array? 我假设您要问如何将数组中的所有值相加?

static int forLua_SumArray (lua_State* L) {
    // Get the length of the table (same as # operator in Lua)
    int n = luaL_len(L, 1);
    double sum = 0.0;

    // For each index from 1 to n, get the table value as a number and add to sum
    for (int i = 1; i <= n; ++i) {
      lua_rawgeti(L, 1, i);
      sum += lua_tonumber(L, -1);
      lua_pop(L, 1);
    }

    lua_pushnumber(L, sum);
    return 1; 
}

By the way, in Lua, t={1=20, 2=30, 3=40} can be written more simply as t={20, 30, 40} . 顺便说一下,在Lua中, t={1=20, 2=30, 3=40} 20,2 t={1=20, 2=30, 3=40} 30,3 t={1=20, 2=30, 3=40}可以更简单地写为t={20, 30, 40} This is how one typically writes arrays. 这就是通常写数组的方式。

You might also want to take a look at the manual's example code for summing a variable number of arguments . 您可能还想看看手册中用于汇总可变数量的arguments的示例代码 Almost the same as what we're doing here, except you might prefer passing multiple arguments instead of having to use a table. 与您在此处执行的操作几乎相同,除了您可能更喜欢传递多个参数而不是必须使用表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM