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"].
Related
im trying to compare 2 arrays but i dont know how
for example:
local array1 = { 'friend', 'work', 'privat' }
local array2 = { 'apple', 'juice', 'privat' }
if both arrays have the same value it should do a print.
i know i need to work with something like this
for x in ipairs(array1) do
if x == array2 then
print ("Hi")
end
end
but ofcourse it didnt work.
so how can i check if the array1 value contains a values from array2?
Think of it this way: You have to check each element in the first array to its counterpart in the second. If any element is not equal, you know right away that the arrays aren't equal. If every element checks out as equal, the arrays are equal.
local function arrayEqual(a1, a2)
-- Check length, or else the loop isn't valid.
if #a1 ~= #a2 then
return false
end
-- Check each element.
for i, v in ipairs(a1) do
if v ~= a2[i] then
return false
end
end
-- We've checked everything.
return true
end
how can i check if the array1 value contains a values from array2?
#luther's answer will not always work for your question..
If the arrays are different sizes, it completely fails.
If you have an array where similar element are not in the exact same index, it can return a false negative.
for example a = {'one', 'two'}; b = {'two', 'one'} will return false
Using table.sort to solve this would be a band-aid solution without fixing the real problem.
The function below will work with arrays of different sizes containing elements in any order
function array_compare(a, b)
for ia, va in ipairs(a) do
for ib, vb in ipairs(b) do
if va == vb then
print("matching:",va)
end
end
end
end
In array_compare we go through all the combinations of elements in table a and table b, compare them, and print if they are equal.
ipairs(table) uses index, value (instead of just value)
For example
local array1 = { 'friend', 'work', 'privat' }
local array2 = { 'apple', 'juice', 'privat' }
array_compare(array1, array2)
will print
matching: privat
(I'm writing a second answer to account for another possible interpretation of the question.)
If you want to see if array1 contains any value that's also in array2, you can do the following:
Convert array1 to a set. A set is a new table where the array's values become keys whose values are true.
Iterate through array2 to see if any of its values are a key in the set.
local set = {}
for _, v in ipairs(array1) do
set[v] = true
end
for _, v in ipairs(array2) do
if set[v] then
print'Hi'
-- Use a break statement if you only want to say hi once.
end
end
If the arrays are large, this algorithm should be faster than a nested loop that compares every value in array1 to every value in array2.
Am I able to make a separated table filled with elements from other tables in Lua? Like this:
TableA = { a=1, b=2, c=3 }
TableB = { John=4, Jane =5 }
TableC = { x = "asd", y = "dsa", z = "sda" }
TableAll = { TableA.a, TableB.John, TableC.x}
It's a general example, but may work. I'm not sure in it.
Is there some reason why that wouldn't work?
All that tablename.key does is access an element of a table. This is a value; the fact that it came from a table is completely irrelevant. The value returned by tablename.key is no different than the value 5, nil, true, "some string", or any other value in Lua.
You can initialize a table with values; it doesn't matter where those values come from.
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"].
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.
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"]};