Forivin
Forivin

Reputation: 15488

LuaPlus create a Lua-table

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.

Upvotes: 2

Views: 455

Answers (2)

111WARLOCK111
111WARLOCK111

Reputation: 867

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

player = {}
toplayer(player)

Upvotes: 1

moteus
moteus

Reputation: 2235

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

Upvotes: 2

Related Questions