Lua: "attempt to concatenate global" Error in MPV - lua

I am trying to write a little script to output filetags in mpv. My script looks like this:
require 'os'
require 'string'
function displayTrack()
currentTrack = mp.get_property("metadata/by-key/Title")
currentArtist = mp.get_property("metadata/by-key/Artist")
currentAlbum = mp.get_property("metadata/by-key/Album")
print(currentArtist)
print(currentAlbum)
print(currentTrack)
if currentTrack == nil then
os.execute("terminal-notifier -title '" .. currentArtist .. "' -message 'Unknown Title'")
else
os.execute("terminal-notifier -title '" .. currentArtist .. "' -message '" .. currentAlbum .. " - " .. currentTrack .. "'")
end
end
mp.observe_property("eof-reached", "bool", displayTrack)
Catching the tags and printing them works with every tested title. But if i want to uncomment the 5 lines starting with "if currentTrack == nil ..." so it also dislpays a native notification i get the LUA error:
/Users/marcel/.config/mpv/scripts/notification.lua:15: attempt to concatenate global 'currentArtist' (a nil value)
Can somebody tell me why i can print the string but not forward it to the os.execute?

It is not os.execute, it is concatenation - .. - that can't work with nil. And yes, you can print standalone nil just fine. In your case not only currentTrack is nil, but currentArtist too, so you can't build a string with it. Consider if you even need those entries where you don't have value for currentArtist and either skip them, provide alternative if branch to do something else or provide some default in concatenation. Usual idiom is (currentArtist or '') - here your default will be empty string.

if currentTrack == nil then
os.execute("terminal-notifier -title '" .. currentArtist .. "' -message 'Unknown Title'")
If this branch gets executed, currentTrack is nil, thus the concatenation fails as stated by the error message.
Just get rid of the concatenation all together:
if currentTrack == nil then
os.execute("terminal-notifier -title -message 'Unknown Title'")

Related

NSIS split enviromental variable

I can read and use the env var with NSIS:
!define var "$%envvar%"
For example envvar contains some string "word anotherword thirdword" so I need to split it by this words and use it while compiling.
!if $"var1" == "word"
...some code
!else if $"var2" == "anotherword"
...some code
!endif
Can I do it with NSIS?
String handling in the pre-compiler is somewhat limited but this works:
!define var "word anotherword thirdword"
!searchparse /noerrors "IGNORED ${var}" ' ' var1 ' ' var2 ' ' var3
!warning "Debug: 1=${var1}"
!warning "Debug: 2=${var2}"
!warning "Debug: 3=${var3}"
!if "${var1}" == "word"
!else if "${var2}" == "anotherword"
!endif
Anything more advanced might require calling batch for with !system and outputting to a .nsh you can include.

Lua - util_server.lua:440 attempt to index local 'self' (a nil value)

