In the command
table.insert(table, data)
how can you use that but for the inserts have string keys?
PSEUDO CODE
tableOfStuff = {cat, pig, hat, lemon}
t = {}
for i=1, #tableOfStuff do
table.insert(t, key=tableOfStuff[i], data=tableOfStuff[i])
end
So I end up with a table...
t['cat'] == 'cat'
t['dog'] == 'dog'
etc.....
EDIT
I think my example confused people... I am asking how to use "insert.table" but insert tings with string keys...
table.insert(table,data,stringkey)
something like this?
Creating One Table
If all you want is to create a table with strings as keys, then check out Table Constructors, you have a couple options.
Option 1:
t = { key1 = "value1", key2 = "value2" }
--or like this:
t = { ["key1"] = "value1", ["key2"] = "value2" }
Option 2: (create an empty table first)
t = {}
t.key1 = "value1"
--or like this
t["key2"] = "value2"
It looks like you want the keys and values to be the same string and that is possible. Just write the same thing for key1 and value1. So t["cat"] = "cat".
Using Two Tables
Based on your example code, it looks like you want to take an existing table of strings and create from that a new table with strings as both the keys and the values. To do that:
table1 = { "cat", "pig", "hat", "lemon" }
table2 = {}
for i=1, #table1 do
table2[ table1[i] ] = table1[i]
end
--test
print table2["cat"]
Here is a good lesson about tables in Lua: Lua Tables Tutorial
The comment is right.You needn't and you can't use table.insert.You can see the document table.insert.It's only support the number.It' used for the array part of table.But you're using the hash part of a table.
code:
tableOfStuff = {"cat", "pig", "hat", "lemon"}
t = {}
for i=1, #tableOfStuff do
local szKey = tableOfStuff[i];
t[szKey] = tableOfStuff[i]; -- the value can be the others.
end
Related
I have some lua code like this:
_table = {
stuff = {
item1 = {Name="Stack",Rarity="Over"};
item2 = {Name="Flow",Rarity="Com"}
};
};
print("placeholder") -- example thing
_stuff = _table.stuff
for i = 1, #_stuff do
print(_stuff[i].Name)
end
The output is this:
placeholder
I've tried to look at stuff but I don't think it was related to my problem.
Lua tables conceptually are "maps": They map keys to values. Your table _table maps the key stuff to the {item1 = ..., item2 = ...} table. Your stuff table maps the string "item1" to the {Name="Stack",Rarity="Over"} table and the string "item2" to the {Name="Flow",Rarity="Com"} table.
The length operator # completely ignores string keys. It returns an integer i such that t[i] ~= nil and t[i+1] == nil. In particular, it returns 0 if there are no integer keys in the table. This is the case for your stuff table: You only have string keys. Thus your loop never runs, as the limit is 0 and i = 1 > 0 already is the case before the first loop iteration.
Put simply, you're trying to iterate over a "dictionary" (a table with string keys) as if it were a list. Lua tables have both a "list part" (integer keys from 1 to n, where usually n = #t) and a "hash part" (of all other keys). The "list part" is empty in your case, so there's nothing for you to iterate over.
To iterate over all key-value pairs of any table (list or dictionary) in an undefined order, use pairs (rather than ipairs or iterating over indices i, which only works for lists):
for itemname, item in pairs(_stuff) do
print(item.Name)
end
If you want a defined order of iteration, either build a second table of keys...
local order = {"item1", "item2"}
for _, key in ipairs(order) do
print(_stuff[key].Name)
end
... or use the integer keys ("list part") of the table:
_table = {
stuff = {
{key = "item1", Name="Stack", Rarity="Over"};
{key = "item2", Name="Flow", Rarity="Com"};
};
};
_stuff = _table.stuff
for _, key in ipairs(order) do
for i = 1, #_stuff do
print(_stuff[i].Name)
end
end
then works as expected.
So I have a dictionary:
local toFind = "Layla"
local songs = {
{name = "Eric Clapton - Layla", id = "123"},
{name = "Eric Clapton - I Shot The Sheriff", id = "321"}
}
Is it possible to use string.find(songs, toFind) or something similar to find the table that contains the "Layla" string?
All strings have string functions attached as methods.
Therefore you can directly do...
for k,v in pairs(songs) do
if v.name:find(toFind) then
return songs[k], v.name
end
end
...that returns the table and the full Text...
table: 0x565cbec0 Eric Clapton - Layla
Is it possible to have a function that can access arbitrarily nested entries of a table?
The following example is just for one table. But in my real application I need the function to check several different tables for the given (nested) index.
local table1 = {
value1 = "test1",
subtable1 = {
subvalue1 = "subvalue1",
},
}
local function myAccess(index)
return table1[index]
end
-- This is fine:
print (myAccess("value1"))
-- But how do I access subtable1.subvalue1?
print (myAccess("subtable1.subvalue1???"))
You won't be able to do this using a string unless you use load to treat it as Lua code or make a function to walk on a table.
You can make a function which will split your string by . to get each key and then go one by one.
You can do this using gmatch + one local above gmatch with current table.
#Spar: Is this what you were suggesting? It works anyway, so thanks!
local table1 = {
value1 = "test1",
subtable1 = {
subvalue1 = "subvalue1",
},
}
local function myAccess(index)
local returnValue = table1
for key in string.gmatch(index, "[^.]+") do
if returnValue[key] then
returnValue = returnValue[key]
else
return nil
end
end
return returnValue
end
-- This is fine:
print (myAccess("value1"))
-- So is this:
print (myAccess("subtable1.subvalue1"))
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"]};
I have a table in lua with some data.
sometable = {
{name = "bob", something = "foo"},
{name = "greg", something = "bar"}
}
I then want to loop through the table and assign a number to each name as a variable. New to lua and tried it like this.
for i,t in ipairs(sometable) do
t.name = i
end
I was then assuming print("name1", bob) would give me name1 = 1. Right now I'm getting nil. So I'm back to my ugly static list of variables till some kind soul tells me how I'm an idiot.
> sometable = {{name = "bob", something = "foo"},{name = "greg", something = "bar"}}
> for i,t in ipairs(sometable) do t[t.name] = i end
> for i,t in ipairs(sometable) do for j,u in pairs (t) do print (j,u) end end
name bob
something foo
bob 1
greg 2
something bar
name greg
> return sometable[1].bob
1>
The ipairs function will iterate only through numerically indexed tables in ascending order.
What you want to use is the pairs function. It will iterate over every key in the table, no matter what type it is.