2

How can I create a Lua-object like this:

players = {
    {
        pos = {x=12.43,y=6.91},
        backpack = {22,54},
        health = 99.71
        name = "player1"
    },
    {
        pos = {x=22.45,y=7.02},
        backpack = {12,31},
        health = 19.00
        name = "player2"
    }
}

in my C++ sourcecode with values that are taken from variables of my c++ code?
In the end it needs to be available to all scripts of course.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Forivin
  • 14,780
  • 27
  • 106
  • 199

2 Answers2

2

This is not tested code but I think you can understand the main idea.

int i = 0;
lua_newtable(L);
  lua_newtable(L);
    lua_newtable(L);
      lua_pushnumber(L, 12.43); lua_setfield(L, -2, "x");
      lua_pushnumber(L, 6.91 ); lua_setfield(L, -2, "y");
    lua_setfield(L, -2, "pos");
    lua_newtable(L);
      lua_pushnumber(L, 22); lua_rawseti(L, -2, 1);
      lua_pushnumber(L, 54); lua_rawseti(L, -2, 2);
    lua_setfield(L, -2, "backpack");
    lua_pushnumber(L, 99.71); lua_setfield(L, -2, "health");
    lua_pushstring(L, "player1"); lua_setfield(L, -2, "name");
  lua_rawset(L, -2, i++);
  // same next player
greatwolf
  • 20,287
  • 13
  • 71
  • 105
moteus
  • 2,187
  • 1
  • 13
  • 16
  • I'm using LuaPlus, so this gives me error messages. It's probably on this page: http://wwhiz.com/LuaPlus/LuaPlus.html I think SetObject() is the function I need. But I have no idea how I'd have to use it to accomplish what I mentioned above.. :/ – Forivin Oct 28 '13 at 16:46
1

You can register a function to create players objects from a lua table.

player = {}
toplayer(player)
111WARLOCK111
  • 857
  • 2
  • 7
  • 14
  • What? oO I don't get it. – Forivin Oct 28 '13 at 16:53
  • @Forivin Register a C++ function that returns array of player objects and name it toplayer(), create players by getting the name, pos and other stuffs from the table, and return them. local players = toplayer({name = "AA"}) – 111WARLOCK111 Oct 28 '13 at 16:58
  • That sounds great, but there is one big problem: C++ doesn't support this kind of array (key-value). As far as I know at least. So how would I create and return it? – Forivin Oct 28 '13 at 18:16
  • @Forivin It does: http://stackoverflow.com/questions/2493431/c-array-of-objects-without-vector – 111WARLOCK111 Oct 28 '13 at 19:53