A better way to assign multiple return values to table keys in Lua - lua

Assume I have a function that returns multiple values. I happen to be working with LÖVE's (Image):getDimensions. This returns two values, which I know to be width,height. I want to assign them to a new table, as an array. I would like named (string) keys. So for instance, I would like to assign the return values of the getDimensions() function to a new table with keys width and height, respectively.
I know the following works...
image = {}
image.data = love.graphics.newImage('myimage.png')
image.size = {}
image.size.width, image.size.height = image.data:getDimensions()
I'm wondering if there is any sort of syntactic sugar I can use, or any use of standard library functions that will allow a syntax more along the lines of...
image.size = { width, height = image.data:getDimensions() }
I know the above line does not work, along with many variations I've tried, including various attempts to use unpack(). I'm new to Lua (~2 days in now), so maybe there is another standard function or best practice that I'm unaware of that will associate a table of keys to an array-like table. Thanks!

You can write your own functions:
local function set_fields(tab, fields, ...)
-- fields is an array of field names
-- (use empty string to skip value at corresponging position)
local values = {...}
for k, field in ipairs(fields) do
if field ~= "" then
tab[field] = values[k]
end
end
return tab
end
local function get_fields(tab, fields)
local values = {}
for k, field in ipairs(fields) do
values[k] = tab[field]
end
return (table.unpack or unpack)(values, 1, #fields)
end
Usage example #1:
image.size = set_fields({}, {"width", "height"}, image.data:getDimensions())
Usage example #2:
Swap the values on-the-fly!
local function get_weekdays()
return "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
end
-- we want to save returned values in different order
local weekdays = set_fields({}, {7,1,2,3,4,5,6}, get_weekdays())
-- now weekdays contains {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}
Usage example #3:
local function get_coords_x_y_z()
return 111, 222, 333 -- x, y, z of the point
end
-- we want to get the projection of the point on the ground plane
local projection = {y = 0}
-- projection.y will be preserved, projection.x and projection.z will be modified
set_fields(projection, {"x", "", "z"}, get_coords_x_y_z())
-- now projection contains {x = 111, y = 0, z = 333}
Usage example #4:
If require("some_module") returns a module with plenty of functions inside, but you need only a few of them:
local bnot, band, bor = get_fields(require("bit"), {"bnot", "band", "bor"})

Using a class construct, I have come up with the following...
Size = {}
Size.mt = {}
Size.prototype = { width = 0, height = 0 }
function Size.new (dimensions)
local size = setmetatable({}, Size.mt)
if dimensions ~= nil and type(dimensions) == 'table' then
for k,v in pairs(dimensions) do
size[k] = v
end
end
return size
end
Size.mt.__index = function (t, k)
if k == 'width' or k == 'height' then
rawset(t, k, Size.prototype[k])
return t[k]
else
return nil
end
end
Size.mt.__newindex = function (t, k, v)
if k == 1 or k == 'width' then
rawset(t, 'width', v)
elseif k == 2 or k == 'height' then
rawset(t, 'height', v)
end
end
Then I can initialize a Size object in a number of ways
Using multiple return values:
image.size = Size.new{image.data:getDimensions()}
image.size = Size.new(table.pack(image.data:getDimensions())
Using default values:
image.size = Size.new()
image.size = Size.new{}
image.size = Size.new({})
Using mixed array and hash tables:
image.size = Size.new({height=20, width=30})
image.size = Size.new({height=20, 30})
There are pros and cons to this approach vs. Egor's (utility function), which is what I was considering doing if there wasn't a simple syntax trick or an existing function that I was unaware of.
Pros:
(personal) learning experience with OO constructs in Lua
I can limit the number of actual keys on the table, while allowing 'synonyms' for those keys to be added by expanding the accepted values in the if/else logic of __index and __newindex
Explicit definition of fields in the table, without needing to worry about syncing a table of keys with a table of values (as with a general purpose utility function)
Cons
would need to repeat this pattern for each data structure where I wanted this behavior
costly, a lot of overhead for what amounts to a very small difference to the consumer
I'm sure I can make this approach more robust in time, but I would appreciate any feedback.

Related

Loop through matrix

I'm creating a simple matrix like follows:
for x = 0, 50 do
current_level[x] = {}
for y = 0, 50 do
current_level[x][y] = grabTile();
end
end
After that i try to read it, but somehow the x is now a object not a number, while y seems perfectly fine!
How i try reading it:
for x,value in pairs(self.map) do
if value == ni then print("none"); return;end;
for y,object in pairs(value) do
if object == ni then print("none"); return;end;
object:render(x,y); -- Here x is an object
end
end
I'm new to working with lua, so i might be doing something obvious terribly wrong.
How would i make this work?
What i get for x is something like: table: 0x07c8d530
This value stays the same along the complete iteration
object:render(x,y); -- Here x is an object
This line is using colon syntax. It is a syntactic sugar for object.render(object,x,y) call.
So your render() function must have the first self argument declared either explicitly as function render(self, x, y) or implicitly with another syntactic sugar for definition: function object:render(x,y).
Unrelated hint. The first loop will be faster/smaller if transformed to:
for x = 0, 50 do
local row = {}
for y = 0, 50 do
row[y] = grabTile();
end
current_level[x] = row
end

How to initialize table size in lua

What is the most efficient way to convert number to table? Or is it possible to make a table without loops?
local t = 10 -- given number
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} -- result
Update: the t variable is mutable number and I want to for each the value.
t = 3
function foreach(f, t)
for i, v in ipairs(t) do
f(v)
end
end
foreach(print, t)
1
2
3
I need a just the quickest way of new Array(n) in Lua. Or doesn't make any sense?
Maybe you don't know how to answer #Sebastian's question. Here are a few alternatives to get you thinking.
Since your table has only computed elements, you could omit the storage and just perform the calculation on every read access (index operation).
local function newArray(size)
local t = {}
setmetatable(t, {
__index = function (_, i)
return i >= 1 and i <= size and i or nil end})
return t
end
t10 = newArray(10)
for i = 0, 11 do -- ipairs won't work as expected with such a table
print(i, t10[i])
end
t10[2] = "stored values override __index"
print(t10[2])
Of course, you could also replace the table with just an identity function that returns the value, or even just an identity expression. But, maybe you have an unexpressed requirement for a table or you need ipairs to iterate over the sequence.
Speaking of iterators,
local function seq_itor(first, last)
local i = first - 1
return function ()
i = i + 1
if i <= last then return i end
end
end
for i in seq_itor(1, 10) do
print(i)
end
The simplest way to do that would be to define a function:
function newArray(size)
local t = {}
for i = 1, size do
t[i] = i
end
return t
end

Lua: set of k-dimensional points

I want to make sure that kD points which I generate randomly don't happen to be identical. To test this efficiently, I want to use a set (at least that's what I would do in C++).
I know that in Lua tables can be used as sets by inserting the object as value with any non-nil key (typically just true or an integer for multisets).
But the problem is that tables in Lua are by default just compared w.r.t. their address, which is of course different even if all the vector components (in my case) are equal.
So I thought I'd implement a equal and/or less than metamethod for my points. But this didn't work (see code below). Can anybody help?
local k = 3
local mt = {}
mt.__eq = function( a, b )
for dim = 1, k do
if a[dim] ~= b[dim] then return false end
end
return true
end
mt.__lt = function( a, b )
for dim = 1, k do
if a[dim] < b[dim] then
return true
elseif a[dim] > b[dim] then
return false
end
end
return false -- equal
end
local set = {}
local p1 = { 1, 2, 3 }
setmetatable( p1, mt )
set[p1] = true
local p2 = { 1, 2, 3 }
setmetatable( p2, mt )
set[p2] = true -- should just overwrite the old value
print( "p1 == p2 --> "..tostring( p1 == p2 ) )
print( "p1 < p2 --> "..tostring( p1 < p2 ) )
local setSize = 0
for _, _ in pairs( set ) do
setSize = setSize + 1
end
print( "Size of the set: "..setSize )
Lua has no facilities for allowing what you're trying to do. That is, there's no metamethod trickery that can make two different pieces of userdata or two different tables map to the same index to the table indexing system.
You'll have to do this manually. You can effectively write your own set, by keeping a list of vectors sorted. table.sort can do the job, since you already have an appropriate __lt metamethod.
If anyone is interested: I have come up with another work-around that has worked for me.
One can use a set of x-coordinates and instead of associating the set items with just "true" or "1", the respective values are sets themselves (of y-coordinates); and so on.
This leads to a tree-like structure where the path to each leaf represents a point (sequence of coordinates) and points with the same first coordinates have common parent nodes. Also all points are unique.

