I can't get table entry index. I need it to remove an item from table.
I use table.insert to add entries to table.
Another question: why Lua doesn't have "overload" to function table.remove so one can remove item by associative index?
Tables implement an unordered one to many relation between keys and values. In other words, any particular key (index) can only appear once in a table, but a value can appear multiple times.
If you know the key k, then t[k] = nil will remove both the key and the associated value from the table. However, this operation has no effect on any other keys or values in the table.
The table.insert and table.remove functions operate over the set of sequential integer keys beginning at 1, that are used by convention to implement arrays or lists. For that purpose, they manipulate other values in the list so as to keep the list from developing holes.
One way to find a key at which some value is found is to simply search the table. If this will be done more than once, then it is probably a good idea to build a second table that inverts the key/value pairs so that lookup by value is as fast as lookup by index.
A suitable implementation will depend on your assumptions and needs. Some samples are:
-- return the first integer index holding the value
function AnIndexOf(t,val)
for k,v in ipairs(t) do
if v == val then return k end
end
end
-- return any key holding the value
function AKeyOf(t,val)
for k,v in pairs(t) do
if v == val then return k end
end
end
-- return all keys holding the value
function AllKeysOf(t,val)
local s={}
for k,v in pairs(t) do
if v == val then s[#s+1] = k end
end
return s
end
-- invert a table so that each value is the key holding one key to that value
-- in the original table.
function Invert(t)
local i={}
for k,v in pairs(t) do
i[v] = k
end
return i
end
t[k]=nil removes from t the entry with key k.
For the second question, the answer is that tables can have individual metatables.
Related
Example:
mytable = {{id=100,wordform="One Hundread"},{id=200,wordform="Two Hundread"}}
I want to be able to access the row based on the id to do something like this:
mynum = 100
print ("The value is " .. mytable[mynum].wordform)
The main point here is I want to be able to set the index value so I can predictably retrieve the associated value later as I might do with a java hashmap.
Ideally your table should just use the ID as key:
local mytable = {[100] = {wordform = "One hundred"}, [200] = {wordform = "Two hundred"}}
print("The value is " .. mytable[100].wordform)
If your table is in list form, you can convert it to ID form rather easily:
local mytable_by_id = {}
for _, item in pairs(mytable) do mytable_by_id[item.id] = item end
Using the hash part of a Lua table is definitely preferable over looping over the list entries in linear time as Renshaw's answer suggests (the fact that it's hidden behind a metatable may hide the poor performance and trick the reader into believing a hash indexing operation is taking place here though).
Furthermore, that answer won't even work correctly, as the list part uses integer keys as well; IDs that are valid list part indices would possibly return the wrong element. You'd have to use a function instead of a metatable.
you can use metatable
setmetatable(mytable, {__index = function(tbl, id)
for _, item in pairs(tbl) do
if type(item) == "table" and item.id == id then
return item
end
end
end})
then
mynum = 100
print ("The value is " .. mytable[mynum].wordform) -- The value is One Hundread
I have this table local cookies = {{["name"]=23, ["value"]=333}, {["name"]=222, ["value"]=33233}} and I want to iterate over the subtables to find the one with the correct "name". Here is what I have tried
for _,elm in ipairs(cookies) do
for k,v in ipairs(elm) do
print(k)
if k == "name" and v == 222 then
print(v)
end
end
end
I does show in the outer for loop that it sees to tables, however, it does not even enter the inner for loop - why? How can I find the subtable for which "name" equals a certain value?
ipairs only iterates over the keys 1, 2, 3, ..., so it won't visit the key "name". If you want to visit all keys, use pairs (though be warned the order of iteration is not predictable).
However, for your example you don't need an inner loop at all. You can simple get the name of elm as elm.name:
for _,elm in ipairs(cookies) do
if elm.name == "222" then
print(elm.name, elm.value)
end
end
In fact, if you don't need the ordering or need to support duplicated cookie names, your cookies table could become a dictionary of name => value, allowing you to write this with no loops:
print(cookies["222"]) --> 33233
I'm inserting the value of an variable to a table and want to make sure the action succeeded.
Therefore I want to return the value, but not by the var, but from the table.
Is there a more simple way as iterating trough the table again?
Some way to remember the key of the value in the table, while it's inserted?
function(value)
for _,v in pairs(theTable) do
if v == value then
return --(due the table already contains the value)
end
end
table.insert(theTable, value)
return -- table.[VALUE]
end
local ix = #theTable + 1
theTable[ix] = value
That's pretty much what table.insert is doing:
As a special (and frequent) case, if we call insert without a position, it inserts the element in the last position of the array (and, therefore, moves no elements)
As a sidenote, your function is pretty inefficient; you're doing an O(n) "contains" check, which could be made much better if you created an index of values.
I have a list of indexes I need my users to input, and I need the code to check if any of them are repeated, so it would give an error (they cannot be repeat).
if i only had two indexes it would be simple as :
if indexa == indexb then error() end
but its a fairly long list.
Here's a basic algorithm for detecting repeats.
-- This table is what's known as a set.
local indexes = {}
while true do
local index = getIndexFromUser()
-- Check for end of input.
if not index then
break
end
-- Check for repeats.
if indexes[index] then
error()
end
-- Store index as a key in indexes.
indexes[index] = true
end
In other words, table keys cannot be repeated, so you can simply store any non-nil value in a table under that key. Later (in future iterations of the loop), you can check to see whether that key is nil.
You could put all the indices in a table, use table.sort to sort them, then loop over table items to test if any consecutive items are identical:
indices = {1,6,3,0,3,5} -- will raise error
indices = {1,6,3,0,4,5} -- will not raise error
table.sort(indices)
for i=1, (#indices-1) do
if indices[i] == indices[i+1] then
error('not allowed duplicates')
end
end
In Lua, I can add an entry inside table with table.insert(tableName, XYZ). Is there a way I can add already existing table into table? I mean a directly call rather then traversing and add it.
Thanks
The insert in your example will work fine with whatever contents happen to be inside the XYZ variable (number, string, table, function, etc.).
That will not copy the table though it will insert the actual table. If you want to insert a copy of the table then you need to traverse it and insert the contents.
First: In general, you do not need table.insert to put new entries into tables.
A table in Lua is a collection of key-value pairs; entries can be made like this:
local t = {} --the table
local key= "name"
local value = "Charlie"
t[key] = value --make a new entry (replace an existing value at the same key!)
print(t.name) --> "Charlie"
Note that key can have any type (not just integer/string)!
Very often you will need tables for a simple special case of this: A sequence ("list", "array") of values. For Lua, this means you want a table where all the keys are consecutive integers, and contain all non-nil values. The table.insert function is intended for that special case: It allows you to insert a value at a certain position (or to append it at the end of the sequence if no position is specified):
local t = {"a", "b", "d"} --a sequence containing three strings (t[1] = "a", ...)
table.insert(t, "e") --append "e" to the sequence
table.insert(t, 3, "c") --insert "c" at index 3 (moving values at higher indices)
--print the whole sequence
for i=1,#t do
print(t[i])
end
If I understand what you mean correctly, you want to do this:
local t1 = {1, 2, 3}
local t2 = {4, 5, 6}
some_function(t1, t2)
-- t1 is now {1, 2, 3, 4, 5, 6}
There is indeed no way to do this without iterating t2. Here is a way to write some_function:
local some_function = function(t1, t2)
local n = #t1
for i=1,#t2 do t1[n+i] = t2[i] end
end
No, you must copy the second table's key/value pairs into the first table. Copying the existing values from the second table is what's known as a "shallow copy." The first table will reference the same objects as the second table.
This works under limited circumstances:
local n = #t1
for i=1,#t2 do t1[n+i] = t2[i] end
It does attempt to shift the t2 elements to just beyond the existing t1 elements. That could be a vital requirement but wasn't stated in the question.
It has a few of problems, though:
By using #t1 and #t2, it misses keys that aren't positive integers and can miss keys that are integers greater than a skipped integer key (i.e. never assigned or assigned nil).
It accesses the first table with an indexer so could invoke the __newindex metamethod. That probably wouldn't be desirable when only copying is wanted.
It accesses the second table with an indexer so could invoke the __index metamethod. That wouldn't be desirable when only copying is wanted.
You might think that ipairs could be used if only positive integer keys are wanted but it quits on the first nil value found so could miss even more than #t2 does.
Use pairs instead:
for key, value in pairs(t2) do
rawset( t1, key, value )
end
If you do want to avoid replacing existing t1 values when the keys match or otherwise map t2 keys in some way then that has to be defined in the requirements.
Bottom line: pairs is the way to get all the keys. It effectively does a rawget so it avoids invoking __index. rawset is the way to do a copy without invoking __newindex.