Lua-Logging data from Device to a file-Excel- Lua scripts - lua

I have the following Lua script that collects temperature values from a device and I would like to log the output data below to an excel spreadsheet. Any help would be greatly appreciated.
if globalsFile == nil then
dofile("globals.lua")
end
if utilFile == nil then
dofile("util.lua")
end
heaterDuration = 0
heaterInterval = 2
heaterTimeout = 20
index = 1
heater.ON()
print("The heaters have been turned on")
print("Temperatures will be updated below every " .. heaterInterval .. " seconds")
print("Item,Time Point,Top,Bottom,Ambient")
tempIncrease = 'n'
while (heaterDuration < heaterTimeout) do
topTemp = heater.top()
bottomTemp = heater.bottom()
ambientTemp = temperature.ambient()
print(index .. "," .. heaterDuration .. "," .. topTemp .. "," .. bottomTemp .. "," .. ambientTemp)
heaterDuration = heaterDuration + heaterInterval
os.sleep(heaterInterval * 1000)
end
Output
Item,Time Point,Top,Bottom,Ambient
1,0,37.022136688232,37.202819824219,28.257425308228
1,2,37.022136688232,37.202819824219,28.282178878784
1,4,37.022136688232,37.202819824219,28.282178878784
1,6,37.022136688232,37.202819824219,28.282178878784
1,8,37.022136688232,37.202819824219,28.282178878784
1,10,37.022136688232,37.202819824219,28.282178878784
1,12,37.022136688232,37.202819824219,28.282178878784
1,14,37.022724151611,37.202819824219,28.282178878784
1,16,37.022136688232,37.202819824219,28.282178878784
1,18,37.022136688232,37.202819824219,28.282178878784```

If you replace the while loop with something like this, depending on the environment that your Lua runs in, you should be creating a CSV file, which is a readable plain text file with literally just values (or strings, but then it can get more complicated) values separated by commas, or tabs, but let's stick to commas here.
The biggest differences are the creation of the mycsv file object, switchin the print to mycsv:write() (while making sure there is a newline), and then closing (and maybe flushing unwritten data) the file object at the end.
mycsv = io.open("mydata.csv", "w")
mycsv:write("Item,Time Point,Top,Bottom,Ambient\n")
while (heaterDuration < heaterTimeout) do
topTemp = heater.top()
bottomTemp = heater.bottom()
ambientTemp = temperature.ambient()
mycsv:write(index .. "," .. heaterDuration .. "," .. topTemp .. "," ..
bottomTemp .. "," .. ambientTemp .. "\n")
heaterDuration = heaterDuration + heaterInterval
os.sleep(heaterInterval * 1000)
end
mycsv:close()
See also: https://luabyexample.org/docs/files/

Related

fix error attempt to perform arithmetic (add) on string

if (hit.Name == "Base") then return end
hit:BreakJoints()
if (hit.Anchored == true) then hit.Anchored = false end
wait(.5)
for i=1, 10 do
hit.Transparency = hit.Transparency + 0.1
wait(0.2)
end
print("removing" + hit:GetFullName()) <---- here
hit:remove()
end
connection = script.Parent.Touched:connect(onTouched)
but i got " attempt to perform arithmetic (add) on string error "in line 10 can you fix this error pls?
if hit:GetFullName() is returning a string, in Lua, we use two dots .. to concatenate two strings instead of the plus +:
print("removing " .. hit:GetFullName())

lua torch, how to get the print() output into a string

require 'nn'
criterion = nn.ClassNLLCriterion()
print(criterion)
this outputs
nn.ClassNLLCriterion
{
sizeAverage : true
output : 0
gradInput : DoubleTensor - empty
output_tensor : DoubleTensor - size: 1
target : LongTensor - size: 1
total_weight_tensor : DoubleTensor - size: 1
}
I would like to get this print output for logging purposes. Does anyone know how to do that?
Hmm I'm not sure how you get this output. When I run this code I get nn.ClassNLLCriterion. Maybe different Lua/Torch versions?
Anyway, if you want to have this info in a string, you might have to extract it yourself. This can easily be done doing a simple loop:
for k,v in pairs(criterion) do
print(k,v)
end
If you want the fancy print output then I suggest you look at TREPL's code (like #nobody suggested in the comments). It's all in Lua so it's very easy to replicate. More precisely, I recommend their sizestr(), print_new() and printvar() functions. Simply change them so instead of printing, they construct a string.
A quick example using their sizestr function:
-- Copy/Paste from trepl/init.lua
local function sizestr(x)
local strt = {}
if _G.torch.typename(x):find('torch.*Storage') then
return _G.torch.typename(x):match('torch%.(.+)') .. ' - size: ' .. x:size()
end
if x:nDimension() == 0 then
table.insert(strt, _G.torch.typename(x):match('torch%.(.+)') .. ' - empty')
else
table.insert(strt, _G.torch.typename(x):match('torch%.(.+)') .. ' - size: ')
for i=1,x:nDimension() do
table.insert(strt, x:size(i))
if i ~= x:nDimension() then
table.insert(strt, 'x')
end
end
end
return table.concat(strt)
end
local function sutoringu(elem)
local str = ''
if torch.isTensor(elem) then
str = sizestr(elem)
else
str = tostring(elem)
end
return str
end
local str = '{\n'
local tab = ' '
for k,v in pairs(criterion) do
str = str .. tab .. k .. ' : ' .. sutoringu(v) .. '\n'
end
str = str .. '}'
print(str)
This outputs the same thing as what you wished for, constructing a string in the process. It's far from optimal but it's a start.

How to separate brackets in ruby?

I've been using the following code for the problem. I'm making a program to change the IUPAC name into structure, so i want to analyse the string entered by the user.In IUPAC name there are brackets as well. I want to extract the compound name as per the brackets. The way I have shown in the end.
I want to modify the way such that the output comes out to be like this and to be stored in an array :
As ["(4'-cyanobiphenyl-4-yl)","5-[(4'-cyanobiphenyl-4-yl)oxy]",
"({5-[(4'-cyanobiphenyl-4-yl)oxy]pentyl}" .... and so on ]
And the code for splitting which i wrote is:
Reg_bracket=/([^(){}\[\]]*)([(){}\[\]])/
attr_reader :obrk, :cbrk
def count_level_br
#xbrk=0
#cbrk=0
if #temp1
#obrk+=1 if #temp1[1]=="(" || #temp1[1]=="[" ||#temp1[1]=="{"
#obrk-=1 if #temp1[1]==")" || #temp1[1]=="]" ||#temp1[1]=="}"
end
puts #obrk.to_s
end
def split_at_bracket(str=nil) #to split the brackets according to Regex
if str a=str
else a=self
end
a=~Reg_bracket
if $& #temp1=[$1,$2,$']
end
#temp1||=[a,"",""]
end
def find_block
#obrk=0 , r=""
#temp1||=["",""]
split_at_bracket
r<<#temp1[0]<<#temp1[1]
count_level_br
while #obrk!=0
split_at_bracket(#temp1[2])
r<<#temp1[0]<<#temp1[1]
count_level_br
puts r.to_s
if #obrk==0
puts "Level 0 has reached"
#puts "Close brackets are #{#cbrk}"
return r
end
end #end
end
end #class end'
I ve used the regex to match the brackets. And then when it finds any bracket it gives the result of before match, after match and second after match and then keeps on doing it until it reaches to the end.
The output which I m getting right now is this.
1
2
1-[(
3
1-[({
4
1-[({5-[
5
1-[({5-[(
4
1-[({5-[(4'-cyanobiphenyl-4-yl)
3
1-[({5-[(4'-cyanobiphenyl-4-yl)oxy]
2
1-[({5-[(4'-cyanobiphenyl-4-yl)oxy]pentyl}
1
1-[({5-[(4'-cyanobiphenyl-4-yl)oxy]pentyl}oxy)
0
1-[({5-[(4'-cyanobiphenyl-4-yl)oxy]pentyl}oxy)carbonyl]
Level 0 has reached
testing ends'
I have written a simple program to match the string using three different regular expressions. The first one will help separate out the parenthesis, the second will separate out the square brackets and the third will give the curly braces. Here is the following code. I hope you will be able to use it in your program effectively.
reg1 = /(\([a-z0-9\'\-\[\]\{\}]+.+\))/ # for parenthesis
reg2 = /(\[[a-z0-9\'\-\(\)\{\}]+.+\])/ # for square brackets
reg3 = /(\{[a-z0-9\'\-\(\)\[\]]+.+\})/ # for curly braces
a = Array.new
s = gets.chomp
x = reg1.match(s)
a << x.to_s
str = x.to_s.chop.reverse.chop.reverse
while x != nil do
x = reg1.match(str)
a << x.to_s
str = x.to_s.chop
end
x = reg2.match(s)
a << x.to_s
str = x.to_s.chop.reverse.chop.reverse
while x != nil do
x = reg2.match(str)
a << x.to_s
str = x.to_s.chop
end
x = reg3.match(s)
a << x.to_s
str = x.to_s.chop.reverse.chop.reverse
while x != nil do
x = reg3.match(str)
a << x.to_s
str = x.to_s.chop
end
puts a
The output is a follows :
ruby reg_yo.rb
4,4'{-1-[({5-[(4'-cyanobiphenyl-4-yl)oxy]pentyl}oxy)carbonyl]-2-[(4'-cyanobiphe‌​nyl-4-yl)oxy]ethylene}dihexanoic acid # input string
({5-[(4'-cyanobiphenyl-4-yl)oxy]pentyl}oxy)carbonyl]-2-[(4'-cyanobiphe‌​nyl-4-yl)
(4'-cyanobiphenyl-4-yl)oxy]pentyl}oxy)
(4'-cyanobiphenyl-4-yl)
[({5-[(4'-cyanobiphenyl-4-yl)oxy]pentyl}oxy)carbonyl]-2-[(4'-cyanobiphe‌​nyl-4-yl)oxy]
[(4'-cyanobiphenyl-4-yl)oxy]pentyl}oxy)carbonyl]
[(4'-cyanobiphenyl-4-yl)oxy]
{-1-[({5-[(4'-cyanobiphenyl-4-yl)oxy]pentyl}oxy)carbonyl]-2-[(4'-cyanobiphe‌​nyl-4-yl)oxy]ethylene}
{5-[(4'-cyanobiphenyl-4-yl)oxy]pentyl}
Update : I have modified the code so as to search for recursive patterns.

How can I print a joined table of strings in Lua?

Okay I am working on a script for my Oxide Lua Plugin, and I am also just learning Lua Script so I am not real sure how to do this.
-- *******************************************
-- Broadcasts a Server Notification
-- *******************************************
function PLUGIN:cmdNotice( netuser, args )
table.concat(args," ")
local allnetusers = rust.GetAllNetUsers()
if (allnetusers) then
for i=1, #allnetusers do
local netuser = allnetusers[i]
rust.Notice(netuser, args[1]))
rust.SendChatToUser(netuser, "Message Sent:" .. args[1])
end
end
end
What I am trying to do is fix this so I do not have to manually encase my notice in "".
For example, as the code stands, while I am in game in rust if I use the /notice command I have two outcomes.
Example 1
/notice hello everone
will only produce
hello
but if I do
/notice "hello everyone"
will give the entire message. So I am a little confused.
So my new code should look like this
-- *******************************************
-- Broadcasts a Server Notification
-- *******************************************
function PLUGIN:cmdNotice( netuser, args )
table.concat(args," ")
local allnetusers = rust.GetAllNetUsers()
if (allnetusers) then
for i=1, #allnetusers do
local netuser = allnetusers[i]
rust.Notice(netuser, table.concat(args, " " ))
rust.SendChatToUser(netuser, "Message Sent:" .. table.concat(args, " "))
end
end
end
Edit 3/15/2014
Okay cool so in a since I can also do this as well correct?
function PLUGIN:cmdNotice( netuser, args )
if (not args[1]) then
rust.Notice( netuser, "Syntax: /notice Message" )
return
end
local allnetusers = rust.GetAllNetUsers()
if allnetusers then
for i=1, #allnetusers do
local netuser = allnetusers[i]
local notice_msg = table.concat(args," ")
rust.Notice(netuser, notice_msg)
rust.SendChatToUser(netuser, "Message Sent:" .. notice_msg)
end
end
end
To clarify what #EgorSkriptunoff said, table.concat returns the joined table, but it does not change the value of args. Since you don't save the joined return value, your line 1 inside the function is useless. As an alternative to his approach, you could do rust.SendChatToUser ( netuser, "Message Sent:" .. table.concat(args, " " ).
My guess is that you were thinking (?) that the joined strings would be saved in the args table as the first item in the table? That's not what happens. The table itself remains unchanged, so when you print args[1], you get only the first string of the array. It "works" when you quote the message because in that case the entire message goes in as one thing, and the array only has an arg[1].
Here's what is going on
t = { "hello", "I", "must", "be", "going"}
-- Useless use of concat since I don't save the return value or use it
table.concat(t, " ")
print(t) -- Still an unjoined table
print(t[1]) -- Prints only "hello"
print(table.concat(t, " ")) -- Now prints the return value
Edit: In response to the follow-up question, see my comments in the code below:
function PLUGIN:cmdNotice( netuser, args )
table.concat(args," ") -- This line is not needed.
local allnetusers = rust.GetAllNetUsers()
-- Lua doesn't count 0 as false, so the line below probably doesn't do
-- what you think it does. If you want to test whether a table has more
-- than 0 items in it, use this:
-- if #allnetusers > 0 then...
if allnetusers then
for i=1, #allnetusers do
local netuser = allnetusers[i]
rust.Notice(netuser, table.concat(args, " " ))
rust.SendChatToUser(netuser, "Message Sent:" .. table.concat(args, " "))
end
end
end

string replacement in Ruby: greentexting support for imageboard

I'm trying to have greentext support for my Rails imageboard (though it should be mentioned that this is strictly a Ruby problem, not a Rails problem)
basically, what my code does is:
1. chop up a post, line by line
2. look at the first character of each line. if it's a ">", start the greentexting
3. at the end of the line, close the greentexting
4. piece the lines back together
My code looks like this:
def filter_comment(c) #use for both OP's and comments
c1 = c.content
str1 = '<p class = "unkfunc">' #open greentext
str2 = '</p>' #close greentext
if c1 != nil
arr_lines = c1.split('\n') #split the text into lines
arr_lines.each do |a|
if a[0] == ">"
a.insert(0, str1) #add the greentext tag
a << str2 #close the greentext tag
end
end
c1 = ""
arr_lines.each do |a|
strtmp = '\n'
if arr_lines.index(a) == (arr_lines.size - 1) #recombine the lines into text
strtmp = ""
end
c1 += a + strtmp
end
c2 = c1.gsub("\n", '<br/>').html_safe
end
But for some reason, it isn't working! I'm having weird things where greentexting only works on the first line, and if you have greentext on the first line, normal text doesn't work on the second line!
Side note, may be your problem, without getting too in depth...
Try joining your array back together with join()
c1 = arr_lines.join('\n')
I think the problem lies with the spliting the lines in array.
names = "Alice \n Bob \n Eve"
names_a = names.split('\n')
=> ["Alice \n Bob \n Eve"]
Note the the string was not splited when \n was encountered.
Now lets try this
names = "Alice \n Bob \n Eve"
names_a = names.split(/\n/)
=> ["Alice ", " Bob ", " Eve"]
or This "\n" in double quotes. (thanks to Eric's Comment)
names = "Alice \n Bob \n Eve"
names_a = names.split("\n")
=> ["Alice ", " Bob ", " Eve"]
This got split in array. now you can check and append the data you want
May be this is what you want.
def filter_comment(c) #use for both OP's and comments
c1 = c.content
str1 = '<p class = "unkfunc">' #open greentext
str2 = '</p>' #close greentext
if c1 != nil
arr_lines = c1.split(/\n/) #split the text into lines
arr_lines.each do |a|
if a[0] == ">"
a.insert(0, str1) #add the greentext tag
# Use a.insert id you want the existing ">" appended to it <p class = "unkfunc">>
# Or else just assign a[0] = str1
a << str2 #close the greentext tag
end
end
c1 = arr_lines.join('<br/>')
c2 = c1.html_safe
end
Hope this helps..!!
I'm suspecting that your problem is with your CSS (or maybe HTML), not the Ruby. Did the resulting HTML look correct to you?

Resources