1

I'm trying to figure out how to get the returned table from the Lua function in C++.

My code:

if (lua_pcall(L, 0, 1, 0)) {
        std::cout << "ERROR : " << lua_tostring(L, -1) << std::endl;
}
vector<float> vec;

if (lua_istable(L, -1) { 

    //how to copy table to vec?
}

How can I copy the returned table to vector if the table size is unknown? Thanks!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Zack Lee
  • 2,784
  • 6
  • 35
  • 77
  • 1
    If the question is just about getting the size of the table, see [this post](https://stackoverflow.com/questions/26643285/get-lua-table-size-in-c). Or are you asking for generating a std::vector from the table ? – Vincent Saulue-Laborde Jun 27 '18 at 13:49
  • 1
    here's another answer that might help: http://stackoverflow.com/a/6142700/847349 – Dmitry Ledentsov Jun 27 '18 at 15:37
  • @DmitryLedentsov Do you mind posting an actual example of copying returned table to float vector using `lua_next`? I'd appreciate it. – Zack Lee Jun 28 '18 at 01:57
  • you can simply use [luastackcrawler](https://github.com/d-led/luastackcrawler) or any other comparable library. Here's a [generic table crawler](https://github.com/d-led/luastackcrawler/blob/f775ba95878b0ba8b27135ee651028357404ea78/luatablestack/luatablecrawler.cpp), which you could try to understand to write your special simple use case. I won't be able to write an example now – Dmitry Ledentsov Jun 28 '18 at 13:38
  • have you tried to understand the Lua book [PiL](https://www.lua.org/pil/25.html)? – Dmitry Ledentsov Jun 28 '18 at 13:40

1 Answers1

0

I think I found out how to do it using lua_next.

lua_getglobal(L, name);

if (lua_pcall(L, 0, 1, 0)) {
        std::cout << "ERROR : " << lua_tostring(L, -1) << std::endl;
}
vector<float> vec;

if (lua_istable(L, -1) { 

   lua_pushvalue(L, -1);
   lua_pushnil(L);

   while (lua_next(L, -2))
   {

        if (lua_isnumber(L, -1))
        {
            vec.push_back(lua_tonumber(L, -1));
        }
        lua_pop(L, 1);
    }
    lua_pop(L, 1);
}
Zack Lee
  • 2,784
  • 6
  • 35
  • 77