Separate string into table of words and spaces between - lua

I am currently working on a lua script that takes in a string and separates it into a table of words and the spaces + characters between the words.
Example:
-- convert this
local input = "This string, is a text!"
-- to this
local output = {
"This", " ", "string", ", ", "is", " ", "a", " ", "text", "!"
}
I tried solving this with lua's pattern implementation, but wasn't successful so far.
Any help is highly appreciated!

local function splitter(input)
local result = {}
for non_word, word, final_non_word in input:gmatch "([^%w]*)(%w+)([^%w]*)" do
if non_word ~= '' then
table.insert(result, non_word)
end
table.insert(result, word)
if final_non_word ~= '' then
table.insert(result, final_non_word)
end
end
return result
end

Related

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

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/

How to write a star pattern program in lua?

The following code is printing the pattern in one line:
for i=6, 1, -1 do
for j=1, i, 1 do
print("*")
end
print(" \n ")
end
Try This:
Instead of print use io.write()
for i=6,1,-1 do
for j=1,i,1 do
io.write('*')
end
print( " \n ")
end

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 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

Print to a file using a variable as SQL active record column name?

Here is my psudocode example:
Mydb.find_by_sql("...").each do |data|
.
.
aFile.print(data.time.to_f, " ", data.column_name, "\n")
My question is how can I use a variable for the column_name? I thought something like:
aFile.print(data.time.to_f, " ", data.#{column_name}, "\n")
or
aFile.print(data.time.to_f, " ", data.'#{column_name}', "\n")
or
aFile.print(data.time.to_f, " ", data."#{column_name}", "\n")
but these didn't work.
Any ideas?
You could try
data.send('column_name')
So if the ActiveRecord returned has an attribute 'foo'
puts(data.foo)
is the same as
puts(data.send('foo'))
UPDATE RE your comment.
#x = X.find(1)
['date','age','sex'].each do |attr|
puts "The value of #{attr} is #{#x.send(attr)}"
end

Resources