I am having trouble with my tables, I am making a text adventure in lua
local locxy = {}
locxy[1] = {}
locxy[1][1] = {}
locxy[1][1]["locdesc"] = "dungeon cell"
locxy[1][1]["items"] = {"nothing"}
locxy[1][1]["monsters"] = {monster1}
The [1][1] refers to x,y coordinates and using a move command I can successfully move into different rooms and receive the description of said room.
Items and monsters are nested tables since multiple items can be held there (each with their own properties).
The problem I am having is getting the items/monsters part to work. I have a separate table such as:
local monsters = {}
monsters["rat"] = {}
monsters["rat"]["Name"] = "a rat"
monsters["rat"]["Health"] = 5
monsters["rat"]["Attack"] = 1
I am using a table like this to create outlines for various enemy types. The monster1 is a variable I can insert into the location table to call upon one of these outlines, however I don't know how to reference it.
print("You are in ", locxy[x][y]["locdesc"]) -- this works
print("You can see a ", locxy[x][y]["monsters]["Name"],".") - does not work
So I would like to know how I can get that to work, I may need a different approach which is fine since I am learning. But I would also specifically like to know how to / if it possible to use a variable within a table entry that points to data in a separate table.
Thanks for any help that can be offered!
This line
locxy[x][y]["monsters]["Name"]
says
look in the locxy table for the x field
then look in the y field of that value
look in the "monsters"` field of that value
then look in the "Name" field of that value
The problem is that the table you get back from locxy[x][y]["monsters"] doesn't have a "Name" field. It has some number of entries in numerical indices.
locxy[x][y]["monsters][1]["Name"] will get you the name of the first monster in that table but you will need to loop over the monsters table to get all of them.
Style notes:
Instead of:
tab = {}
tab[1] = {}
tab[1][1] = {}
you can just use:
tab = {
[1] = {
{}
}
}
and instead of:
monsters = {}
monsters["rat"] = {}
monsters["rat"]["Name"] = "foo"
you can just use:
monsters = {
rat = {
Name = "foo"
}
}
Or ["rat"] and ["Name"] if you want to be explicit in your keys.
Similarly instead of monsters["rat"]["Name"] you can use monsters.rat.Name.
Related
So im trying to add a table inside another table but each time i do it, it adds a "1": from nowhere...
my code :
local previousClothes = json.decode(xPlayer.get('clothes'))
print("old previousClothes"..json.encode(previousClothes))
local clothes = {[label] = {[parentName] = parentValue, [partName] = partValue}}
print("old clothes"..json.encode(clothes))
clothes[#clothes+1] = previousClothes
print("new clothes: "..json.encode(clothes))
xPlayer.get('clothes') = my clothes stored in my db
local clothes = my new clothes received in the function/event
and here comes my issue.. it adds a "1": to my table
https://i.stack.imgur.com/sb5pj.png
Instead of adding previousClothes as an array element to clothes, you can copy key-value pairs of previousClothes into clothes.
for k, v in pairs(previousClothes) do
clothes[k] = v
end
I assume this is what you want.
Because Your clothes is not an array, see the documentation in here. When you use # get a table length, it is better to be an array.
Hello i have got a table, that uses string indexes:
shirt = {
["shirtwhite.png"] = "shirt_white.png",
["shirtwhite.png^[multiply:#3f3f3f"] = "shirt_white.png^[multiply:#3f3f3f",
["shirtwhite.png^[multiply:#ff0000"] = "shirt_white.png^[multiply:#ff0000",
["shirtwhite.png^[multiply:#ff7f00"] = "shirt_white.png^[multiply:#ff7f00",
["shirtwhite.png^[multiply:#ffff00"] = "shirt_white.png^[multiply:#ffff00",
["shirtwhite.png^[multiply:#00ff00"] = "shirt_white.png^[multiply:#00ff00",
["shirtwhite.png^[multiply:#0000ff"] = "shirt_white.png^[multiply:#0000ff",
["shirtwhite.png^[multiply:#9f00ff"] = "shirt_white.png^[multiply:#9f00ff",
},
Theese are t-shirt-textures for an editable game-character-skin (with colour-values for different colors).
There are some more of theese tables in the code, for other parts of the character-skin
how can I keep the table in it´s shown order, while it´s loaded in this code-snippet?
The tzables are in a file "skins.lua" and the code-snippet is from another lua-file
character_creator = {}
character_creator.skins = dofile(minetest.get_modpath("character_creator") .. "/skins.lua")
local skins = character_creator.skins
local skins_array = {}
minetest.after(0, function()
local function associative_to_array(associative)
local array = {}
for key in pairs(associative) do
table.insert(array, key)
end
return array
end
skins_array = {
skin = associative_to_array(skins.skin),
hair = associative_to_array(skins.hair),
eyes = associative_to_array(skins.eyes),
shirt = associative_to_array(skins.shirt),
pants = associative_to_array(skins.pants),
}
end)
In Lua only arrays (positive integer-indexed tables) have "order" (can be iterated using ipairs); the hash tables (like the one you are working with) are unordered. If you want to iterate over a table like this in a specific order, you'd usually create an array with the keys, sorted them in the order you want and then iterate over that array extracting elements from your table.
There are also components (like ordered table) that may keep track of insertions and return results in the same order, if that's what you want.
I parsed some data from a CSV file to a Lua table.
Lets say the table looks like this just bigger
tab {
{ id = 1761, anotherID=2, ping=pong}
{ id = 2071, anotherID=4, ping=notpong}
}
Now I want to know every ID (without displaying any other data yet) to store them in another table for some time.
I am completely lost here for now..
Using what you wrote I rewrote it a bit and went to have:
minitab = {}
for i, value in ipairs(tab) do
local id = value.id
local anotherID = value.anotherID
minitab[id] = anotherID
end
Would that work? In fact i later want to get just 2 values of a way larger array (around 30 datas) - but I can only push a single array to a GUI dropdown. I want to save the ID as a key and the "anotherID" value wich will be a text after that key so if a ask for the 2071st value it displays the "name" 4
The code below stores the ids as keys in another table:
id={}
for k,v in ipairs(tab) do
id[v.id]=true
end
You can then traverse id with pairs to list the ids.
If you want to remember where each id came from, use id[v.id]=k in the loop.
Based on your question, you can use this code to traverse your data table tab and get minitab to be used for your GUI array:
--data
tab = {
{id = "4204", label = "2", desc = "Roancyme"},
{id = "5517", label = "9", desc = "Bicktuft"},
{id = "1035", label = "3", desc = "Pipyalum"},
}
--temporary table
local minitab = {}
for i, option in ipairs(tab) do
minitab[option.id] = option.label
end
--print minitab
print('<select>')
for id, label in pairs(minitab) do
print(string.format('<option value="%s">%s</option>', id, label)) --> <option value="1035">3</option>
end
print('</select>')
print()
However, I don't think it is necessary to create a temporary table to store those values, because you can easily traverse your original table tab and directly pull out the output you need; like this:
--print directly from tab
print('<select>')
for i, option in ipairs(tab) do
print(string.format('<option value="%s">%s</option>', option.id, option.label)) --> <option value="1035">3</option>
end
print('</select>')
print()
Unless you need to work with it before displaying the list on the drop down (e.g. add some prefix to the label, sort minitab by the label, etc); but you don't want to disturb the original data table tab. In this case, it would make sense to use the temporary table.
--format values in temporary table
local minitab = {}
for i, option in ipairs(tab) do
local minitabID = option.id
local minitabLabel = string.format('Item %s - %s', option.label, option.desc)
table.insert(minitab, {id = minitabID, label = minitabLabel})
end
--sort temporary table
table.sort(minitab, function (o1, o2) return o2.label > o1. label end)
--print formatted values from temporary table
print('<select>')
for i, option in ipairs(minitab) do
print(string.format('<option value="%s">%s</option>', option.id, option.label)) --> <option value="4204">Item 2 - Roancyme</option>
end
print('</select>')
NB: Please take a note on which table iteration uses ipairs and which one uses pairs. See the complete code snippet here.
Backpack = {Potion = 'backpack',Stack = 'bag',Loot = 'derp', Gold = 'random'}
Backpack[1] ~= 'backpack' -- nope
As you guys can see, I cannot call Backpack[1] since its not a numeral table, how would I generate a table after the construction of Backpack, consisting only of it's values? for example:
Table_to_be_Constructed = {Value of Potion,Value of Stack,Value of Loot,Value of Gold} -- this is what i need
It seems simple but I couldn't find a way to do it.
I need it this way because i will run a numeric loop on Table_to_be_Constructed[i]
To iterate over all the key-value pairs in a table, use the pairs function:
local Table_to_be_Constructed = {}
for key, value in pairs(Backpack) do
table.insert(Table_to_be_Constructed, value)
end
Note: the iteration order is not defined. So, you might want to sort Table_to_be_Constructed afterwards.
By convention, the variable name _ is used to indicate a variable who's value won't be used. So, since you want only the values in the tables, you might write the loop this way instead:
for _, value in pairs(Backpack) do
For the updated question
Backpack has no order (The order in the constructor statement is not preserved.) If you want to add an order to its values when constructing Table_to_be_Constructed, you can do it directly like this:
local Table_to_be_Constructed = {
Backpack.Potion,
Backpack.Stack,
Backpack.Loot,
Backpack.Gold
}
Or indirectly like this:
local items = { 'Potion', 'Stack', 'Loot', 'Gold' }
local Table_to_be_Constructed = {}
for i=1, #items do
Table_to_be_Constructed[i] = Backpack[items[i]]
end
Just picking upon Lua and trying to figure out how to construct tables.
I have done a search and found information on table.insert but all the examples I have found seem to assume I only want numeric indices while what I want to do is add key pairs.
So, I wonder if this is valid?
my_table = {}
my_table.insert(key = "Table Key", val = "Table Value")
This would be done in a loop and I need to be able to access the contents later in:
for k, v in pairs(my_table) do
...
end
Thanks
There are essentially two ways to create tables and fill them with data.
First is to create and fill the table at once using a table constructor. This is done like follows:
tab = {
keyone = "first value", -- this will be available as tab.keyone or tab["keyone"]
["keytwo"] = "second value", -- this uses the full syntax
}
When you do not know what values you want there beforehand, you can first create the table using {} and then fill it using the [] operator:
tab = {}
tab["somekey"] = "some value" -- these two lines ...
tab.somekey = "some value" -- ... are equivalent
Note that you can use the second (dot) syntax sugar only if the key is a string respecting the "identifier" rules - i.e. starts with a letter or underscore and contains only letters, numbers and underscore.
P.S.: Of course you can combine the two ways: create a table with the table constructor and then fill the rest using the [] operator:
tab = { type = 'list' }
tab.key1 = 'value one'
tab['key2'] = 'value two'
Appears this should be the answer:
my_table = {}
Key = "Table Key"
-- my_table.Key = "Table Value"
my_table[Key] = "Table Value"
Did the job for me.