Lua: Creating tables

I'm attempting to use a table as a means to do two things at once. For example:
s = passengers -- user input
t = {[3] = car, [7] = bus, [24] = plane, [45] = train}
for k,v in ipairs t do
if s = k then
z = v * 10 -- cost per person
end
end
Now this is extremely basic for what I'm trying to do. I have a list of about 12 items that each have their own number. I want to know if I can do what I did above with the table and provide each of the 12 items with their own key value and then use that ? This key value would represent each items particular, unique number. Also, can I then use that key's value in a later equation, such as above?
If your keys are unique, your data structure. The point of a table key is direct access to the corresponding value.
This has the same effect as your loop:
local v = t[s] -- value for s or nil if s is not a key
if v != nil then
z = v * 10
end
(Or, more exactly the same: local v = rawget(t,s) to account for cases where t has an __index metamethod.)
If we can assume that v will never be false (which would cause an error at false * 10) then it can be written more naturally (which skips that error):
local v = t[s]
if v then
z = v * 10
end

Concatenation of tables in Lua

ORIGINAL POST
Given that there is no built in function in Lua, I am in search of a function that allows me to append tables together. I have googled quite a bit and have tried every solutions I stumbled across but none seem to work properly.
The scenario goes like this: I am using Lua embeded in an application. An internal command of the application returns a list of values in the form of a table.
What I am trying to do is call that command recursively in a loop and append the returned values, again in the form of a table, to the table from previous iterations.
EDIT
For those who come across this post in the future, please note what #gimf posted. Since Tables in Lua are as much like arrays than anything else (even in a list context), there is no real correct way to append one table to another. The closest concept is merging of tables. Please see the post, "Lua - merge tables?" for help in that regard.
Overcomplicated answers much?
Here is my implementation:
function TableConcat(t1,t2)
for i=1,#t2 do
t1[#t1+1] = t2[i]
end
return t1
end
If you want to concatenate an existing table to a new one, this is the most concise way to do it:
local t = {3, 4, 5}
local concatenation = {1, 2, table.unpack(t)}
Although I'm not sure how good this is performance-wise.
And one more way:
for _,v in ipairs(t2) do
table.insert(t1, v)
end
It seems to me the most readable one - it iterates over the 2nd table and appends its values to the 1st one, end of story. Curious how it fares in speed to the explicit indexing [] above
A simple way to do what you want:
local t1 = {1, 2, 3, 4, 5}
local t2 = {6, 7, 8, 9, 10}
local t3 = {unpack(t1)}
for I = 1,#t2 do
t3[#t1+I] = t2[I]
end
To add two tables together do this
ii=0
for i=#firsttable, #secondtable+#firsttable do
ii=ii+1
firsttable[i]=secondtable[ii]
end
use the first table as the variable you wanted to add as code adds the second one on to the end of the first table in order.
i is the start number of the table or list.
#secondtable+#firsttable is what to end at.
It starts at the end of the first table you want to add to, and ends at the end of the second table in a for loop so it works with any size table or list.
In general the notion of concatenating arbitrary tables does not make sense in Lua because a single key can only have one value.
There are special cases in which concatenation does make sense. One such is for tables containing simple arrays, which might be the natural result of a function intended to return a list of results.
In that case, you can write:
-- return a new array containing the concatenation of all of its
-- parameters. Scaler parameters are included in place, and array
-- parameters have their values shallow-copied to the final array.
-- Note that userdata and function values are treated as scalar.
function array_concat(...)
local t = {}
for n = 1,select("#",...) do
local arg = select(n,...)
if type(arg)=="table" then
for _,v in ipairs(arg) do
t[#t+1] = v
end
else
t[#t+1] = arg
end
end
return t
end
This is a shallow copy, and makes no attempt to find out if a userdata or function value is a container or object of some kind that might need different treatment.
An alternative implementation might modify the first argument rather than creating a new table. This would save the cost of copying, and make array_concat different from the .. operator on strings.
Edit: As observed in a comment by Joseph Kingry, I failed to properly extract the actual value of each argument from .... I also failed to return the merged table from the function at all. That's what I get for coding in the answer box and not testing the code at all.
If you want to merge two tables, but need a deep copy of the result table, for whatever reason, use the merge from another SO question on merging tables plus some deep copy code from lua-users.
(edit
Well, maybe you can edit your question to provide a minimal example... If you mean that a table
{ a = 1, b = 2 }
concatenated with another table
{ a = 5, b = 10 }
should result in
{ a = 1, b = 2, a = 5, b = 10 }
then you're out of luck. Keys are unique.
It seems you want to have a list of pairs, like { { a, 1 }, { b, 2 }, { a, 5 }, { b, 10 } }. You could also use a final structure like { a = { 1, 5 }, b = { 2, 10 } }, depending on your application.
But the simple of notion of "concatenating" tables does not make sense with Lua tables.
)
Here is an implementation I've done similar to RBerteig's above, but using the hidden parameter arg which is available when a function receives a variable number of arguments. Personally, I think this is more readable vs the select syntax.
function array_concat(...)
local t = {}
for i = 1, arg.n do
local array = arg[i]
if (type(array) == "table") then
for j = 1, #array do
t[#t+1] = array[j]
end
else
t[#t+1] = array
end
end
return t
end
Here is my implementation to concatenate a set of pure-integer-indexing tables, FYI.
define a function to concatenate two tables, concat_2tables
another recursive function concatenateTables: split the table list by unpack, and call concat_2tables to concatenate table1 and restTableList
t1 = {1, 2, 3}
t2 = {4, 5}
t3 = {6}
concat_2tables = function(table1, table2)
len = table.getn(table1)
for key, val in pairs(table2)do
table1[key+len] = val
end
return table1
end
concatenateTables = function( tableList )
if tableList==nil then
return nil
elseif table.getn(tableList) == 1 then
return tableList[1]
else
table1 = tableList[1]
restTableList = {unpack(tableList, 2)}
return concat_2tables(table1, concatenateTables(restTableList))
end
end
tt = {t1, t2, t3}
t = concatenateTables(tt)
-- Lua 5.1+
function TableAppend(t1, t2)
-- A numeric for loop is faster than pairs, but it only gets the sequential part of t2
for i = 1, #t2 do
t1[#t1 + 1] = t2[i] -- this is slightly faster than table.insert
end
-- This loop gets the non-sequential part (e.g. ['a'] = 1), if it exists
local k, v = next(t2, #t2 ~= 0 and #t2 or nil)
while k do
t1[k] = v -- if index k already exists in t1 then it will be overwritten
k, v = next(t2, k)
end
end
EDIT
Here's a better solution, the other one tended to overwrite numeric keys, the usage is still the same:
function merge(...)
local temp = {}
local index = 1
local result = {}
math.randomseed(os.time())
for i, tbl in ipairs({ ... }) do
for k, v in pairs(tbl) do
if type(k) == 'number' then
-- randomize numeric keys
k = math.random() * i * k
end
temp[k] = v
end
end
for k, v in pairs(temp) do
if type(k) == "number" then
-- Sort numeric keys into order
if result[index] then
index = index + 1
end
k = index
end
result[k] = v
end
return result
end
ORIGINAL
A wee bit late to the game, but this seems to work for me:
function concat(...)
local result = {}
for i, tbl in ipairs({...}) do
for k, v in pairs(tbl) do
if type(k) ~= "number" then
result[k] = v
else
result[i] = v
end
end
end
return result
end
It might be a bit overcomplicated, but it takes an infinite amount of arguments, and works for both key-value pairs and regular "arrays" (numbers as keys). Here's an example
I like the simplicity in #Weeve Ferrelaine answer, but mutations may cause many issues and in general, are not desirable.
Version with NO MUTATION.
---#param t1 {}
---#param t2 {}
function TableConcat(t1,t2)
local tOut = {}
for i = 1, #t1 do
tOut[i] = t1[i]
end
for i = #t1, #t1 + #t2 do
tOut[i] = t2[i]
end
return tOut
end
Original implementation, that's mutating t1.
function TableConcat(t1,t2)
for i=1,#t2 do
t1[#t1+1] = t2[i]
end
return t1
end
Use table.concat:
http://lua-users.org/wiki/TableLibraryTutorial
> = table.concat({ 1, 2, "three", 4, "five" })
12three4five
> = table.concat({ 1, 2, "three", 4, "five" }, ", ")
1, 2, three, 4, five
> = table.concat({ 1, 2, "three", 4, "five" }, ", ", 2)
2, three, 4, five
> = table.concat({ 1, 2, "three", 4, "five" }, ", ", 2, 4)
2, three, 4

Resources