Currently I'm stuck on this:
t = {['79402d'] = {'-5.4','5','1.6'}, ['5813g1'] = {'3','0.15','18'}}
Now i need to loop through this table to check if name == t[1], but how can i do so?
I tried doing something like: for i=1,#t,1 do print(t[i]) but it doesn't seem to work.
I hope you can help me guys ;)
Not sure why it didn't worked first time but i solved my problem with:
for a,b in pairs(t) do
print(a, b[1], b[2], b[3])
end
Please note that the length operator # will give you the correct number of elements in a table only in a special case. in your case #t will return 0, hence your for loop does nothing.
Please refer to https://www.lua.org/manual/5.3/manual.html Section 3.4.7 – The Length Operator for details on how to use the lenght operator.
For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. so #t will be zero if you have no t[1] or n-1 if t[n] is the first nil value in your table starting from t[1].
As you have no t[1] but only a t['79402d'] and a t['5813g1'] your for loop indexing t[i] would not work anyway.
Please read 3.4.9 – Table Constructors on how table construction works.
t = {"hello", "world"}
is the same as
t = {}
t[1] = "hello"
t[2] = "world"
(here t[1] is "hello" and #t is 2
whereas t = {['key1'] = "hello", ['key2'] = "world"}
equals
t = {}
t['key1'] = "hello"
t['key2'] = "world"
so t[1] here is nil and #t is 0
# operator returns lenght of array part of the table. Your table is not an array (i.e. a table with non-nil values from index 1 to a given n). Because of that your loop is not iterating any elements.
Use pairs to iterate over all keys in the table regardless of what they are.
Related
I have this table in lua:
local values={"a", "b", "c"}
is there a way to return the index of the table if a variable equals one the table entries?
say
local onevalue = "a"
how can I get the index of "a" or onevalue in the table without iterating all values?
There is no way to do that without iterating.
If you find yourself needing to do this frequently, consider building an inverse index:
local index={}
for k,v in pairs(values) do
index[v]=k
end
return index["a"]
The accepted answer works, but there is room for improvement:
Why not exit the loop once the element is found? And why bother copying the entire source table into a new throwaway table?
Usually, this sort of function returns the first array index with that value, not an arbitrary array index with that value.
For arrays:
-- Return the first index with the given value (or nil if not found).
function indexOf(array, value)
for i, v in ipairs(array) do
if v == value then
return i
end
end
return nil
end
print(indexOf({'b', 'a', 'a'}, 'a')) -- 2
For hash tables:
-- Return a key with the given value (or nil if not found). If there are
-- multiple keys with that value, the particular key returned is arbitrary.
function keyOf(tbl, value)
for k, v in pairs(tbl) do
if v == value then
return k
end
end
return nil
end
print(keyOf({ a = 1, b = 2 }, 2)) -- 'b'
If you use Lua for Roblox development, you can use the table.find method:
print(table.find({'a', 'b', 'c'}, 'b'))
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.
I am a hobbyest making mods in TableTop Simulator using LUA and have a question that I can not seam to work out.
I have a number of "objects" which is a table in TTS that contains various data for those objects. For example.. obj.position = {x,y,z}... and can be accessed at the axis level as well.
obj.position = {5,10,15} -- x,y,z
obj.position.x == 5
This is an example. The makers of TTS have made it so you can access all the parts like that. So I can acess the object.. and then its various parts. There is a heap, like name, mesh, difuse and a ton more. roations{x,y,z} etc etc
Anyway. I have a table of objects... and would like to order those objects based on the positional data of the x axis.. so highest to lowest. So if I have a table and obj1 in that table is x=3 and obj2 is x=1 and obj3 = x=2 it would be sorted as obj2,obj3,obj1
Pseudo code:
tableOfObjects = {obj1,obj2,obj3}
--[[
tableOfObjectsp[1] == obj1
tableOfObjectsp[2] == obj2
tableOfObjectsp[3] == obj3
tableOfObjectsp[1].position.x == 3
tableOfObjectsp[2].position.x == 1
tableOfObjectsp[4].position.x == 2
--]]
---After Sort it would look this list
tableOfObjects = {obj1,obj3,obj2}
--[[
tableOfObjectsp[1] == obj1
tableOfObjectsp[2] == obj3
tableOfObjectsp[3] == obj2
tableOfObjectsp[1].position.x == 3
tableOfObjectsp[2].position.x == 2
tableOfObjectsp[3].position.x == 1
--]]
I hope I am making sense. I am self taught in the last few months!
So basically I have a table of objects and want to sort the objects in that table based on a single value attached to each individual object in the table. In this case the obj.position.x
Thanks!
You need table.sort. The first argument is the table to sort, the second is a function to compare items.
Example:
t = {
{str = 42, dex = 10, wis = 100},
{str = 18, dex = 30, wis = 5}
}
table.sort(t, function (k1, k2)
return k1.str < k2.str
end)
This article has more information
table.sort(tableOfObjects, function(a, b) return a.position.x > b.position.x end)
This line will sort your table tableOfObjects in descending order by the x-coordinate.
To reverse order, replace > by <.
From the Lua reference manual:
table.sort (list [, comp])
Sorts list elements in a given order, in-place, from list[1] to
list[#list]. If comp is given, then it must be a function that
receives two list elements and returns true when the first element
must come before the second in the final order (so that, after the
sort, i < j implies not comp(list[j],list[i])). If comp is not given,
then the standard Lua operator < is used instead.
Note that the comp function must define a strict partial order over
the elements in the list; that is, it must be asymmetric and
transitive. Otherwise, no valid sort may be possible.
The sort algorithm is not stable: elements considered equal by the
given order may have their relative positions changed by the sort.
So in other words table.sort will sort a table in ascending order by its values.
If you want to order descending or by something other than the table value (like the x-coordinate of your table value's position in your case) you have to provide a function that tells Lua which element will come first.
you can create a function that handles this exact thing:
local function fix_table(t)
local x_data = {};
local inds = {};
local rt = {};
for i = 1, #t do
x_data[#x_data + 1] = t[i].position.x;
inds[t[i].position.x] = t[i];
end
local min_index = math.min(table.unpack(x_data));
local max_index = math.max(table.unpack(x_data));
for i = min_index, max_index do
if inds[i] ~= nil then
rt[#rt + 1] = inds[i];
end
end
return rt;
end
local mytable = {obj1, obj2, obj3};
mytable = fix_table(mytable);
fix_table first takes in every x value inside of the given table, and also places a new index inside the table inds according to each x value (so that they will be ordered from least to greatest), then it gets the smallest value in the x_data array table, which is used to traverse the inds table in order. fix_table checks to make sure that inds[i] is not equal to nil before it increases the size of the return table rt so that every value in rt is ordered from greatest to least, starting at index 1, and ending at index #rt, finally rt is returned.
I hope this helped.
Lets say that I have a dictionary in Lua (i.e. a Lua table that contains indexes of type string) like so:
local my_dictionary = {a = 123; b = 321; c = 456; d = 654};
What I am trying to do is create an iterator function that can iterate over a table even if its indexes are of type string; kind of like pairs, however whenever I try to call next() to get the next index,value it will only return the index,value if the index is of type int. An idea I had was maybe to call (index):byte(1, -1) and add up the tuple of ints, and use that as a sort of pretend index, just to keep track of the indexes, but I do not think that would work with next. Here is basically what I have so far:
local function each(list)
if #list > 0 then
local function my_itr(lst, ind)
return next(lst, ind);
end
return my_itr, List, 0;
end
return function() end, nil, nil;
end
this only works for a table with int indexes (an array table), so I was wondering if anyone could help me out.
Thanks.
Edit: To make this less vague here is an example piece of code of what I am trying to accomplish:
local mytable = {a = 123; b = 321; 3, 2, 1, c = "bca"};
for i,v in each(mytable) do
print(i,v);
end
what it should output:
>a 123
>b 321
>1 3
>2 2
>3 1
>c bca
The output would not have to be in exact order.
It should work exactly as you want it to with a couple of tweaks: fix typo in List and pass nil instead of 0:
local function each(list)
local function my_itr(lst, ind)
return next(lst, ind)
end
return my_itr, list, nil
end
local mytable = {a = 123; b = 321; 3, 2, 1, c = "bca"}
for i,v in each(mytable) do
print(i,v)
end
This prints the following for me, which is what you'd need:
1 3
2 2
3 1
a 123
b 321
c bca
You can achieve this very behavior by using pairs. Don't confuse it with ipairs though - these are two different table traversal functions!
While ipairs only traverses integer keys of the table (usually it also stops at the first non-existent integer key), pairs traverses all key-value pairs in the table.
So, by writing
local mytable = {a = 123; b = 321; 3, 2, 1, c = "bca"};
for i, v in pairs(mytable) do
print(i, v);
end
You'll get all key-value pairs printed, in some random order. Here's the demo.
As a sidenote, there's no such thing as 'dictionary' in Lua - all associative arrays are referred to as 'tables'.
Let's suppose I want to store a list of element. Including some nil values. The position of the values is significant, and I need to represent the absence of a value in the list at a given position.
Here is a problem:
a = {1,2,3,nil,4}
for k,v in ipairs(a) do
print(k,v)
end
print(a[4])
print(a[5])
The for loop will only print elements 1,2 and 3. It stops at nil. The first print statement prints nil, but I'm not sure if it is actually stored in the table or not. (Who knows?) The second print statement prints 4 - as expected.
So here is the question: how to represent a list of elements in a table, and iterate through them efficiently? Given the conditions above, e.g. the position is significant, and some of the positions are "empty". In other words: have no value, but the absence of that value at that position has a meaning.
This is module "null.lua"
local function null(...)
local t, n = {...}, select('#', ...)
for k = 1, n do
local v = t[k]
if v == null then t[k] = nil
elseif v == nil then t[k] = null
end
end
return (table.unpack or unpack)(t, 1, n)
end
_G.null = null
Use null() as encoder and decoder
require("null")
a = {null(1,2,3,nil,4)}
-- the same could be done element-by-element
-- a = {null(1),null(2),null(3),null(nil),null(4)}
for k,v in ipairs(a) do
v = null(v)
print(k,v)
end
print(null(a[4]))
print(null(a[5]))
Lua tables can be used to create any Abstract Data Structure, in your case you indicated that you want a "list". A Lua table is a data structure that combines numeric index based access with key:value access.
Based on your example, you are using the numeric index feature of tables that let you iterate (with ipairs()) through those values. You will not be able to put nil into the table since the numeric index stops at the first nil entry. The remaining values in the table are stored as key:value pairs.
There are several work-arounds, but it depends on why you want a nil in the list. The simplest approach is to use the string "nil" rather than the native data type nil.
a = {1, 2, 3, "nil", 4}
for k,v in ipairs(a) do
print(k,v)
end
The result of this code is:
1 1
2 2
3 3
4 nil
5 4
Because of the way Lua implements strings, there is not a performance penalty for comparing to the string "nil" versus comparing to the native type nil.
The issue of "holes" (caused by nil) in an array are discussed in Programming in Lua, Chapter 5 Tables. Roberto Ierusalimschy recommendation is to track the size of the array to avoid problems with holes.
The following code shows an Object Oriented approach to tracking the size of the list. There are many possible variations on this theme.
function makeList(...)
local list = table.pack(...)
list.length =
function(self) return self.n
end
list.append =
function(self, value)
self.n = self.n + 1
self[self.n] = value
end
list.print =
function(self)
for i = 1, self.n do print(i, self[i]) end
end
return list
end
a = makeList(1, 2, 3, nil, 4)
a:append(5)
a:print()
print(a:length())
The result is:
1 1
2 2
3 3
4 nil
5 4
6 5
6
Note that the function table.pack creates a field 'n' which contains the correct number of items even when 'nil' is present. See PIL chapter 6.2, Variadic Functions for a complete explanation.
Don't just hack something together, write your own datastructure for this. If you "overload" ipairs (by writing an appropriate iterator) you can use it as a table:
function create(...)
local t = table.pack(...)
local self = {
num = t.n,
elements = { ... }
}
return self
end
function elements(t)
local f = function(s, i)
i = i + 1
if i <= s.num then
return i, s.elements[i]
end
end
return f, t, 0
end
local seq = create(1, 2, nil, 3)
print(seq.num)
for i, e in elements(seq) do
print(i, e)
end
-- results:
-- 4
-- 1 1
-- 2 2
-- 3 nil
-- 4 3
You could know define a metatable for this structure and have it use its own ipairs, so you don't even have to change the name.
Well, you can't store nil in the table without issues.
The most simple solution here would be to introduce your own unique value.
local mynil = {} -- every new table is unique!
a = {1,2,3,mynil,4}
for k,v in ipairs(a) do
if (v == mynil) then
v = nil
end
print(k,v)
end
No more issues with "nil" string that might be stored in the table as well, the minor issue is one more comparison. ipairs or any other iterator will show that the key with mynil value exists. That means you can separate mynil key existence with missing key =nil.
P.S. If you want to shift your list, you may consider table.remove(list, key) function.
The answer to this is rather simple, and these "workaround a" suggested is definitely overkill. Just keep track of the number of items in your table whenever it's changed (note: do not use #, you have too keep track manually to deal with nil values) and use a numeric for loop to iterate over it.