Index values from table into another table - lua

I want to store the values by selecting the keys of a table into another table, for example:
polyline = {color="blue", thickness=2, npoints=4}
stuff = {"polyline.color":[polyline.thickness]}
print(stuff)
Should produce:
blue 2
However, I get the following error:
input:3: '}' expected near ':'

local polyline = {color="blue", thickness=2, npoints=4}
local stuff = {polyline.color, polyline.thickness}
print(table.unpack(stuff))

I believe, You're mixing in some Python syntax. Do you notice using two different (wrong) ways of accessing the values?
I guess, this is what You've meant with your snippet of Lua code:
polyline = {color = "blue", thickness = 2, npoints = 4}
stuff = {[polyline.color] = polyline.thickness}
for key, val in pairs(stuff) do
print(key, val)
end

Related

Lua and Love2D, table in table error

Why isn't this working? I'm trying to put all my object tables in a single table and use a forloop to iterate through each of them and draw. It shows an error message saying: "}" expected near "=" at line 5
function love.load()
solidstatic = {
ground = {x = 0,y = 160,width = 1000,height = 1000},
box = {x = 80,y = 100,width = 15,height = 15}
}
end
function love.draw()
for i,obj in ipairs(solidstatic) do
love.graphics.rectangle("fill",obj[x],obj[y],obj[width],obj[height])
end
end
(edit) solved the error problem, I was running the wrong .lua file. But still, it doesn't draw anything on the screen
Two things.
Firstly, you must use pairs instead of ipairs to list keys that are not numbers.
for i, v in pairs(table) do
...
end
You must also index the variables as a string.
t = {
x = 1
}
t['x'] = 1
-- or
t.x = 1
This is because doing it without quotes would be indexing with the global variable x, which doesn't exist.
You need to use pairs instead of ipairs to iterate over elements in solidstatic as there are no array keys in that table.

Lua search tables using index or value

So if I have a table of colours:
colour["red"] = 1
colour["blue"] = 4
colour["purple"] = 5
and I want to add red to blue, I can easily get the number values of red and blue, but then with the value 5, can I get it to return "purple" without scanning the whole table?
You would need a table with both hash and array part, if colour numbers are unique. For example:
colour["purple"] = 5
colour[5] = "purple"
You can create a little helper function that would facilitate populating the table, such as:
function addColour(coltab, str, val)
coltab[str] = val
coltab[val] = str
end
#W.B.'s answer is good, if you want something more magic you can use this variation using the __newindex metamethod:
local colour = setmetatable({}, {
__newindex = function(self,k,v)
rawset(self,k,v)
rawset(self,v,k)
end
})
colour["red"] = 1
colour["blue"] = 4
colour["purple"] = 5
print(colour["purple"]) -- 5
print(colour[4]) -- blue

Get number of objects by name Corona SDK

