You only need to set the reference in 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 take all attributes of each player dynamically using the loop with pairs().
I understood, but what I want to do is the following: create a function that "adds" new chars in the table and another function that fetches the name of this char and returns the values. I tried what you gave me and I got an idea.
– lowes
What I didn’t get (in the old code) was to transform a string into a variable, as it would create a separate table for each player.
– lowes
I think I got it, I’ll edit it with an example. See if it helps.
– Tom Melo
Thank you very much, friend. Just one more thing, can you explain to me what pairs, ipairs and pairsbykeys mean? And why _,? Thank you. :)
– lowes
_ no for is just a representation of a variable I want to ignore, in which case I don’t want to use the "key" that pairs() returns. About the difference between functions I believe it is a question of sorting, which elements will be returned first in the loop. I think this link should help you: http://www.luafaq.org/#T1.10
– Tom Melo
Why use the
add_attr
?player.health = 10
would not work?– Francisco
add_attr is just to demonstrate how to create an attribute dynamically. It is totally unnecessary to use this function.
– Tom Melo