How to get access to a value inside a table inside array? - lua

I have this structure and I'm trying to access the last index:
table = { {[11] = 22}, {[255] = 1}, {[55] = 1000} }
I have tried this, but it returns me nil
print(table[#table][1])
how do I get that 1000 value?

since you use numeric keys it's actually table[#table][55].

Related

converting string to table data type

I have some code, I want it to pick a random string from the list and convert it to a data type to be used in joypad.set() function.
Here is my code:
Buttons = { A = true,
B = true,
Down = true}
while (true) do
Random = math.random(3)
NewButton = (Buttons[Random])
joypad.set(1, (NewButton))
emu.frameadvance();
end;
You don't state your problem, but from your code, it looks like you're not getting the values from the array you expect. You're getting a random number between 1 and 3, but A, B, and Down are not 1, 2, and 3. Buttons is an associative array (key-value pairs) the way you declare it, so if you want to use it this way, you will need to set up a second array with just the key names, and get a random index from that, like so:
ButtonKeys = { "A", "B", "Down" }
Random = math.random(3)
NewButton = (Buttons[ButtonKeys[Random]])
This creates a table with the values of A, B, and Down as index 1, 2, and 3, so you use the random number to get the value from the ButtonKeys array, then use that value as the index for the Buttons array.
Edit: I reread the question and went over my original answer and realized I was thinking about you declaring the table differently. The way you declare the table, A, B, and Down become properties of Buttons, which you can access by calling them directly like Buttons.A, Buttons.B, and Buttons.C, or by using brackets with a string name of the property you want to access. In your case, Buttons["A"], Buttons["B"], and Buttons["Down"].

Lua Tables Assigning values to key in tables

Um what's the difference between in assigning values:
Lesson["Maths"] = {grade = 10, class = 3}
and
Lesson["Maths"] = {["grade"] = 10, ["class"] = 3}
Which one should I go if I want to assign a value to a key in a table? Or which one is more used? Thanks a lot
In your case, both of them are the same. The first usage fails when you want keys with special characters in them:
tEx = {
failed-approach = true,
}
The code segment above will result in an error and you would be forced to follow the second method of creating keys:
tEx = {
['failed-approach'] = false,
}
Both of the approaches are same and it doesn't matter which one you wish to use.

Lua pass function argument as a table key

I'm working on exporting the contents of a Lua table to a HTML File so I can display the contents in the browser. Right now I'm having problems with passing a function argument as a table key.
I have a sparse table as such:
map = {}
for x = 1, 20 do
map[x] = {}
for y = 1, 20 do
map[x][y] = {}
map[x][y].node = math.random(1,20)
map[x][y].image = "path/to/image.png"
end
end
I pass the table to my function as such:
htmParser:_dumpSparseToHTML(map, 20, 20) where map = table I want to pass, 20,20 = width and height of the array. Somewhere in _dumpSparseToHTML I write the values of v.node and v.image to the file. How do I handle the exact same thing without knowing the name of the keys in the table? For example map could contain map[x][y].value, map[x][y].gfx, map[x][y].nodeType, and I would like to pass them as htmParser:_dumpSparseToHTML(map, 20, 20, value, gfx, nodeType, etc).
I know that Lua can handle a variable number of arguments, by defining the function as: _dumpSparseToHTML(map, 20, 20, ...). I tried to do the following:
--_table = map
for i,v in ipairs(arg) do
file:write("<td>".._table[x][y].v.."</td>)
end
The error I get is: "attempt to concatenate field 'v' (a nil value).
So, my question is: how do I pass a variable number of arguments as table keys?
You need to use _table[x][y][v] for that. _table[x][y].v is _table[x][y]["v"].

Nested tables and numerical keys in Lua

I'm not sure if this is possible due to the numerical indices, but hopefully someone can point me in the right direction.
Given the table of:
t = { 13, 200, 12, 15, 23 }
how can I nest a table using the numbers?
t["200"] = {"stuff", "more stuff", "even more stuff"}
doesn't seem to work, as it'll create a position 200 and fill in the empty cells with null. I'd add a letter as a suffix/prefix, but the problem comes trying to sort the table numerically. Is this even possible, or am I stuck with a different method? Thanks!
Slight edit due to a realisation:
t["200"] = {"stuff", "more stuff", "even more stuff"}
actually creates a key of "200", whereas:
t[200] = {"stuff", "more stuff", "even more stuff"}
creates the index 200 with everything else null.
First, DeadMG is correct; you used a string rather than a numerical index. However, even if you did use a number index, it wouldn't help.
If you do this:
someTable = {"value1", "value2", {"value3a", "value3b"}};
someTable[50] = {"value50a", "value50b"};
The length of the table, #someTable, will still be 3. Why? Because Lua defines arrays in a table based on contiguous elements. Remember: you can access any element of any table; they are all conceptually filled with nil until you give them an actual value.
Lua defines length for a table as the number of values in a table if you start counting from numerical index 1 until you reach the first nil value. Since someTable[4] is nil, the length is 3.
If you want to insert a new element at the end of an array table, then you can do this:
someTable[#someTable + 1] = "newValue";
The value can itself be a table:
someTable[#someTable + 1] = {"newValuea", "newValueb"};
If you're just asking how to access a nested table, that's simple, and it has nothing to do with the keys you use.
There is nothing special about nested tables. Tables are values, and table entries can be any value, including other tables.
If you have a table, and want to walk the array entries in it, you use this:
local aTable = {"first", "second", "third", ...}
for i, value in ipairs(aTable) do
--`value` contains the entries in the table.
end
A nested table is no different; it is simply a matter of getting the table.
local nestedTable = { "first", "second", "third", ...}
nestedTable[#nestedTable + 1] = {"newFirst", "newSecond", ...}
local aTable = nestedTable[#nestedTable];
for i, value in ipairs(aTable) do
--`value` contains the entries in the table.
end
Or you could just do ipairs(nestedTable[#nestedTable]). Note that the particular key used here (an integer value) is entirely unimportant. That key could have been a string, a floating-point number, another table, some user-data, etc. It doesn't matter.
Note also that we use ipairs because we only want to iterate over the array members of the table. The length of the array is defined above. If we wanted to loop over every member of the table, we would use pairs instead of ipairs. Of course, pairs does an unordered search, so it is not guaranteed to be in array order.
If you want to recursively find every element in a nested table, you can do this:
local function RecursiveSearch(aTable)
for key, value in pairs(aTable) do --unordered search
if(type(value) == "table") then
RecursiveSearch(value)
else
--Do something with this.
end
end
end
Note that the above can do an infinite loop, since it is possible for a table to have circular references:
local tableA = {}
local tableB = {tableA}
local tableA[1] = tableB
RecursiveSearch(tableA) --Infinite loop.
Perhaps it helps to view your assignment like this:
t = { [1] = 13, [2] = 200, [3] = 12, [4] = 15, [5] = 23 }
To change what is currently 200 (namely t[2]), you do:
t[2] = {"stuff", "more stuff", "even more stuff"}
Edit: that results in your table looking like this:
t = { [1] = 13, [2] = {"stuff", "more stuff", "even more stuff"}, [3] = 12, [4] = 15, [5] = 23 }
-- or, equivalent::
t = { 13, {"stuff", "more stuff", "even more stuff"}, 12, 15, 23 }
The trouble is your use of "". Your table t contains a bunch of numbers, and you're entering a string as the key. You want to iterate over the table and do... something that you didn't particularly well define. However, you can't add to a table whilst iterating over it, so you might have to do some funny stuff.
t = { 13, 200, 12, 15, 23 }
newt = {};
for key, value in pairs(t) {
newt[value] = { };
}
This will create a table entry in newt, where the key is a value in the table t, for all values in t.

How to quickly initialise an associative table in Lua?

In Lua, you can create a table the following way :
local t = { 1, 2, 3, 4, 5 }
However, I want to create an associative table, I have to do it the following way :
local t = {}
t['foo'] = 1
t['bar'] = 2
The following gives an error :
local t = { 'foo' = 1, 'bar' = 2 }
Is there a way to do it similarly to my first code snippet ?
The correct way to write this is either
local t = { foo = 1, bar = 2}
Or, if the keys in your table are not legal identifiers:
local t = { ["one key"] = 1, ["another key"] = 2}
i belive it works a bit better and understandable if you look at it like this
local tablename = {["key"]="value",
["key1"]="value",
...}
finding a result with : tablename.key=value
Tables as dictionaries
Tables can also be used to store information which is not indexed
numerically, or sequentially, as with arrays. These storage types are
sometimes called dictionaries, associative arrays, hashes, or mapping
types. We'll use the term dictionary where an element pair has a key
and a value. The key is used to set and retrieve a value associated
with it. Note that just like arrays we can use the table[key] = value
format to insert elements into the table. A key need not be a number,
it can be a string, or for that matter, nearly any other Lua object
(except for nil or 0/0). Let's construct a table with some key-value
pairs in it:
> t = { apple="green", orange="orange", banana="yellow" }
> for k,v in pairs(t) do print(k,v) end
apple green
orange orange
banana yellow
from : http://lua-users.org/wiki/TablesTutorial
To initialize associative array which has string keys matched by string values, you should use
local petFamilies = {["Bat"]="Cunning",["Bear"]="Tenacity"};
but not
local petFamilies = {["Bat"]=["Cunning"],["Bear"]=["Tenacity"]};

Resources