Accessing sub-tables in a moon table

2

How do I read a subtable within a table? I tried to return the value with the following function but went wrong.

name = {"Lowes", "Renata", "Titia", "Maria"}

health = {}

posx = {}

posy = {}

posz = {}

players = {name, health, posx, posy, posz}




for id, i in pairs(players) do

    print(id.." - "..tostring(players.name))

end
    
asked by anonymous 20.12.2017 / 16:50

1 answer

0

You only need to set the reference in the table (key, value):

name   = {"Lowes", "Renata", "Titia", "Maria"}
health = {}
posx   = {}
posy   = {}
posz   = {}

players = {["name"]=name, ["health"]=health, ["posx"]=posx, ["posy"]=posy, ["posz"]=posz}

for key, value in pairs(players) do
    print("players["..key.."]")
    for k, v in pairs(players[key]) do
       print(k.." -> "..v)
    end
 end

EDIT

online_players = {}
users = {"Lowes", "Renata", "Titia", "Maria"}

function create_player(name)
    return { name = name }
end

function add_attr(player, attr, value)
    player[attr] = value
end

-- lista todos os jogadores
for _, value in pairs(users) do

    --inicializa o jogador
    player = create_player(value);

    --adiciona os demais atributos do jogador
    add_attr(player, "health", 10)
    add_attr(player, "posx", math.random(1,10))
    add_attr(player, "posy", math.random(1,10))
    add_attr(player, "posz", math.random(1,10))
    add_attr(player, "custom", { age = math.random(1,60) })

    table.insert(online_players, player)
end

-- exibe os attributos dos jogadores
for _, player in pairs(online_players) do

    print("-- Player Attributes --")
    print("Name: "..player.name)
    print("Health: "..player.health)
    print("PosX: "..player.posx)
    print("PosY: "..player.posy)
    print("PosZ: "..player.posy)
    print("Custom: "..player.custom.age)
    print("")

end

You can also get all the attributes of each player dynamically using the pairs () loop.

    
20.12.2017 / 17:08