Insert elements to a table inside other table - lua

I need help to know how to do for use table.insert, and insert elements in to one table that is in to another table. This what i have:
Table = {} --Main table
function InsertNewValues()
local TIME = --Any value, string or integer
local SIGNAL = --Any value, string or integer
table.insert(Table, {TIME, SIGNAL})
end
Ok, this allow me to insert the values of TIME and SIGNAL everytime i call that function, so the table will have:
Table[1][1] = TIME
Table[1][2] = SINGAL
...
Table[...][1] = TIME
Table[...][2] = SIGNAL
BUT ... I need to insert the values of TIME and SIGNAL in to another table that is inside of the table "Table", and that table work as a KEY to refer those values ... TIME and SIGNAL ...
therefore, the resulting table would be the following:
+Table
|
+-[1]othertable
|
+-+[1]TIME - [2]SIGNAL
+-+[1]TIME - [2]SIGNAL
+- ...
|
+-[2]othertable
|
+-+[1]TIME - [2]SIGNAL
+-+[1]TIME - [2]SIGNAL
+- ...
How can i do for do that?
----------------- EDIT -----------------
I have not explained myself well, what I need is:
Given a table called "Table", I need to be able to use "strings" as "keys" within that table. That would be:
-- Name of my "container" table
Table = {}
Values to be introduced
Time = '1 seconds' -- this value can change as desired
Value = 'logic' -- this value can change as desired
Add to my master table "Table", using the string key "RandomName"
-- "RandomName" can change as desired
function AddNewValues ()
table.insert (Table [RandomName], {Time, Value})
end
Every time I call the function "AddNewValues ()", it should add the values present in "Time" and "Value" as a "NEW ENTRY" for that "RandomName".
So the table result may should look like this:
+table -- that contains
+-RandomName-- string key to access
+--"Time,Value"
+--"Time,Value"
+--"Time,Value"
+...
And then, to be able to access the values that are inside that table, using "RandomName" as the key:
function Load()
for key, v in pairs(Table) do
a = Table[key][RandomName][1] -- reference to "Time"
b = Table[key][RandomName][2] -- reference to "Value"
print('Time: ' .. a ..'/' .. 'Value: ' .. b)
end
end

You're just not starting deep enough into the table. When you want the sequence values for the table under the key equaling the value of RandomName, just do:
function Load()
for _, v in ipairs(Table[RandomName]) do
a = v[1] -- reference to "Time"
b = v[RandomName][2] -- reference to "Value"
print('Time: ' .. a ..'/' .. 'Value: ' .. b)
end
end
Answer to original question:
It appears that you want something like this:
Table = { ["[1]othertable"] = {}, ["[2]othertable"] = {} }
table.insert(Table["[1]othertable"], {TIME, SIGNAL})
The keys are "[1]othertable" and "[2]othertable".
You might prefer to use keys like "othertable1" and "othertable2". If you use valid identifiers you can drop some of the syntax:
Table = { othertable1 = {}, othertable2 = {} }
table.insert(Table.othertable1, {TIME, SIGNAL})
In fact, you might prefer to do something similar with TIME and SIGNAL. Instead of positive integer indices, you could use string keys:
Table = { othertable1 = {}, othertable2 = {} }
table.insert(Table.othertable1, {TIME = 12.42, SIGNAL = 3.2})
print(Table.othertable1[1].TIME)

Related

Get index of table Lua from string input

Suppose I have the following:
table = {a = {1, 2}, b = {3, 4}}
input = "a" -- abstracted away; it's a RV from another function.
You can use table.a[1] to get 1; however, I want to get it from the input variable - which is the return value of another function that I have, which returns the string "a" and not just a.
Now, this is where the error from here comes into play:
When I did table[input], it returned a table object, so then when I tried table[input][1], it had the calling a table error.
Is it possible to get 1 using indexing with the input "a"? If so, could someone let me know how this works? Thanks!
for any table if you use . to index it, it will use a string index.
When you use [] to index it, this means you can use any sort of datatype and it allows you to also use variables.
local someTable = {
a = "hello",
b = "world"
c = "!"
}
-- I can do
print(someTable.a) -- prints "hello"
-- and
print(someTable["b"]) -- prints "world"
-- however
print(someTable[c]) -- will error since there is no c variable
------
-- note that this would be valid
local someVariable = "c"
print(someTable[someVariable]) -- prints "!"
Going back to your case. tbl1 is using [] and using the variable input. However tbl2 is using the string "input" as the index in your table. Your table does not contain "input" as a key, so it returns nil
I hope I understand your question correctly, I apologize if not. If you want to, for example, send a specific part of a table to a user after they specified which key of the table they want then you're already doing everything correctly.
The tbl1 table contains the key "a" part of the main table. You can't print a table, but you can either print specific values by using tbl1[number] or do this:
table = {a = {1, 2}, b = {3, 4}}
input = "b"
tbl1 = table[input]
for _, v in pairs(table) do
print(v)
end
-- Expected output:
-- 3
-- 4

Lua new table from smaller table

Struggling with a specific Lua table problem, extracting values from a smaller table to set on/off switches for a longer table.
I have an iterator:
for i = 0,11 do
some things
end
Inside the iterator with length 12 I wish to extract values from a table that might look like this (always <= iterator length):
t = {0,2,4,6,8,10}
and generate a new table with the iterator so that if index i = t value insert 1 else insert 0. That is, the new table would look like this:
newTable = {1,0,1,0,1,0,1,0,1,0,1,0}
Help?
t = {0,2,4,6,8,10}
newTable = {}
for i = 0, 11 do
newTable[i] = 0
end -- Set the entire new table to 0's
for _, v in ipairs(t) do
newTable[v] = 1
end -- Loop through t, replace the 0's in new table with a 1 where newTable[v]

Lua how to access specific data in a nested table

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.

Get table key name from value

I'm trying to get table key name from a value.
tostring only returns table: XXXXXXXXX
I tried some functions but nothing work.
config = {
opt1 = "etc..."
}
players = {}
function openMenu(playerName, configTable)
players[playerName] = Something to get Table Key...
-- read the table and create a gui not yet made
end
And next, if I do this :
print(players[playerName])
I want to get this output :
"config"
You will need to iterate over all pairs of the table and return the key if the value is equal. Note that this will only return one binding, even if multiple keys can lead to the same value:
function find(tbl, val)
for k, v in pairs(tbl) do
if v == val then return k end
end
return nil
end
table.find(t, value [,start_index]) -> [key or nil]

Create a numerical table from the values of a non numerical table

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

Resources