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

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")`.

Related

Can't set the data to a comboBox choice

it has been days I'm trying to create a comboBox with all available models.
The code is this
for name , models in SortedPairs( player_manager.AllValidModels() ) do
print("name: "..name.." model: "..models)
custCbox:AddChoice(name , models , false)
end
I tried to print every name and model to know if I was wrong, but that's ok: name prints the display name and models prints the path.
The OnSelect function is this:
custCbox.OnSelect = function( index, value, data )
modelPanel:SetModel( data )
print("Data " .. data)
print("Value " .. value)
end
Data gives the display name and value gives a number.
Why?
From the DComboBox documentation:
local cbox = vgui.Create( "DComboBox", BGPanel )
...
cbox:AddChoice( "Pink", Color( 255, 0, 255 ) )
function cbox:OnSelect( index, text, data )
-- Set background panel color
BGPanel:SetBackgroundColor( data )
end
Note the difference to your
custCbox.OnSelect = function( index, value, data )
modelPanel:SetModel( data )
print("Data " .. data)
print("Value " .. value)
end
which is equivalent to
function custCbox.onSelect(index, value, data)
-- ...
end
And the example that uses the colon syntax.
function cbox:OnSelect(index, text, data)
end
is equivalent to
function cbox.OnSelect(self, index, text, data)
end
This difference causes a parameter shift by one. So what you think is index is actually your combobox, text is the selected index and data is the choices text.
Please read
Lua 5.4 Reference Manual: 3.4.10 Function Calls
Lua 5.4 Reference Manual: 3.4.11 Function Definitions
This is a very common mistake among beginners.

Lua: "attempt to concatenate global" Error in MPV

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'")

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

String compatibility error, attempt to index a nil value

I am using Gideros and getting this error:
main.lua:47: attempt to index a nil value
stack traceback:
main.lua:47: in function 'func'
[string "compatibility.lua"]:36: in function <[string "compatibility.lua"]:35>
I have this piece of code and as soon as the text is displayed, it gives me the above mentioned error:How can I fix this?
function onEnter()
function youLoose()
local font2 = TTFont.new("billo.ttf", 20, "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
LooserText = TextField.new(font2, "You Loose , Try AGAIN?")
LooserText:setPosition(100, 100)
stage:addChild(LooserText)
Timer = Timer.delayedCall(1000, removing)
end --line 36
end
function removing()
LooserText:getParent():removeChild(LooserText) --line 47
end
The index nil error means that on that line you are probably getting nil as a return value from LooserText:getParent().
Why you would be getting nil for that I can't tell you other than presumably because it doesn't have one.
The documentation indicates that there is no error condition for Stage.addChild except that the object added must be a Sprite. TextField inherits Sprite so there is no apparent reason for you to get this error. However, you should not re-assign the return value of delayedCall to a global variable of same name as the Timer class, this could affect other parts of the application. Since you don't use the returned Timer instance, I have removed the assignment. Also, if the stage:addChild succeeded then the removing can use stage. One thing that is strange is that your onEnter just defines youLose() but does not call it or return it, is this part of code you ommitted? In any case, you need to add some sanity checks to verify that what you think is happening is really happening w/r/t child add/remove:
function onEnter()
function youLoose()
local font2 = TTFont.new("billo.ttf", 20, "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
LoserText = TextField.new(font2, "You Lose , Try AGAIN?")
LoserText:setPosition(100, 100)
print('Stage num children:' .. stage:getNumChildren())
stage:addChild(LoserText)
print('Stage num children:' .. stage:getNumChildren())
print('LoserText is stage child #' .. stage:getChildIndex(LoserText))
Timer.delayedCall(1000, removing)
end
end
function removing()
print('Stage num children:' .. stage:getNumChildren())
print('LoserText is stage child #' .. stage:getChildIndex(LoserText))
stage:removeChild(LoserText)
print('Stage num children:' .. stage:getNumChildren())
end

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