Good evening
Will you help me solve this problem?
ERROR: race/util_server.lua:440: attempt to index local 'self' (a nil value)
function string:split(separator)
if separator == '.' then
separator = '%.'
end
local result = {}
for part in self:gmatch('(.-)' .. separator) do
result[#result+1] = part
end
result[#result+1] = self:match('.*' .. separator .. '(.*)$') or self
return result
end
You're probably calling it wrong.
function string:split(separator)
Is short hand for:
function string.split(self, separator)
Given a string and separator:
s = 'This is a test'
separator = ' '
You need to call it like this:
string.split(s, separator)
Or:
s:split(separator)
If you call it like this:
s.split(separator)
You're failing to provide a value for the self argument.
Side note, you can write split more simply like this:
function string:split(separators)
local result = {}
for part in self:gmatch('[^'..separators..']+') do
result[#result + 1] = part
end
return result
end
This has the disadvantage that you can't used multi-character strings as delimiters, but the advantage that you can specify more than one delimiter. For instance, you could strip all the punctuation from a sentence and grab just the words:
s = 'This is an example: homemade, freshly-baked pies are delicious!'
for _,word in pairs(s:split(' :.,!-')) do
print(word)
end
Output:
This
is
an
example
homemade
freshly
baked
pies
are
delicious

Table printing nil on Lua

I have this code written in Lua, it's just an example code, because the actual one I'm using is bigger than this, but this is the part I'm having problems.
Does anyone know why when I try to print what's inside the table t I get nil as result?
t = {
{name="John",sex="M",age=19},
{name="Susan",sex="F",age=20}
}
for _ in ipairs(t) do
print("NAME: " .. t.name)
print("SEX: " .. t.sex)
print("AGE: " .. t.age)
print("\n")
end
I mean, this is the result I get when I run the code:
attempt to concatenate field 'name' (a nil value)
Iterating over t doesn't change t. You need to specify where to put the values you are iterating over, and use those variables.
local t = {
{name="John",sex="M",age=19},
{name="Susan",sex="F",age=20}
}
for index, value in ipairs(t) do
print("NAME: " .. value.name)
print("SEX: " .. value.sex)
print("AGE: " .. value.age)
print("\n")
end

Attempt to call field 'defaultName' (a string value) error

I'm getting a strange Attempt to call field 'defaultName' (a string value) when i add " some more text " to my code below:
--
alert = native.showAlert( "saved!", "Your score is saved to " ..defaultName " some more text " ..allScore_txt , { "Done" }, onComplete )
--
any idea how to fix this ?
You missed a .. after defaultName and so Lua thinks you mean a function call, hence the error message. Lua allows function calls in the form identifier"string" as shorthand for identifier("string")`.

Lua Script Error

Situation:
I want to save the record of a data which is a value of the sensor in the certain file.
Code is..
--Header file
require("TIMER")
require("IPBOX")
require("ANALOG_IN")
require("LOG")
function OnExit()
print("Exit code...do something")
end
function main()
timer = "Timer"
local analogsensor_1 = "AIR_1"
local analogsensor_2 = "AIR_2"
local timestr = os.data("%Y-%m-%d %H:%M:%S")
-- open the file for writing binary data
local filehandle = io.open("collection_of_data.txt", "a")
while true do
valueOfSensor_1 = ANALOG_IN.readAnalogIn(analogsensor_1);
valueOfSensor_2 = ANALOG_IN.readAnalogIn(analogsensor_2);
if (valueOfSensor_1 > 0 and valueOfSensor_2 > 0) then
-- save values of sensors
filehandle:write(timestr, " -The Value of the Sensors: ", tostring(valueOfSensor_1), tostring(valueOfSensor_2)"\n");
-- save values using rolling log appender:
LOG.log_event( ScenarioLoggerDevicenameInDeviceList, " -The Value of the Sensors: ", tostring(valueOfSensor_1), tostring(valueOfSensor_2), "any other string you wish to add", "etc", "etc")
LOG.log_event( ScenarioLoggerDevicenameInDeviceList, " -The Value of the Sensors: ", tostring(valueOfSensor_1))
print("Hello3"..valueOfSensor_1)
end
TIMER.sleep(timer,500)
end
-- close the file
filehandle:close()
end
print("start main")
main()
In this line:
filehandle:write(timestr, " -The Value of the Sensors: ", tostring(valueOfSensor_1), tostring(valueOfSensor_2)"\n");
I get an error:
"attemp to index global 'filehandle' (a nil value)"
How can I fix it?
io.open returns nil if it cannot open the file. This can be due to "file not found", "permissions denied" and maybe other reasons. To figure out the problem, io.open has a second return value, which lets you inspect the error (in fact, it even returns a third value, which is an error-code integer - but its meaning is system dependent).
Change:
local filehandle = io.open("collection_of_data.txt", "a")
to
local filehandle, message = io.open("collection_of_data.txt", "a")
if not filehandle then
print(message)
end
You can also use the following Lua idiom:
local filehandle = assert(io.open("collection_of_data.txt", "a"))
This will do the same. If the first argument to assert is nil, then the second argument (the second return value of io.open will be printed. If the first argument is not nil, it will simply be returned.

Resources