I'm trying to see if it's possible to get all the objects with the same name. I'm using the following code to load a bunch of circles on the screen. They all have the same
local myCircle = display.newCircle(30+(yCount*20), 220+(yCount*10), 8)
myCircle.name = "peg"
I would imagine there is a way to do this but I'm not sure where to even look for such a thing.
Thanks
First of all you need a circle array
array = {}
Then when you create a single circle, you should add that circle to the array
array[#array+1] = myCircle
Now here is the find function by spesific name
local function findByName( name )
local resultArray = {}
for i=1, #array do
if array[i].name == name then
resultArray[#resultArray+1] = array[i]
end
end
return resultArray
end
So, at the end, when you call
local tempArray = findByName( "peg" )
you'll get circles named "peg" in tempArray

lua Hashtables, table index is nil?

What I'm currently trying to do is make a table of email addresses (as keys) that hold person_records (as values). Where the person_record holds 6 or so things in it. The problem I'm getting is that when I try to assign the email address as a key to a table it complains and says table index is nil... This is what I have so far:
random_record = split(line, ",")
person_record = {first_name = random_record[1], last_name = random_record[2], email_address = random_record[3], street_address = random_record[4], city = random_record[5], state = random_record[6]}
email_table[person_record.email_address] = person_record
I wrote my own split function that basically takes a line of input and pulls out the 6 comma seperated values and stores them in a table (random_record)
I get an error when I try to say email_table[person_record.email_address] = person_record.
But when I print out person_record.email_address it's NOT nil, it prints out the string I stored in it.. I'm so confused.
function split(str, pat)
local t = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
return t
end
The following code is copy and pasted from your example and runs just fine:
email_table = {}
random_record = {"first", "second", "third"}
person_record = {first_name = random_record[1], last_name = random_record[1], email_address = random_record[1]}
email_table[person_record.email_address] = person_record
So your problem is in your split function.
BTW, Lua doesn't have "hashtables". It simply has "tables" which store key/value pairs. Whether these happen to use hashes or not is an implementation detail.
It looks like you iterating over some lines that have comma-separated data.
Looking at your split function, it stops as soon as there's no more separator (,) symbols in particular line to find. So feeding it anything with less than 3 ,-separated fields (for very common example: an empty line at end of file) will produce a table that doesn't go up to [3]. Addressing any empty table value will return you a nil, so person_record.email_address will be set to nil as well on the 2nd line of your code. Then, when you attempt to use this nil stored in person_record.email_address as an index to email_table in 3rd line, you will get the exact error you've mentioned.

How Lua tables work

I am starting to learn Lua from Programming in Lua (2nd edition)
I didn't understand the following in the book. Its very vaguely explained.
a.) w={x=0,y=0,label="console"}
b.) x={math.sin(0),math.sin(1),math.sin(2)}
c.) w[1]="another field"
d.) x.f=w
e.) print (w["x"])
f.) print (w[1])
g.) print x.f[1]
When I do print(w[1]) after a.), why doesn't it print x=0
What does c.) do?
What is the difference between e.) and print (w.x)?
What is the role of b.) and g.)?
You have to realize that this:
t = {3, 4, "eggplant"}
is the same as this:
t = {}
t[1] = 3
t[2] = 4
t[3] = "eggplant"
And that this:
t = {x = 0, y = 2}
is the same as this:
t = {}
t["x"] = 0
t["y"] = 2
Or this:
t = {}
t.x = 0
t.y = 2
In Lua, tables are not just lists, they are associative arrays.
When you print w[1], then what really matters is line c.) In fact, w[1] is not defined at all until line c.).
There is no difference between e.) and print (w.x).
b.) creates a new table named x which is separate from w.
d.) places a reference to w inside of x. (NOTE: It does not actually make a copy of w, just a reference. If you've ever worked with pointers, it's similar.)
g.) Can be broken up in two parts. First we get x.f which is just another way to refer to w because of line d.). Then we look up the first element of that table, which is "another field" because of line c.)
There's another way of creating keys in in-line table declarations.
x = {["1st key has spaces!"] = 1}
The advantage here is that you can have keys with spaces and any extended ASCII character.
In fact, a key can be literally anything, even an instanced object.
function Example()
--example function
end
x = {[Example] = "A function."}
Any variable or value or data can go into the square brackets to work as a key. The same goes with the value.
Practically, this can replace features like the in keyword in python, as you can index the table by values to check if they are there.
Getting a value at an undefined part of the table will not cause an error. It will just give you nil. The same goes for using undefined variables.
local w = {
--[1] = "another field"; -- will be set this value
--["1"] = nil; -- not save to this place, different with some other language
x = 0;
y = 0;
label = "console";
}
local x = {
math.sin(0);
math.sin(1);
math.sin(2);
}
w[1] = "another field" --
x.f = w
print (w["x"])
-- because x.f = w
-- x.f and w point one talbe address
-- so value of (x.f)[1] and w[1] and x.f[1] is equal
print (w[1])
print ((x.f)[1])
print (x.f[1])
-- print (x.f)[1] this not follows lua syntax
-- only a function's has one param and type of is a string
-- you can use print "xxxx"
-- so you print x.f[1] will occuur error
-- in table you can use any lua internal type 's value to be a key
-- just like
local t_key = {v=123}
local f_key = function () print("f123") end
local t = {}
t[t_key] = 1
t[f_key] = 2
-- then t' key actualy like use t_key/f_key 's handle
-- when you user t[{}] = 123,
-- value 123 related to this no name table {} 's handle

Resources