Lua iterator to array - lua

In Lua parlance, is there any syntactic sugar for turning an iterator function into an array (repeated invocations with results stored in ascending indices), perhaps something in the standard library ?
I'm tokenizing a string belonging to a protocol and need to to have positional access to elements at the start of the string, and the end of the string is a variant collection.
The code (specific to my use-case) is as follows, I find it hard to believe that it isn't in the standard library :d
local array_tokenise = function (line)
local i = 1;
local array = {};
for item in string.gmatch(line,"%w+") do
array[i] = item;
i = i +1
end
return array
end

There's no standard library function for it. But really, it's pretty trivial to write:
function BuildArray(...)
local arr = {}
for v in ... do
arr[#arr + 1] = v
end
return arr
end
local myArr = BuildArray(<iterator function call>)
This will only work if your iterator function returns single elements. If it returns multiple elements, you'd have to do something different.

As Nicol Bolas said, there is no standard library function that performs the action you desire.
Here is a utility function that extends the table library:
function table.build(build_fn, iterator_fn, state, ...)
build_fn = (
build_fn
or function(arg)
return arg
end
)
local res, res_i = {}, 1
local vars = {...}
while true do
vars = {iterator_fn(state, vars[1])}
if vars[1] == nil then break end
--build_fn(unpack(vars)) -- see https://web.archive.org/web/20120708033619/http://trac.caspring.org/wiki/LuaPerformance : TEST 3
res[res_i] = build_fn(vars)
res_i = res_i+1
end
return res
end
Here is some example code demonstrating usage:
require"stringify"
local t1 = {4, 5, 6, {"crazy cake!"}}
local t2 = {a = "x", b = "y", c = "z"}
print(stringify(table.build(nil, pairs(t1))))
print(stringify(table.build(nil, pairs(t2))))
print(stringify(table.build(
function(arg) -- arg[1] = k, arg[2] = v
return tostring(arg[1]).." = "..tostring(arg[2])
end
, pairs(t1)
)))
local poetry = [[
Roses are red, violets are blue.
I like trains, and so do you!
By the way, oranges are orange.
Also! Geez, I almost forgot...
Lemons are yellow.
]]
print(stringify(table.build(
function(arg) -- arg[1] == plant, arg[2] == colour
return (
string.upper(string.sub(arg[1], 1, 1))..string.lower(string.sub(arg[1], 2))
.. " is "
.. string.upper(arg[2]).."!"
)
end
, string.gmatch(poetry, "(%a+)s are (%a+)")
)))
Output:
{
[1] = {
[1] = 1,
[2] = 4,
},
[2] = {
[1] = 2,
[2] = 5,
},
[3] = {
[1] = 3,
[2] = 6,
},
[4] = {
[1] = 4,
[2] = {
[1] = "crazy cake!",
},
},
}
{
[1] = {
[1] = "a",
[2] = "x",
},
[2] = {
[1] = "c",
[2] = "z",
},
[3] = {
[1] = "b",
[2] = "y",
},
}
{
[1] = "1 = 4",
[2] = "2 = 5",
[3] = "3 = 6",
[4] = "4 = table: 00450BE8",
}
{
[1] = "Rose is RED!",
[2] = "Violet is BLUE!",
[3] = "Orange is ORANGE!",
[4] = "Lemon is YELLOW!",
}
stringify.lua can be found here

if you are just looking to auto-increment the table key for each data element, you can use table.insert(collection, item) - this will append the item to the collection and sets the key to the collection count + 1

Related

How to combine two lua tables and maintain their ordering?

Given
local t1 = {
["foo"] = "val1",
["bar"] = "val2",
["baz"] = "val3",
}
local t2 = {
["foo1"] = "val4",
["bar1"] = "val5",
["baz1"] = "val6",
}
Id like to get result
local t3 = {
["foo"] = "val1",
["bar"] = "val2",
["baz"] = "val3",
["foo1"] = "val4",
["bar1"] = "val5",
["baz1"] = "val6",
}
I have been attempting various ways for around a day now, using other questions provided here, and still am unsure of where things are going wrong or how to handle it. The tables vs arrays in lua is a bit hard to grasp. Thanks for any help :D
AFAIK, if the hash part of a table is used, it does not preserve the order. There is a very simple way to highlight this.
t1 = {
["foo"] = "val1",
["bar"] = "val2",
["baz"] = "val3",
}
for k,v in pairs(t1) do
print(k, v)
end
On my computer, the order is not preserved:
foo val1
baz val3
bar val2
If the order is important, it is required to use an array.
One (convoluted) way to do it would be the following code. Obviously, I am not aware of the given requirements, so this code might not be the most straight-forward.
t1 = {
{ foo = "val1" }, -- Element t1[1]
{ bar = "val2" }, -- Element t1[2]
{ baz = "val3" } -- Element t1[3]
}
t2 = {
{ foo1 = "val4" }, -- Element t2[1]
{ bar1 = "val5" }, -- Element t2[2]
{ baz1 = "val6" } -- Element t2[3]
}
function merge (t1, t2)
local new_table = {}
-- Copy all the items from the first table
for index = 1, #t1 do
new_table[#new_table+1] = t1[index]
end
-- Copy all the items from the second table
for index = 1, #t2 do
new_table[#new_table+1] = t2[index]
end
-- return the new table
return new_table
end
for k,v in pairs(merge(t1,t2)) do
local subtable = v
for k,v in pairs(subtable) do
print(k,v)
end
end
This would print the following:
foo val1
bar val2
baz val3
foo1 val4
bar1 val5
baz1 val6

How can I merge two tables like this? - Lua

I have these tables set like this
local tableone = {["Gold"] = 10, ["Gem"] = 5}
local tabletwo = {["Level"] = 1}
This is the code for merging
local test = {tableone, tabletwo}
print(test)
But if I try to merge the tables then the output is like this
[1] = {
["Gold"] = 10,
["Gem"] = 5
},
[2] = {
["Level"] = 1
}
And I would like to have the output like this
[1] = {
["Gold"] = 10,
["Gem"] = 5,
["Level"] = 1
}
Is this possible?
Sorry if I'm not that good at explaining.
You can do this with a simple nested loop.
local function merge(...)
local result <const> = {}
-- For each source table
for _, t in ipairs{...} do
-- For each pair in t
for k, v in pairs(t) do
result[k] = v
end
end
return result
end
local t <const> = {merge(tableone, tabletwo)}
I put the result in a table constructor due to the [1] in the question.

lua open a file with a table and change certain values

I have a file with a large table. Need to open it, get certain values and replace other values with the new ones. With this example, Females and Males Classroom a and b must equal Teachers Classroom a and b.
Read as much as I can on IO, but I cannot seem to get this to work correctly. Any help will be greatly appreciated.
--file with sample data to test, original file has 7000+lines
theData =
{
["theSchool"] =
{
["theTeachers"] =
{
["theClassroom"] =
{
["a"] = 001,
["b"] = 002,
},
},
["theFemales"] =
{
["theClassroom"] =
{
["a"] = 005,
["b"] = 010,
},
},
["theMales"] =
{
["theClassroom"] =
{
["a"] = 012,
["b"] = 014,
},
},
},
}
Then the function file looks like this
local file = io.open(filepath,'r')
local newCa = '["a"] = '..theData.theSchool.theTeachers.theClassroom.a
local newCb = '["b"] = '..theData.theSchool.theTeachers.theClassroom.b
local replaceFa = '["a"] = '..tostring(theData.theSchool.theFemales.theClassroom.a)
local replaceFb = '["b"] = '..tostring(theData.theSchool.theFemales.theClassroom.b)
local replaceMa = '["a"] = '..tostring(theData.theSchool.theMales.theClassroom.a)
local replaceMb = '["b"] = '..tostring(theData.theSchool.theMales.theClassroom.b)
file:close()
--Will it work?
print("Original Values:")
print(newCa)
print(newCb)
print(replaceFa)
print(replaceFb)
print(replaceMa)
print(replaceMb)
file = io.open(filepath,'r+')
function lines_from(filepath)
lines = {}
for line in io.lines(filepath) do
lines[#lines + 1] = line
end
return lines
end
local lines = lines_from(filepath)
for k,v in ipairs(lines) do
if v == replaceFa then
file:write(newCa..'\n')
elseif v == replaceFb then
file:write(newCb..'\n')
elseif v == replaceMa then
file:write(newCa..'\n')
elseif v == replaceMb then
file:write(newCb..'\n')
else
file:write(v..'\n')
end
--('[' .. k .. ']', v)
end
--replaceF = {[a] = newCa, [b] = newCb}
--replaceM = {[a] = newCa, [b] = newCb}
--file:write(replaceF)
--file:write(replaceM)
--print(tostring(theData.theSchool.theFemales.theClassroom.a))
file:close()
file = io.open(filepath,'r')
--Did it work?
print("New Values:")
print(theData.theSchool.theTeachers.theClassroom.a)
print(theData.theSchool.theTeachers.theClassroom.b)
print(theData.theSchool.theFemales.theClassroom.a)
print(theData.theSchool.theFemales.theClassroom.b)
print(theData.theSchool.theMales.theClassroom.a)
print(theData.theSchool.theMales.theClassroom.b)```
> I'll remove all the print things after it works.
try this solution, loading the table in one read of the file will be faster, and writing is also better with one command write
--- read
local handle = io.open("data.lua",'rb')
local data = handle:read("*a")
handle:close()
data = data .. "\n return theData"
local t = loadstring(data)()
-- edit
theData.theSchool.theTeachers.theClassroom.a = theData.theSchool.theTeachers.theClassroom.a + 1
-- write
local function concat(t, r)
r = r or {}
for k,v in pairs(t) do
if type(v)=="table" then
r[#r+1] = string.format('\t["%s"]={\n',k )
concat(v, r)
r[#r+1] = "\t},\n"
else
r[#r+1] = string.format('\t\t["%s"]=%03s,\n',k ,v )
end
end
return r
end
local r = concat(t)
local text = "theData = { \n " .. table.concat(r) .. "}"
print(text) -- just control
local handle = io.open("data.lua",'wb')
local data = handle:write(text)
handle:close()

Spawn specific objects from table in for loop - Corona

I have a table of objects that I spawn into a scrollview space, but at the moment its picking randomly when I would actually like to actually spawn in specific sets, for example:
[1] [2] [3] [1] [2] [3] [1] [2] [3] across the loop number.
I understand it would be something to do with removing the math.random to spawn 1 random object from the table, but I'm not sure how I could code it to do it in order of the table instead. Maybe its something simple I missed.
spawn table
local colorsData = {
{name = "Blue", img = "images/RectangleBlue#2x.png"},
{name = "Red", img = "images/RectangleRed#2x.png"},
{name = "Green", img = "images/RectangleGreen#2x.png"}
}
For loop
local spaceApart = 100
for idx = 1,11 do
local c = math.random(1, #colorsData)
local cd = colorsData[c]
local s = display.newImageRect(cd.img, 106,60)
s.name = cd.name
s.x = (idx * spaceApart)
s.y = (scrollView.height / 2)
physics.addBody(s, { isSensor = true })
s:addEventListener ("tap", levelTapped)
scrollView:insert(s)
end

lua Printing specific key/value pairs in table

I have an external lua table that is structured as follows:
sgeT = {
[2535047] = {
{
["account"] = "TG-MCB110105",
["exec"] = "/share/home/00288/tg455591/NAMD_2.8b3/NAMD_2.8b3_Linux-x86_64-MVAPICH-Intel-Ranger/namd2",
["execEpoch"] = 1305825864,
["execModify"] = "Thu May 19 12:24:24 2011",
["execType"] = "user:binary",
["jobID"] = "2535047",
["numCores"] = "128",
["numNodes"] = "8",
pkgT = {
},
["runTime"] = "65125",
["sha1"] = "e157dd510a7be4d775d6ceb271373ea24e7f9559",
sizeT = {
["bss"] = "104552",
["data"] = "192168",
["text"] = "10650813",
},
["startEpoch"] = "1335843433",
["startTime"] = "Mon Apr 30 22:37:13 2012",
["user"] = "guo",
},
},
[2535094] = {
{
["account"] = "TG-MCB110105",
["exec"] = "/share/home/00288/tg455591/NAMD_2.8b3/NAMD_2.8b3_Linux-x86_64-MVAPICH-Intel-Ranger/namd2",
["execEpoch"] = 1305825864,
["execModify"] = "Thu May 19 12:24:24 2011",
["execType"] = "user:binary",
["jobID"] = "2535094",
["numCores"] = "128",
["numNodes"] = "8",
pkgT = {
},
["runTime"] = "81635",
["sha1"] = "e157dd510a7be4d775d6ceb271373ea24e7f9559",
sizeT = {
["bss"] = "104552",
["data"] = "192168",
["text"] = "10650813",
},
["startEpoch"] = "1335823028",
["startTime"] = "Mon Apr 30 16:57:08 2012",
["user"] = "guo",
},
},
I am trying to use the following lua script to print the exec key/value pair as follows:
function DeepPrint (e)
if type(e) == "table" then
for k,v in pairs(e) do
if k == "exec" then
print(k)
DeepPrint(v)
end
end
else
print(e)
end
end
FileStr = "lariatData-sgeT-2012-05-01_2.lua"
Hnd, ErrStr = io.open(FileStr, "r")
if Hnd then
dofile(FileStr)
for Str in Hnd:lines() do
DeepPrint(sgeT)
end
Hnd.close()
else
print(ErrStr, "\n")
end
Ideally, I would like to print the numerical indices and exec values, such as:
2535047 execVal
However, nothing returns when I run the code. Originally the numerical indices were not enclosed in square brackets, but I added them to enable the file to be read. However, given that they are not sequential, I cannot loop through them like an array, yet I believe that these numerical indices may be the source of my problems. I am not sure what is wrong with the code I have, but it returns nothing. Can anyone recommend how I can fix the code so that I can get the appropriate keys and values to return? Thanks in advance!!!
Since your table has a fixed structure, you can simply use the syntactical sugar sgeT[key1][key2] to access exec key.
for i, v in pairs( sgeT ) do
print( i, v[1].exec )
end
You are iterating over lines in the file, but you already processed and loaded that file (as a Lua chunk), so it's no longer needed. Just do this:
dofile(FileStr)
DeepPrint(sgeT)
The main issue is that you only call DeepPrint recursively for those keys that have value exec, but none of the keys at the first level do (so nothing gets printed as you didn't go beyond the first level). You probably need to close if before calling DeepPrint:
function DeepPrint (e)
if type(e) == "table" then
for k,v in pairs(e) do
if k == "exec" then
print(k)
end
DeepPrint(v)
end
else
print(e)
end
end

Resources