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.

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

I'm using LuaPlus, so this gives me error messages. It's probably on this page: 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.. :/
1

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

player = {}
toplayer(player)

4 Comments

What? oO I don't get it.
@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"})
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.